blob: 92997ecafde1d0d22ec21d0871c71fa9dd0f17b6 [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
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Douglas Gregord1702062010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000023#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000024#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000026#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000027#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000029#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000031#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000033#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Designator.h"
35#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000036#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000037#include "clang/Sema/ParsedTemplate.h"
John McCallde6836a2010-08-24 07:21:54 +000038#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000039using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000040using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000041
David Chisnall9f57c292009-08-17 16:35:33 +000042
Douglas Gregor171c45a2009-02-18 21:56:37 +000043/// \brief Determine whether the use of this declaration is valid, and
44/// emit any corresponding diagnostics.
45///
46/// This routine diagnoses various problems with referencing
47/// declarations that can occur when using a declaration. For example,
48/// it might warn if a deprecated or unavailable declaration is being
49/// used, or produce an error (and return true) if a C++0x deleted
50/// function is being used.
51///
Chris Lattnerb7df3c62009-10-25 22:31:57 +000052/// If IgnoreDeprecated is set to true, this should not want about deprecated
53/// decls.
54///
Douglas Gregor171c45a2009-02-18 21:56:37 +000055/// \returns true if there was an error (this declaration cannot be
56/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000057///
John McCall28a6aea2009-11-04 02:18:39 +000058bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner4bf74fd2009-02-15 22:43:40 +000059 // See if the decl is deprecated.
Benjamin Kramerbfac7dc2010-10-09 15:49:00 +000060 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>())
61 EmitDeprecationWarning(D, DA->getMessage(), Loc);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000062
Chris Lattnera27dd592009-10-25 17:21:40 +000063 // See if the decl is unavailable
Fariborz Jahanianc74073c2010-10-06 23:12:32 +000064 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) {
65 if (UA->getMessage().empty())
66 Diag(Loc, diag::err_unavailable) << D->getDeclName();
67 else
68 Diag(Loc, diag::err_unavailable_message)
Benjamin Kramerbfac7dc2010-10-09 15:49:00 +000069 << D->getDeclName() << UA->getMessage();
Chris Lattnera27dd592009-10-25 17:21:40 +000070 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
71 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000072
Douglas Gregor171c45a2009-02-18 21:56:37 +000073 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000074 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000075 if (FD->isDeleted()) {
76 Diag(Loc, diag::err_deleted_function_use);
77 Diag(D->getLocation(), diag::note_unavailable_here) << true;
78 return true;
79 }
Douglas Gregorde681d42009-02-24 04:26:15 +000080 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000081
Douglas Gregor171c45a2009-02-18 21:56:37 +000082 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +000083}
84
Fariborz Jahanian027b8862009-05-13 18:09:35 +000085/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +000086/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +000087/// attribute. It warns if call does not have the sentinel argument.
88///
89void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +000090 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000091 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +000092 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +000093 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +000094
95 // FIXME: In C++0x, if any of the arguments are parameter pack
96 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +000097 int sentinelPos = attr->getSentinel();
98 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +000099
Mike Stump87c57ac2009-05-16 07:39:55 +0000100 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
101 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000102 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000103 bool warnNotEnoughArgs = false;
104 int isMethod = 0;
105 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
106 // skip over named parameters.
107 ObjCMethodDecl::param_iterator P, E = MD->param_end();
108 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
109 if (nullPos)
110 --nullPos;
111 else
112 ++i;
113 }
114 warnNotEnoughArgs = (P != E || i >= NumArgs);
115 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000116 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000117 // skip over named parameters.
118 ObjCMethodDecl::param_iterator P, E = FD->param_end();
119 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
120 if (nullPos)
121 --nullPos;
122 else
123 ++i;
124 }
125 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000126 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000127 // block or function pointer call.
128 QualType Ty = V->getType();
129 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000130 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000131 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
132 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000133 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
134 unsigned NumArgsInProto = Proto->getNumArgs();
135 unsigned k;
136 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
137 if (nullPos)
138 --nullPos;
139 else
140 ++i;
141 }
142 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
143 }
144 if (Ty->isBlockPointerType())
145 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000146 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000147 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000148 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000149 return;
150
151 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000152 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000153 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000154 return;
155 }
156 int sentinel = i;
157 while (sentinelPos > 0 && i < NumArgs-1) {
158 --sentinelPos;
159 ++i;
160 }
161 if (sentinelPos > 0) {
162 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000163 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000164 return;
165 }
166 while (i < NumArgs-1) {
167 ++i;
168 ++sentinel;
169 }
170 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000171 if (!sentinelExpr) return;
172 if (sentinelExpr->isTypeDependent()) return;
173 if (sentinelExpr->isValueDependent()) return;
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000174 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000175 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
176 Expr::NPC_ValueDependentIsNull))
177 return;
178
179 // Unfortunately, __null has type 'int'.
180 if (isa<GNUNullExpr>(sentinelExpr)) return;
181
182 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
183 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000184}
185
Douglas Gregor87f95b02009-02-26 21:00:50 +0000186SourceRange Sema::getExprRange(ExprTy *E) const {
187 Expr *Ex = (Expr *)E;
188 return Ex? Ex->getSourceRange() : SourceRange();
189}
190
Chris Lattner513165e2008-07-25 21:10:04 +0000191//===----------------------------------------------------------------------===//
192// Standard Promotions and Conversions
193//===----------------------------------------------------------------------===//
194
Chris Lattner513165e2008-07-25 21:10:04 +0000195/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
196void Sema::DefaultFunctionArrayConversion(Expr *&E) {
197 QualType Ty = E->getType();
198 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
199
Chris Lattner513165e2008-07-25 21:10:04 +0000200 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000201 ImpCastExprToType(E, Context.getPointerType(Ty),
John McCalle3027922010-08-25 11:45:40 +0000202 CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000203 else if (Ty->isArrayType()) {
204 // In C90 mode, arrays only promote to pointers if the array expression is
205 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
206 // type 'array of type' is converted to an expression that has type 'pointer
207 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
208 // that has type 'array of type' ...". The relevant change is "an lvalue"
209 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000210 //
211 // C++ 4.2p1:
212 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
213 // T" can be converted to an rvalue of type "pointer to T".
214 //
215 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
216 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000217 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
John McCalle3027922010-08-25 11:45:40 +0000218 CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000219 }
Chris Lattner513165e2008-07-25 21:10:04 +0000220}
221
Douglas Gregorb92a1562010-02-03 00:27:59 +0000222void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
223 DefaultFunctionArrayConversion(E);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000224
Douglas Gregorb92a1562010-02-03 00:27:59 +0000225 QualType Ty = E->getType();
226 assert(!Ty.isNull() && "DefaultFunctionArrayLvalueConversion - missing type");
227 if (!Ty->isDependentType() && Ty.hasQualifiers() &&
228 (!getLangOptions().CPlusPlus || !Ty->isRecordType()) &&
229 E->isLvalue(Context) == Expr::LV_Valid) {
230 // C++ [conv.lval]p1:
231 // [...] If T is a non-class type, the type of the rvalue is the
232 // cv-unqualified version of T. Otherwise, the type of the
233 // rvalue is T
234 //
235 // C99 6.3.2.1p2:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000236 // If the lvalue has qualified type, the value has the unqualified
237 // version of the type of the lvalue; otherwise, the value has the
Douglas Gregorb92a1562010-02-03 00:27:59 +0000238 // type of the lvalue.
John McCalle3027922010-08-25 11:45:40 +0000239 ImpCastExprToType(E, Ty.getUnqualifiedType(), CK_NoOp);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000240 }
241}
242
243
Chris Lattner513165e2008-07-25 21:10:04 +0000244/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000245/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000246/// sometimes surpressed. For example, the array->pointer conversion doesn't
247/// apply if the array is an argument to the sizeof or address (&) operators.
248/// In these instances, this routine should *not* be called.
249Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
250 QualType Ty = Expr->getType();
251 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000252
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000253 // C99 6.3.1.1p2:
254 //
255 // The following may be used in an expression wherever an int or
256 // unsigned int may be used:
257 // - an object or expression with an integer type whose integer
258 // conversion rank is less than or equal to the rank of int
259 // and unsigned int.
260 // - A bit-field of type _Bool, int, signed int, or unsigned int.
261 //
262 // If an int can represent all values of the original type, the
263 // value is converted to an int; otherwise, it is converted to an
264 // unsigned int. These are called the integer promotions. All
265 // other types are unchanged by the integer promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000266 QualType PTy = Context.isPromotableBitField(Expr);
267 if (!PTy.isNull()) {
John McCalle3027922010-08-25 11:45:40 +0000268 ImpCastExprToType(Expr, PTy, CK_IntegralCast);
Eli Friedman629ffb92009-08-20 04:21:42 +0000269 return Expr;
270 }
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000271 if (Ty->isPromotableIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000272 QualType PT = Context.getPromotedIntegerType(Ty);
John McCalle3027922010-08-25 11:45:40 +0000273 ImpCastExprToType(Expr, PT, CK_IntegralCast);
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000274 return Expr;
Eli Friedman629ffb92009-08-20 04:21:42 +0000275 }
276
Douglas Gregorb92a1562010-02-03 00:27:59 +0000277 DefaultFunctionArrayLvalueConversion(Expr);
Chris Lattner513165e2008-07-25 21:10:04 +0000278 return Expr;
279}
280
Chris Lattner2ce500f2008-07-25 22:25:12 +0000281/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000282/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000283/// double. All other argument types are converted by UsualUnaryConversions().
284void Sema::DefaultArgumentPromotion(Expr *&Expr) {
285 QualType Ty = Expr->getType();
286 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000287
Chris Lattner2ce500f2008-07-25 22:25:12 +0000288 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000289 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
290 return ImpCastExprToType(Expr, Context.DoubleTy,
John McCalle3027922010-08-25 11:45:40 +0000291 CK_FloatingCast);
Mike Stump11289f42009-09-09 15:08:12 +0000292
Chris Lattner2ce500f2008-07-25 22:25:12 +0000293 UsualUnaryConversions(Expr);
294}
295
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000296/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
297/// will warn if the resulting type is not a POD type, and rejects ObjC
298/// interfaces passed by value. This returns true if the argument type is
299/// completely illegal.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000300bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
301 FunctionDecl *FDecl) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000302 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000303
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000304 // __builtin_va_start takes the second argument as a "varargs" argument, but
305 // it doesn't actually do anything with it. It doesn't need to be non-pod
306 // etc.
307 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
308 return false;
309
John McCall8b07ec22010-05-15 11:32:37 +0000310 if (Expr->getType()->isObjCObjectType() &&
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000311 DiagRuntimeBehavior(Expr->getLocStart(),
312 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
313 << Expr->getType() << CT))
314 return true;
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000315
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000316 if (!Expr->getType()->isPODType() &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000317 DiagRuntimeBehavior(Expr->getLocStart(),
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000318 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
319 << Expr->getType() << CT))
320 return true;
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000321
322 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000323}
324
325
Chris Lattner513165e2008-07-25 21:10:04 +0000326/// UsualArithmeticConversions - Performs various conversions that are common to
327/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000328/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000329/// responsible for emitting appropriate error diagnostics.
330/// FIXME: verify the conversion rules for "complex int" are consistent with
331/// GCC.
332QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
333 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000334 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000335 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000336
337 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000338
Mike Stump11289f42009-09-09 15:08:12 +0000339 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000340 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000341 QualType lhs =
342 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000343 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000344 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000345
346 // If both types are identical, no conversion is needed.
347 if (lhs == rhs)
348 return lhs;
349
350 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
351 // The caller can deal with this (e.g. pointer + int).
352 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
353 return lhs;
354
Douglas Gregord2c2d172009-05-02 00:36:19 +0000355 // Perform bitfield promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000356 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000357 if (!LHSBitfieldPromoteTy.isNull())
358 lhs = LHSBitfieldPromoteTy;
Eli Friedman629ffb92009-08-20 04:21:42 +0000359 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000360 if (!RHSBitfieldPromoteTy.isNull())
361 rhs = RHSBitfieldPromoteTy;
362
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000363 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000364 if (!isCompAssign)
John McCalle3027922010-08-25 11:45:40 +0000365 ImpCastExprToType(lhsExpr, destType, CK_Unknown);
366 ImpCastExprToType(rhsExpr, destType, CK_Unknown);
Douglas Gregora11693b2008-11-12 17:17:38 +0000367 return destType;
368}
369
Chris Lattner513165e2008-07-25 21:10:04 +0000370//===----------------------------------------------------------------------===//
371// Semantic Analysis for various Expression Types
372//===----------------------------------------------------------------------===//
373
374
Steve Naroff83895f72007-09-16 03:34:24 +0000375/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000376/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
377/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
378/// multiple tokens. However, the common case is that StringToks points to one
379/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000380///
John McCalldadc5752010-08-24 06:29:42 +0000381ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000382Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000383 assert(NumStringToks && "Must have at least one string!");
384
Chris Lattner8a24e582009-01-16 18:51:42 +0000385 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000386 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000387 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000388
Chris Lattner23b7eb62007-06-15 23:05:46 +0000389 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000390 for (unsigned i = 0; i != NumStringToks; ++i)
391 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000392
Chris Lattner36fc8792008-02-11 00:02:17 +0000393 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000394 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000395 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000396
397 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000398 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000399 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000400
Chris Lattner36fc8792008-02-11 00:02:17 +0000401 // Get an array type for the string, according to C99 6.4.5. This includes
402 // the nul terminator character as well as the string length for pascal
403 // strings.
404 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000405 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000406 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000407
Chris Lattner5b183d82006-11-10 05:03:26 +0000408 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000409 return Owned(StringLiteral::Create(Context, Literal.GetString(),
410 Literal.GetStringLength(),
411 Literal.AnyWide, StrTy,
412 &StringTokLocs[0],
413 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000414}
415
Chris Lattner2a9d9892008-10-20 05:16:36 +0000416/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
417/// CurBlock to VD should cause it to be snapshotted (as we do for auto
418/// variables defined outside the block) or false if this is not needed (e.g.
419/// for values inside the block or for globals).
420///
Douglas Gregor4f13beb2010-03-01 20:44:28 +0000421/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
Chris Lattner497d7b02009-04-21 22:26:47 +0000422/// up-to-date.
423///
Douglas Gregor9a28e842010-03-01 23:15:13 +0000424static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
Chris Lattner2a9d9892008-10-20 05:16:36 +0000425 ValueDecl *VD) {
426 // If the value is defined inside the block, we couldn't snapshot it even if
427 // we wanted to.
428 if (CurBlock->TheDecl == VD->getDeclContext())
429 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000430
Chris Lattner2a9d9892008-10-20 05:16:36 +0000431 // If this is an enum constant or function, it is constant, don't snapshot.
432 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
433 return false;
434
435 // If this is a reference to an extern, static, or global variable, no need to
436 // snapshot it.
437 // FIXME: What about 'const' variables in C++?
438 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000439 if (!Var->hasLocalStorage())
440 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000441
Chris Lattner497d7b02009-04-21 22:26:47 +0000442 // Blocks that have these can't be constant.
443 CurBlock->hasBlockDeclRefExprs = true;
444
445 // If we have nested blocks, the decl may be declared in an outer block (in
446 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
447 // be defined outside all of the current blocks (in which case the blocks do
448 // all get the bit). Walk the nesting chain.
Douglas Gregor9a28e842010-03-01 23:15:13 +0000449 for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
450 BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000451
Douglas Gregor9a28e842010-03-01 23:15:13 +0000452 if (!NextBlock)
453 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000454
Chris Lattner497d7b02009-04-21 22:26:47 +0000455 // If we found the defining block for the variable, don't mark the block as
456 // having a reference outside it.
457 if (NextBlock->TheDecl == VD->getDeclContext())
458 break;
Mike Stump11289f42009-09-09 15:08:12 +0000459
Chris Lattner497d7b02009-04-21 22:26:47 +0000460 // Otherwise, the DeclRef from the inner block causes the outer one to need
461 // a snapshot as well.
462 NextBlock->hasBlockDeclRefExprs = true;
463 }
Mike Stump11289f42009-09-09 15:08:12 +0000464
Chris Lattner2a9d9892008-10-20 05:16:36 +0000465 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000466}
467
Chris Lattner2a9d9892008-10-20 05:16:36 +0000468
John McCalldadc5752010-08-24 06:29:42 +0000469ExprResult
John McCallce546572009-12-08 09:08:17 +0000470Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000471 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000472 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
473 return BuildDeclRefExpr(D, Ty, NameInfo, SS);
474}
475
476/// BuildDeclRefExpr - Build a DeclRefExpr.
John McCalldadc5752010-08-24 06:29:42 +0000477ExprResult
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000478Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty,
479 const DeclarationNameInfo &NameInfo,
480 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000481 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000482 Diag(NameInfo.getLoc(),
Mike Stump11289f42009-09-09 15:08:12 +0000483 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000484 << D->getDeclName();
485 return ExprError();
486 }
Mike Stump11289f42009-09-09 15:08:12 +0000487
Anders Carlsson946b86d2009-06-24 00:10:43 +0000488 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Douglas Gregor15243332010-04-27 21:10:04 +0000489 if (isa<NonTypeTemplateParmDecl>(VD)) {
490 // Non-type template parameters can be referenced anywhere they are
491 // visible.
Douglas Gregora8a089b2010-07-13 18:40:04 +0000492 Ty = Ty.getNonLValueExprType(Context);
Douglas Gregor15243332010-04-27 21:10:04 +0000493 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
Anders Carlsson946b86d2009-06-24 00:10:43 +0000494 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
495 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000496 Diag(NameInfo.getLoc(),
497 diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000498 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000499 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000500 << D->getIdentifier();
501 return ExprError();
502 }
503 }
504 }
505 }
Mike Stump11289f42009-09-09 15:08:12 +0000506
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000507 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +0000508
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000509 return Owned(DeclRefExpr::Create(Context,
510 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
511 SS? SS->getRange() : SourceRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000512 D, NameInfo, Ty));
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000513}
514
Douglas Gregord5846a12009-04-15 06:41:24 +0000515/// \brief Given a field that represents a member of an anonymous
516/// struct/union, build the path from that field's context to the
517/// actual member.
518///
519/// Construct the sequence of field member references we'll have to
520/// perform to get to the field in the anonymous union/struct. The
521/// list of members is built from the field outward, so traverse it
522/// backwards to go from an object in the current context to the field
523/// we found.
524///
525/// \returns The variable from which the field access should begin,
526/// for an anonymous struct/union that is not a member of another
527/// class. Otherwise, returns NULL.
528VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
529 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000530 assert(Field->getDeclContext()->isRecord() &&
531 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
532 && "Field must be stored inside an anonymous struct or union");
533
Douglas Gregord5846a12009-04-15 06:41:24 +0000534 Path.push_back(Field);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000535 VarDecl *BaseObject = 0;
536 DeclContext *Ctx = Field->getDeclContext();
537 do {
538 RecordDecl *Record = cast<RecordDecl>(Ctx);
John McCall61925b02010-05-21 01:17:40 +0000539 ValueDecl *AnonObject = Record->getAnonymousStructOrUnionObject();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000540 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregord5846a12009-04-15 06:41:24 +0000541 Path.push_back(AnonField);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000542 else {
543 BaseObject = cast<VarDecl>(AnonObject);
544 break;
545 }
546 Ctx = Ctx->getParent();
Mike Stump11289f42009-09-09 15:08:12 +0000547 } while (Ctx->isRecord() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000548 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregord5846a12009-04-15 06:41:24 +0000549
550 return BaseObject;
551}
552
John McCalldadc5752010-08-24 06:29:42 +0000553ExprResult
Douglas Gregord5846a12009-04-15 06:41:24 +0000554Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
555 FieldDecl *Field,
556 Expr *BaseObjectExpr,
557 SourceLocation OpLoc) {
558 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump11289f42009-09-09 15:08:12 +0000559 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregord5846a12009-04-15 06:41:24 +0000560 AnonFields);
561
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000562 // Build the expression that refers to the base object, from
563 // which we will build a sequence of member references to each
564 // of the anonymous union objects and, eventually, the field we
565 // found via name lookup.
566 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000567 Qualifiers BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000568 if (BaseObject) {
569 // BaseObject is an anonymous struct/union variable (and is,
570 // therefore, not part of another non-anonymous record).
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000571 MarkDeclarationReferenced(Loc, BaseObject);
Steve Narofff6009ed2009-01-21 00:14:39 +0000572 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000573 SourceLocation());
John McCall8ccfcb52009-09-24 19:53:00 +0000574 BaseQuals
575 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000576 } else if (BaseObjectExpr) {
577 // The caller provided the base object expression. Determine
578 // whether its a pointer and whether it adds any qualifiers to the
579 // anonymous struct/union fields we're looking into.
580 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000581 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000582 BaseObjectIsPointer = true;
583 ObjectType = ObjectPtr->getPointeeType();
584 }
John McCall8ccfcb52009-09-24 19:53:00 +0000585 BaseQuals
586 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000587 } else {
588 // We've found a member of an anonymous struct/union that is
589 // inside a non-anonymous struct/union, so in a well-formed
590 // program our base object expression is "this".
John McCall87fe5d52010-05-20 01:18:31 +0000591 DeclContext *DC = getFunctionLevelDeclContext();
592 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000593 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000594 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000595 = Context.getTagDeclType(
596 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
597 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000598 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000599 == Context.getCanonicalType(ThisType)) ||
600 IsDerivedFrom(ThisType, AnonFieldType)) {
601 // Our base object expression is "this".
Douglas Gregor4b654412009-12-24 20:23:34 +0000602 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000603 MD->getThisType(Context),
604 /*isImplicit=*/true);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000605 BaseObjectIsPointer = true;
606 }
607 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000608 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
609 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000610 }
John McCall8ccfcb52009-09-24 19:53:00 +0000611 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000612 }
613
Mike Stump11289f42009-09-09 15:08:12 +0000614 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000615 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
616 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000617 }
618
619 // Build the implicit member references to the field of the
620 // anonymous struct/union.
621 Expr *Result = BaseObjectExpr;
John McCall8ccfcb52009-09-24 19:53:00 +0000622 Qualifiers ResultQuals = BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000623 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
624 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
625 FI != FIEnd; ++FI) {
626 QualType MemberType = (*FI)->getType();
John McCall8ccfcb52009-09-24 19:53:00 +0000627 Qualifiers MemberTypeQuals =
628 Context.getCanonicalType(MemberType).getQualifiers();
629
630 // CVR attributes from the base are picked up by members,
631 // except that 'mutable' members don't pick up 'const'.
632 if ((*FI)->isMutable())
633 ResultQuals.removeConst();
634
635 // GC attributes are never picked up by members.
636 ResultQuals.removeObjCGCAttr();
637
638 // TR 18037 does not allow fields to be declared with address spaces.
639 assert(!MemberTypeQuals.hasAddressSpace());
640
641 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
642 if (NewQuals != MemberTypeQuals)
643 MemberType = Context.getQualifiedType(MemberType, NewQuals);
644
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000645 MarkDeclarationReferenced(Loc, *FI);
John McCall16df1e52010-03-30 21:47:33 +0000646 PerformObjectMemberConversion(Result, /*FIXME:Qualifier=*/0, *FI, *FI);
Douglas Gregorc1905232009-08-26 22:36:53 +0000647 // FIXME: Might this end up being a qualified name?
Steve Narofff6009ed2009-01-21 00:14:39 +0000648 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
649 OpLoc, MemberType);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000650 BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000651 ResultQuals = NewQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000652 }
653
Sebastian Redlffbcf962009-01-18 18:53:16 +0000654 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000655}
656
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000657/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +0000658/// possibly a list of template arguments.
659///
660/// If this produces template arguments, it is permitted to call
661/// DecomposeTemplateName.
662///
663/// This actually loses a lot of source location information for
664/// non-standard name kinds; we should consider preserving that in
665/// some way.
666static void DecomposeUnqualifiedId(Sema &SemaRef,
667 const UnqualifiedId &Id,
668 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000669 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +0000670 const TemplateArgumentListInfo *&TemplateArgs) {
671 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
672 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
673 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
674
675 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
676 Id.TemplateId->getTemplateArgs(),
677 Id.TemplateId->NumArgs);
678 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
679 TemplateArgsPtr.release();
680
John McCall3e56fd42010-08-23 07:28:44 +0000681 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000682 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
683 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +0000684 TemplateArgs = &Buffer;
685 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000686 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +0000687 TemplateArgs = 0;
688 }
689}
690
John McCall69f9dbc2010-02-08 19:26:07 +0000691/// Determines whether the given record is "fully-formed" at the given
692/// location, i.e. whether a qualified lookup into it is assured of
693/// getting consistent results already.
John McCall10eae182009-11-30 22:42:35 +0000694static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
John McCall69f9dbc2010-02-08 19:26:07 +0000695 if (!Record->hasDefinition())
696 return false;
697
John McCall10eae182009-11-30 22:42:35 +0000698 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
699 E = Record->bases_end(); I != E; ++I) {
700 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
701 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
702 if (!BaseRT) return false;
703
704 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall69f9dbc2010-02-08 19:26:07 +0000705 if (!BaseRecord->hasDefinition() ||
John McCall10eae182009-11-30 22:42:35 +0000706 !IsFullyFormedScope(SemaRef, BaseRecord))
707 return false;
708 }
709
710 return true;
711}
712
John McCall2d74de92009-12-01 22:10:20 +0000713/// Determines if the given class is provably not derived from all of
714/// the prospective base classes.
715static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
716 CXXRecordDecl *Record,
717 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +0000718 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +0000719 return false;
720
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000721 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +0000722 if (!RD) return false;
723 Record = cast<CXXRecordDecl>(RD);
724
John McCall2d74de92009-12-01 22:10:20 +0000725 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
726 E = Record->bases_end(); I != E; ++I) {
727 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
728 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
729 if (!BaseRT) return false;
730
731 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +0000732 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
733 return false;
734 }
735
736 return true;
737}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000738
John McCall2d74de92009-12-01 22:10:20 +0000739enum IMAKind {
740 /// The reference is definitely not an instance member access.
741 IMA_Static,
742
743 /// The reference may be an implicit instance member access.
744 IMA_Mixed,
745
746 /// The reference may be to an instance member, but it is invalid if
747 /// so, because the context is not an instance method.
748 IMA_Mixed_StaticContext,
749
750 /// The reference may be to an instance member, but it is invalid if
751 /// so, because the context is from an unrelated class.
752 IMA_Mixed_Unrelated,
753
754 /// The reference is definitely an implicit instance member access.
755 IMA_Instance,
756
757 /// The reference may be to an unresolved using declaration.
758 IMA_Unresolved,
759
760 /// The reference may be to an unresolved using declaration and the
761 /// context is not an instance method.
762 IMA_Unresolved_StaticContext,
763
764 /// The reference is to a member of an anonymous structure in a
765 /// non-class context.
766 IMA_AnonymousMember,
767
768 /// All possible referrents are instance members and the current
769 /// context is not an instance method.
770 IMA_Error_StaticContext,
771
772 /// All possible referrents are instance members of an unrelated
773 /// class.
774 IMA_Error_Unrelated
775};
776
777/// The given lookup names class member(s) and is not being used for
778/// an address-of-member expression. Classify the type of access
779/// according to whether it's possible that this reference names an
780/// instance member. This is best-effort; it is okay to
781/// conservatively answer "yes", in which case some errors will simply
782/// not be caught until template-instantiation.
783static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
784 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +0000785 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +0000786
John McCall87fe5d52010-05-20 01:18:31 +0000787 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +0000788 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +0000789 (!isa<CXXMethodDecl>(DC) ||
790 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +0000791
792 if (R.isUnresolvableResult())
793 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
794
795 // Collect all the declaring classes of instance members we find.
796 bool hasNonInstance = false;
797 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
798 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +0000799 NamedDecl *D = *I;
800 if (D->isCXXInstanceMember()) {
John McCall2d74de92009-12-01 22:10:20 +0000801 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
802
803 // If this is a member of an anonymous record, move out to the
804 // innermost non-anonymous struct or union. If there isn't one,
805 // that's a special case.
806 while (R->isAnonymousStructOrUnion()) {
807 R = dyn_cast<CXXRecordDecl>(R->getParent());
808 if (!R) return IMA_AnonymousMember;
809 }
810 Classes.insert(R->getCanonicalDecl());
811 }
812 else
813 hasNonInstance = true;
814 }
815
816 // If we didn't find any instance members, it can't be an implicit
817 // member reference.
818 if (Classes.empty())
819 return IMA_Static;
820
821 // If the current context is not an instance method, it can't be
822 // an implicit member reference.
823 if (isStaticContext)
824 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
825
826 // If we can prove that the current context is unrelated to all the
827 // declaring classes, it can't be an implicit member reference (in
828 // which case it's an error if any of those members are selected).
829 if (IsProvablyNotDerivedFrom(SemaRef,
John McCall87fe5d52010-05-20 01:18:31 +0000830 cast<CXXMethodDecl>(DC)->getParent(),
John McCall2d74de92009-12-01 22:10:20 +0000831 Classes))
832 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
833
834 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
835}
836
837/// Diagnose a reference to a field with no object available.
838static void DiagnoseInstanceReference(Sema &SemaRef,
839 const CXXScopeSpec &SS,
840 const LookupResult &R) {
841 SourceLocation Loc = R.getNameLoc();
842 SourceRange Range(Loc);
843 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
844
845 if (R.getAsSingle<FieldDecl>()) {
846 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
847 if (MD->isStatic()) {
848 // "invalid use of member 'x' in static member function"
849 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
850 << Range << R.getLookupName();
851 return;
852 }
853 }
854
855 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
856 << R.getLookupName() << Range;
857 return;
858 }
859
860 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +0000861}
862
John McCalld681c392009-12-16 08:11:27 +0000863/// Diagnose an empty lookup.
864///
865/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000866bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
867 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +0000868 DeclarationName Name = R.getLookupName();
869
John McCalld681c392009-12-16 08:11:27 +0000870 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000871 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +0000872 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
873 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +0000874 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +0000875 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000876 diagnostic_suggest = diag::err_undeclared_use_suggest;
877 }
John McCalld681c392009-12-16 08:11:27 +0000878
Douglas Gregor598b08f2009-12-31 05:20:13 +0000879 // If the original lookup was an unqualified lookup, fake an
880 // unqualified lookup. This is useful when (for example) the
881 // original lookup would not have found something because it was a
882 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000883 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000884 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +0000885 if (isa<CXXRecordDecl>(DC)) {
886 LookupQualifiedName(R, DC);
887
888 if (!R.empty()) {
889 // Don't give errors about ambiguities in this lookup.
890 R.suppressDiagnostics();
891
892 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
893 bool isInstance = CurMethod &&
894 CurMethod->isInstance() &&
895 DC == CurMethod->getParent();
896
897 // Give a code modification hint to insert 'this->'.
898 // TODO: fixit for inserting 'Base<T>::' in the other cases.
899 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000900 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000901 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
902 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +0000903 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000904 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +0000905 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +0000906 Diag(R.getNameLoc(), diagnostic) << Name
907 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
908 QualType DepThisType = DepMethod->getThisType(Context);
909 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
910 R.getNameLoc(), DepThisType, false);
911 TemplateArgumentListInfo TList;
912 if (ULE->hasExplicitTemplateArgs())
913 ULE->copyTemplateArgumentsInto(TList);
914 CXXDependentScopeMemberExpr *DepExpr =
915 CXXDependentScopeMemberExpr::Create(
916 Context, DepThis, DepThisType, true, SourceLocation(),
917 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
918 R.getLookupNameInfo(), &TList);
919 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +0000920 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +0000921 // FIXME: we should be able to handle this case too. It is correct
922 // to add this-> here. This is a workaround for PR7947.
923 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +0000924 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000925 } else {
John McCalld681c392009-12-16 08:11:27 +0000926 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000927 }
John McCalld681c392009-12-16 08:11:27 +0000928
929 // Do we really want to note all of these?
930 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
931 Diag((*I)->getLocation(), diag::note_dependent_var_use);
932
933 // Tell the callee to try to recover.
934 return false;
935 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +0000936
937 R.clear();
John McCalld681c392009-12-16 08:11:27 +0000938 }
939 }
940
Douglas Gregor598b08f2009-12-31 05:20:13 +0000941 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000942 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +0000943 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000944 if (!R.empty()) {
945 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
946 if (SS.isEmpty())
947 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
948 << FixItHint::CreateReplacement(R.getNameLoc(),
949 R.getLookupName().getAsString());
950 else
951 Diag(R.getNameLoc(), diag::err_no_member_suggest)
952 << Name << computeDeclContext(SS, false) << R.getLookupName()
953 << SS.getRange()
954 << FixItHint::CreateReplacement(R.getNameLoc(),
955 R.getLookupName().getAsString());
956 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
957 Diag(ND->getLocation(), diag::note_previous_decl)
958 << ND->getDeclName();
959
960 // Tell the callee to try to recover.
961 return false;
962 }
Alexis Huntc46382e2010-04-28 23:02:27 +0000963
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000964 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
965 // FIXME: If we ended up with a typo for a type name or
966 // Objective-C class name, we're in trouble because the parser
967 // is in the wrong place to recover. Suggest the typo
968 // correction, but don't make it a fix-it since we're not going
969 // to recover well anyway.
970 if (SS.isEmpty())
971 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
972 else
973 Diag(R.getNameLoc(), diag::err_no_member_suggest)
974 << Name << computeDeclContext(SS, false) << R.getLookupName()
975 << SS.getRange();
976
977 // Don't try to recover; it won't work.
978 return true;
979 }
980 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +0000981 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000982 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +0000983 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000984 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000985 else
Douglas Gregor25363982010-01-01 00:15:04 +0000986 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000987 << Name << computeDeclContext(SS, false) << Corrected
988 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +0000989 return true;
990 }
Douglas Gregor25363982010-01-01 00:15:04 +0000991 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +0000992 }
993
994 // Emit a special diagnostic for failed member lookups.
995 // FIXME: computing the declaration context might fail here (?)
996 if (!SS.isEmpty()) {
997 Diag(R.getNameLoc(), diag::err_no_member)
998 << Name << computeDeclContext(SS, false)
999 << SS.getRange();
1000 return true;
1001 }
1002
John McCalld681c392009-12-16 08:11:27 +00001003 // Give up, we can't recover.
1004 Diag(R.getNameLoc(), diagnostic) << Name;
1005 return true;
1006}
1007
Fariborz Jahanian86151342010-07-22 23:33:21 +00001008static ObjCPropertyDecl *OkToSynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001009 IdentifierInfo *II,
1010 SourceLocation NameLoc) {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001011 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
1012 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1013 if (!IDecl)
1014 return 0;
1015 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1016 if (!ClassImpDecl)
1017 return 0;
1018 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1019 if (!property)
1020 return 0;
1021 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1022 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
1023 return 0;
1024 return property;
1025}
1026
Fariborz Jahanian18722982010-07-17 00:59:30 +00001027static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001028 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001029 IdentifierInfo *II,
1030 SourceLocation NameLoc) {
1031 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001032 bool LookForIvars;
1033 if (Lookup.empty())
1034 LookForIvars = true;
1035 else if (CurMeth->isClassMethod())
1036 LookForIvars = false;
1037 else
1038 LookForIvars = (Lookup.isSingleResult() &&
1039 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1040 if (!LookForIvars)
1041 return 0;
1042
Fariborz Jahanian18722982010-07-17 00:59:30 +00001043 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1044 if (!IDecl)
1045 return 0;
1046 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001047 if (!ClassImpDecl)
1048 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001049 bool DynamicImplSeen = false;
1050 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1051 if (!property)
1052 return 0;
1053 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1054 DynamicImplSeen =
1055 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
1056 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001057 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1058 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001059 NameLoc,
1060 II, PropType, /*Dinfo=*/0,
1061 ObjCIvarDecl::Protected,
1062 (Expr *)0, true);
1063 ClassImpDecl->addDecl(Ivar);
1064 IDecl->makeDeclVisibleInContext(Ivar, false);
1065 property->setPropertyIvarDecl(Ivar);
1066 return Ivar;
1067 }
1068 return 0;
1069}
1070
John McCalldadc5752010-08-24 06:29:42 +00001071ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001072 CXXScopeSpec &SS,
1073 UnqualifiedId &Id,
1074 bool HasTrailingLParen,
1075 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001076 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1077 "cannot be direct & operand and have a trailing lparen");
1078
1079 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001080 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001081
John McCall10eae182009-11-30 22:42:35 +00001082 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001083
1084 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001085 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001086 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001087 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001088
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001089 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001090 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001091 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001092
John McCalle66edc12009-11-24 19:00:30 +00001093 // C++ [temp.dep.expr]p3:
1094 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001095 // -- an identifier that was declared with a dependent type,
1096 // (note: handled after lookup)
1097 // -- a template-id that is dependent,
1098 // (note: handled in BuildTemplateIdExpr)
1099 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001100 // -- a nested-name-specifier that contains a class-name that
1101 // names a dependent type.
1102 // Determine whether this is a member of an unknown specialization;
1103 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001104 bool DependentID = false;
1105 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1106 Name.getCXXNameType()->isDependentType()) {
1107 DependentID = true;
1108 } else if (SS.isSet()) {
1109 DeclContext *DC = computeDeclContext(SS, false);
1110 if (DC) {
1111 if (RequireCompleteDeclContext(SS, DC))
1112 return ExprError();
1113 // FIXME: We should be checking whether DC is the current instantiation.
1114 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
1115 DependentID = !IsFullyFormedScope(*this, RD);
1116 } else {
1117 DependentID = true;
1118 }
1119 }
1120
1121 if (DependentID) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001122 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001123 TemplateArgs);
1124 }
Fariborz Jahanian86151342010-07-22 23:33:21 +00001125 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001126 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001127 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001128 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001129 // Lookup the template name again to correctly establish the context in
1130 // which it was found. This is really unfortunate as we already did the
1131 // lookup to determine that it was a template name in the first place. If
1132 // this becomes a performance hit, we can work harder to preserve those
1133 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001134 bool MemberOfUnknownSpecialization;
1135 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1136 MemberOfUnknownSpecialization);
John McCalle66edc12009-11-24 19:00:30 +00001137 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001138 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001139 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001140
John McCalle66edc12009-11-24 19:00:30 +00001141 // If this reference is in an Objective-C method, then we need to do
1142 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001143 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001144 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001145 if (E.isInvalid())
1146 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001147
John McCalle66edc12009-11-24 19:00:30 +00001148 Expr *Ex = E.takeAs<Expr>();
1149 if (Ex) return Owned(Ex);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001150 // Synthesize ivars lazily
1151 if (getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001152 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc))
Fariborz Jahanian18722982010-07-17 00:59:30 +00001153 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1154 isAddressOfOperand);
1155 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001156 // for further use, this must be set to false if in class method.
1157 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001158 }
Chris Lattner59a25942008-03-31 00:36:02 +00001159 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001160
John McCalle66edc12009-11-24 19:00:30 +00001161 if (R.isAmbiguous())
1162 return ExprError();
1163
Douglas Gregor171c45a2009-02-18 21:56:37 +00001164 // Determine whether this name might be a candidate for
1165 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001166 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001167
John McCalle66edc12009-11-24 19:00:30 +00001168 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001169 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001170 // in C90, extension in C99, forbidden in C++).
1171 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1172 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1173 if (D) R.addDecl(D);
1174 }
1175
1176 // If this name wasn't predeclared and if this is not a function
1177 // call, diagnose the problem.
1178 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001179 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001180 return ExprError();
1181
1182 assert(!R.empty() &&
1183 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001184
1185 // If we found an Objective-C instance variable, let
1186 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001187 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001188 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1189 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001190 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001191 assert(E.isInvalid() || E.get());
1192 return move(E);
1193 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001194 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001195 }
Mike Stump11289f42009-09-09 15:08:12 +00001196
John McCalle66edc12009-11-24 19:00:30 +00001197 // This is guaranteed from this point on.
1198 assert(!R.empty() || ADL);
1199
1200 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001201 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
Fariborz Jahanianc15dfd82010-07-29 16:53:53 +00001202 !getLangOptions().ObjCNonFragileABI2 &&
1203 Var->isFileVarDecl()) {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001204 ObjCPropertyDecl *Property =
1205 OkToSynthesizeProvisionalIvar(*this, II, NameLoc);
1206 if (Property) {
1207 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1208 Diag(Property->getLocation(), diag::note_property_declare);
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001209 Diag(Var->getLocation(), diag::note_global_declared_at);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001210 }
1211 }
John McCalle66edc12009-11-24 19:00:30 +00001212 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001213 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1214 // C99 DR 316 says that, if a function type comes from a
1215 // function definition (without a prototype), that type is only
1216 // used for checking compatibility. Therefore, when referencing
1217 // the function, we pretend that we don't have the full function
1218 // type.
John McCalle66edc12009-11-24 19:00:30 +00001219 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001220 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001221
Douglas Gregor3256d042009-06-30 15:47:41 +00001222 QualType T = Func->getType();
1223 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001224 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Eli Friedmanb41ad0f2010-05-17 02:50:18 +00001225 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(),
1226 Proto->getExtInfo());
John McCalle66edc12009-11-24 19:00:30 +00001227 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001228 }
1229 }
Mike Stump11289f42009-09-09 15:08:12 +00001230
John McCall2d74de92009-12-01 22:10:20 +00001231 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001232 // C++ [class.mfct.non-static]p3:
1233 // When an id-expression that is not part of a class member access
1234 // syntax and not used to form a pointer to member is used in the
1235 // body of a non-static member function of class X, if name lookup
1236 // resolves the name in the id-expression to a non-static non-type
1237 // member of some class C, the id-expression is transformed into a
1238 // class member access expression using (*this) as the
1239 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001240 //
1241 // But we don't actually need to do this for '&' operands if R
1242 // resolved to a function or overloaded function set, because the
1243 // expression is ill-formed if it actually works out to be a
1244 // non-static member function:
1245 //
1246 // C++ [expr.ref]p4:
1247 // Otherwise, if E1.E2 refers to a non-static member function. . .
1248 // [t]he expression can be used only as the left-hand operand of a
1249 // member function call.
1250 //
1251 // There are other safeguards against such uses, but it's important
1252 // to get this right here so that we don't end up making a
1253 // spuriously dependent expression if we're inside a dependent
1254 // instance method.
John McCall57500772009-12-16 12:17:52 +00001255 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001256 bool MightBeImplicitMember;
1257 if (!isAddressOfOperand)
1258 MightBeImplicitMember = true;
1259 else if (!SS.isEmpty())
1260 MightBeImplicitMember = false;
1261 else if (R.isOverloadedResult())
1262 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001263 else if (R.isUnresolvableResult())
1264 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001265 else
1266 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl());
1267
1268 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001269 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001270 }
1271
John McCalle66edc12009-11-24 19:00:30 +00001272 if (TemplateArgs)
1273 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001274
John McCalle66edc12009-11-24 19:00:30 +00001275 return BuildDeclarationNameExpr(SS, R, ADL);
1276}
1277
John McCall57500772009-12-16 12:17:52 +00001278/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001279ExprResult
John McCall57500772009-12-16 12:17:52 +00001280Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1281 LookupResult &R,
1282 const TemplateArgumentListInfo *TemplateArgs) {
1283 switch (ClassifyImplicitMemberAccess(*this, R)) {
1284 case IMA_Instance:
1285 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1286
1287 case IMA_AnonymousMember:
1288 assert(R.isSingleResult());
1289 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1290 R.getAsSingle<FieldDecl>());
1291
1292 case IMA_Mixed:
1293 case IMA_Mixed_Unrelated:
1294 case IMA_Unresolved:
1295 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1296
1297 case IMA_Static:
1298 case IMA_Mixed_StaticContext:
1299 case IMA_Unresolved_StaticContext:
1300 if (TemplateArgs)
1301 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1302 return BuildDeclarationNameExpr(SS, R, false);
1303
1304 case IMA_Error_StaticContext:
1305 case IMA_Error_Unrelated:
1306 DiagnoseInstanceReference(*this, SS, R);
1307 return ExprError();
1308 }
1309
1310 llvm_unreachable("unexpected instance member access kind");
1311 return ExprError();
1312}
1313
John McCall10eae182009-11-30 22:42:35 +00001314/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1315/// declaration name, generally during template instantiation.
1316/// There's a large number of things which don't need to be done along
1317/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001318ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001319Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001320 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001321 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001322 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001323 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001324
John McCall0b66eb32010-05-01 00:40:08 +00001325 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001326 return ExprError();
1327
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001328 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001329 LookupQualifiedName(R, DC);
1330
1331 if (R.isAmbiguous())
1332 return ExprError();
1333
1334 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001335 Diag(NameInfo.getLoc(), diag::err_no_member)
1336 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001337 return ExprError();
1338 }
1339
1340 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1341}
1342
1343/// LookupInObjCMethod - The parser has read a name in, and Sema has
1344/// detected that we're currently inside an ObjC method. Perform some
1345/// additional lookup.
1346///
1347/// Ideally, most of this would be done by lookup, but there's
1348/// actually quite a lot of extra work involved.
1349///
1350/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001351ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001352Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001353 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001354 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001355 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001356
John McCalle66edc12009-11-24 19:00:30 +00001357 // There are two cases to handle here. 1) scoped lookup could have failed,
1358 // in which case we should look for an ivar. 2) scoped lookup could have
1359 // found a decl, but that decl is outside the current instance method (i.e.
1360 // a global variable). In these two cases, we do a lookup for an ivar with
1361 // this name, if the lookup sucedes, we replace it our current decl.
1362
1363 // If we're in a class method, we don't normally want to look for
1364 // ivars. But if we don't find anything else, and there's an
1365 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001366 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001367
1368 bool LookForIvars;
1369 if (Lookup.empty())
1370 LookForIvars = true;
1371 else if (IsClassMethod)
1372 LookForIvars = false;
1373 else
1374 LookForIvars = (Lookup.isSingleResult() &&
1375 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001376 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001377 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001378 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001379 ObjCInterfaceDecl *ClassDeclared;
1380 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1381 // Diagnose using an ivar in a class method.
1382 if (IsClassMethod)
1383 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1384 << IV->getDeclName());
1385
1386 // If we're referencing an invalid decl, just return this as a silent
1387 // error node. The error diagnostic was already emitted on the decl.
1388 if (IV->isInvalidDecl())
1389 return ExprError();
1390
1391 // Check if referencing a field with __attribute__((deprecated)).
1392 if (DiagnoseUseOfDecl(IV, Loc))
1393 return ExprError();
1394
1395 // Diagnose the use of an ivar outside of the declaring class.
1396 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1397 ClassDeclared != IFace)
1398 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1399
1400 // FIXME: This should use a new expr for a direct reference, don't
1401 // turn this into Self->ivar, just return a BareIVarExpr or something.
1402 IdentifierInfo &II = Context.Idents.get("self");
1403 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001404 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001405 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001406 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001407 SelfName, false, false);
1408 if (SelfExpr.isInvalid())
1409 return ExprError();
1410
John McCalle66edc12009-11-24 19:00:30 +00001411 MarkDeclarationReferenced(Loc, IV);
1412 return Owned(new (Context)
1413 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1414 SelfExpr.takeAs<Expr>(), true, true));
1415 }
Chris Lattner87313662010-04-12 05:10:17 +00001416 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001417 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001418 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001419 ObjCInterfaceDecl *ClassDeclared;
1420 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1421 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1422 IFace == ClassDeclared)
1423 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1424 }
1425 }
1426
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001427 if (Lookup.empty() && II && AllowBuiltinCreation) {
1428 // FIXME. Consolidate this with similar code in LookupName.
1429 if (unsigned BuiltinID = II->getBuiltinID()) {
1430 if (!(getLangOptions().CPlusPlus &&
1431 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1432 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1433 S, Lookup.isForRedeclaration(),
1434 Lookup.getNameLoc());
1435 if (D) Lookup.addDecl(D);
1436 }
1437 }
1438 }
John McCalle66edc12009-11-24 19:00:30 +00001439 // Sentinel value saying that we didn't do anything special.
1440 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001441}
John McCalld14a8642009-11-21 08:51:07 +00001442
John McCall16df1e52010-03-30 21:47:33 +00001443/// \brief Cast a base object to a member's actual type.
1444///
1445/// Logically this happens in three phases:
1446///
1447/// * First we cast from the base type to the naming class.
1448/// The naming class is the class into which we were looking
1449/// when we found the member; it's the qualifier type if a
1450/// qualifier was provided, and otherwise it's the base type.
1451///
1452/// * Next we cast from the naming class to the declaring class.
1453/// If the member we found was brought into a class's scope by
1454/// a using declaration, this is that class; otherwise it's
1455/// the class declaring the member.
1456///
1457/// * Finally we cast from the declaring class to the "true"
1458/// declaring class of the member. This conversion does not
1459/// obey access control.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001460bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001461Sema::PerformObjectMemberConversion(Expr *&From,
1462 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001463 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001464 NamedDecl *Member) {
1465 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1466 if (!RD)
1467 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001468
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001469 QualType DestRecordType;
1470 QualType DestType;
1471 QualType FromRecordType;
1472 QualType FromType = From->getType();
1473 bool PointerConversions = false;
1474 if (isa<FieldDecl>(Member)) {
1475 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001476
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001477 if (FromType->getAs<PointerType>()) {
1478 DestType = Context.getPointerType(DestRecordType);
1479 FromRecordType = FromType->getPointeeType();
1480 PointerConversions = true;
1481 } else {
1482 DestType = DestRecordType;
1483 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001484 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001485 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1486 if (Method->isStatic())
1487 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001488
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001489 DestType = Method->getThisType(Context);
1490 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001491
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001492 if (FromType->getAs<PointerType>()) {
1493 FromRecordType = FromType->getPointeeType();
1494 PointerConversions = true;
1495 } else {
1496 FromRecordType = FromType;
1497 DestType = DestRecordType;
1498 }
1499 } else {
1500 // No conversion necessary.
1501 return false;
1502 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001503
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001504 if (DestType->isDependentType() || FromType->isDependentType())
1505 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001506
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001507 // If the unqualified types are the same, no conversion is necessary.
1508 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1509 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001510
John McCall16df1e52010-03-30 21:47:33 +00001511 SourceRange FromRange = From->getSourceRange();
1512 SourceLocation FromLoc = FromRange.getBegin();
1513
John McCall2536c6d2010-08-25 10:28:54 +00001514 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001515
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001516 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001517 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001518 // class name.
1519 //
1520 // If the member was a qualified name and the qualified referred to a
1521 // specific base subobject type, we'll cast to that intermediate type
1522 // first and then to the object in which the member is declared. That allows
1523 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1524 //
1525 // class Base { public: int x; };
1526 // class Derived1 : public Base { };
1527 // class Derived2 : public Base { };
1528 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1529 //
1530 // void VeryDerived::f() {
1531 // x = 17; // error: ambiguous base subobjects
1532 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1533 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001534 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001535 QualType QType = QualType(Qualifier->getAsType(), 0);
1536 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1537 assert(QType->isRecordType() && "lookup done with non-record type");
1538
1539 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1540
1541 // In C++98, the qualifier type doesn't actually have to be a base
1542 // type of the object type, in which case we just ignore it.
1543 // Otherwise build the appropriate casts.
1544 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00001545 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001546 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001547 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001548 return true;
1549
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001550 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00001551 QType = Context.getPointerType(QType);
John McCall2536c6d2010-08-25 10:28:54 +00001552 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
1553 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00001554
1555 FromType = QType;
1556 FromRecordType = QRecordType;
1557
1558 // If the qualifier type was the same as the destination type,
1559 // we're done.
1560 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1561 return false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001562 }
1563 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001564
John McCall16df1e52010-03-30 21:47:33 +00001565 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001566
John McCall16df1e52010-03-30 21:47:33 +00001567 // If we actually found the member through a using declaration, cast
1568 // down to the using declaration's type.
1569 //
1570 // Pointer equality is fine here because only one declaration of a
1571 // class ever has member declarations.
1572 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1573 assert(isa<UsingShadowDecl>(FoundDecl));
1574 QualType URecordType = Context.getTypeDeclType(
1575 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1576
1577 // We only need to do this if the naming-class to declaring-class
1578 // conversion is non-trivial.
1579 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1580 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00001581 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001582 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001583 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001584 return true;
Alexis Huntc46382e2010-04-28 23:02:27 +00001585
John McCall16df1e52010-03-30 21:47:33 +00001586 QualType UType = URecordType;
1587 if (PointerConversions)
1588 UType = Context.getPointerType(UType);
John McCalle3027922010-08-25 11:45:40 +00001589 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001590 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00001591 FromType = UType;
1592 FromRecordType = URecordType;
1593 }
1594
1595 // We don't do access control for the conversion from the
1596 // declaring class to the true declaring class.
1597 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001598 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001599
John McCallcf142162010-08-07 06:22:56 +00001600 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00001601 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1602 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00001603 IgnoreAccess))
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001604 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001605
John McCalle3027922010-08-25 11:45:40 +00001606 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001607 VK, &BasePath);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001608 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001609}
Douglas Gregor3256d042009-06-30 15:47:41 +00001610
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001611/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001612static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001613 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00001614 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001615 const DeclarationNameInfo &MemberNameInfo,
1616 QualType Ty,
John McCalle66edc12009-11-24 19:00:30 +00001617 const TemplateArgumentListInfo *TemplateArgs = 0) {
1618 NestedNameSpecifier *Qualifier = 0;
1619 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001620 if (SS.isSet()) {
1621 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1622 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001623 }
Mike Stump11289f42009-09-09 15:08:12 +00001624
John McCalle66edc12009-11-24 19:00:30 +00001625 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001626 Member, FoundDecl, MemberNameInfo,
1627 TemplateArgs, Ty);
Douglas Gregorc1905232009-08-26 22:36:53 +00001628}
1629
John McCall2d74de92009-12-01 22:10:20 +00001630/// Builds an implicit member access expression. The current context
1631/// is known to be an instance method, and the given unqualified lookup
1632/// set is known to contain only instance members, at least one of which
1633/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00001634ExprResult
John McCall2d74de92009-12-01 22:10:20 +00001635Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1636 LookupResult &R,
1637 const TemplateArgumentListInfo *TemplateArgs,
1638 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00001639 assert(!R.empty() && !R.isAmbiguous());
1640
John McCalld14a8642009-11-21 08:51:07 +00001641 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00001642
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001643 // We may have found a field within an anonymous union or struct
1644 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00001645 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00001646 // FIXME: template-ids inside anonymous structs?
John McCall10eae182009-11-30 22:42:35 +00001647 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001648 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCallb53bbd42009-11-22 01:44:31 +00001649 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001650
John McCall2d74de92009-12-01 22:10:20 +00001651 // If this is known to be an instance access, go ahead and build a
1652 // 'this' expression now.
John McCall87fe5d52010-05-20 01:18:31 +00001653 DeclContext *DC = getFunctionLevelDeclContext();
1654 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2d74de92009-12-01 22:10:20 +00001655 Expr *This = 0; // null signifies implicit access
1656 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00001657 SourceLocation Loc = R.getNameLoc();
1658 if (SS.getRange().isValid())
1659 Loc = SS.getRange().getBegin();
1660 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001661 }
1662
John McCallb268a282010-08-23 23:25:46 +00001663 return BuildMemberReferenceExpr(This, ThisType,
John McCall2d74de92009-12-01 22:10:20 +00001664 /*OpLoc*/ SourceLocation(),
1665 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00001666 SS,
1667 /*FirstQualifierInScope*/ 0,
1668 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00001669}
1670
John McCalle66edc12009-11-24 19:00:30 +00001671bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001672 const LookupResult &R,
1673 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00001674 // Only when used directly as the postfix-expression of a call.
1675 if (!HasTrailingLParen)
1676 return false;
1677
1678 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00001679 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00001680 return false;
1681
1682 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00001683 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00001684 return false;
1685
1686 // Turn off ADL when we find certain kinds of declarations during
1687 // normal lookup:
1688 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1689 NamedDecl *D = *I;
1690
1691 // C++0x [basic.lookup.argdep]p3:
1692 // -- a declaration of a class member
1693 // Since using decls preserve this property, we check this on the
1694 // original decl.
John McCall57500772009-12-16 12:17:52 +00001695 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00001696 return false;
1697
1698 // C++0x [basic.lookup.argdep]p3:
1699 // -- a block-scope function declaration that is not a
1700 // using-declaration
1701 // NOTE: we also trigger this for function templates (in fact, we
1702 // don't check the decl type at all, since all other decl types
1703 // turn off ADL anyway).
1704 if (isa<UsingShadowDecl>(D))
1705 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1706 else if (D->getDeclContext()->isFunctionOrMethod())
1707 return false;
1708
1709 // C++0x [basic.lookup.argdep]p3:
1710 // -- a declaration that is neither a function or a function
1711 // template
1712 // And also for builtin functions.
1713 if (isa<FunctionDecl>(D)) {
1714 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1715
1716 // But also builtin functions.
1717 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1718 return false;
1719 } else if (!isa<FunctionTemplateDecl>(D))
1720 return false;
1721 }
1722
1723 return true;
1724}
1725
1726
John McCalld14a8642009-11-21 08:51:07 +00001727/// Diagnoses obvious problems with the use of the given declaration
1728/// as an expression. This is only actually called for lookups that
1729/// were not overloaded, and it doesn't promise that the declaration
1730/// will in fact be used.
1731static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1732 if (isa<TypedefDecl>(D)) {
1733 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1734 return true;
1735 }
1736
1737 if (isa<ObjCInterfaceDecl>(D)) {
1738 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1739 return true;
1740 }
1741
1742 if (isa<NamespaceDecl>(D)) {
1743 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1744 return true;
1745 }
1746
1747 return false;
1748}
1749
John McCalldadc5752010-08-24 06:29:42 +00001750ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001751Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001752 LookupResult &R,
1753 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00001754 // If this is a single, fully-resolved result and we don't need ADL,
1755 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00001756 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001757 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
1758 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00001759
1760 // We only need to check the declaration if there's exactly one
1761 // result, because in the overloaded case the results can only be
1762 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00001763 if (R.isSingleResult() &&
1764 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00001765 return ExprError();
1766
John McCall58cc69d2010-01-27 01:50:18 +00001767 // Otherwise, just build an unresolved lookup expression. Suppress
1768 // any lookup-related diagnostics; we'll hash these out later, when
1769 // we've picked a target.
1770 R.suppressDiagnostics();
1771
John McCalle66edc12009-11-24 19:00:30 +00001772 bool Dependent
1773 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCalld14a8642009-11-21 08:51:07 +00001774 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001775 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001776 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001777 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001778 NeedsADL, R.isOverloadedResult(),
1779 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00001780
1781 return Owned(ULE);
1782}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001783
John McCalld14a8642009-11-21 08:51:07 +00001784
1785/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00001786ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001787Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001788 const DeclarationNameInfo &NameInfo,
1789 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00001790 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00001791 assert(!isa<FunctionTemplateDecl>(D) &&
1792 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00001793
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001794 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001795 if (CheckDeclInExpr(*this, Loc, D))
1796 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00001797
Douglas Gregore7488b92009-12-01 16:58:18 +00001798 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1799 // Specifically diagnose references to class templates that are missing
1800 // a template argument list.
1801 Diag(Loc, diag::err_template_decl_ref)
1802 << Template << SS.getRange();
1803 Diag(Template->getLocation(), diag::note_template_decl_here);
1804 return ExprError();
1805 }
1806
1807 // Make sure that we're referring to a value.
1808 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1809 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001810 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00001811 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00001812 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00001813 return ExprError();
1814 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001815
Douglas Gregor171c45a2009-02-18 21:56:37 +00001816 // Check whether this declaration can be used. Note that we suppress
1817 // this check when we're going to perform argument-dependent lookup
1818 // on this function name, because this might not be the function
1819 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00001820 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00001821 return ExprError();
1822
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001823 // Only create DeclRefExpr's for valid Decl's.
1824 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001825 return ExprError();
1826
Chris Lattner2a9d9892008-10-20 05:16:36 +00001827 // If the identifier reference is inside a block, and it refers to a value
1828 // that is outside the block, create a BlockDeclRefExpr instead of a
1829 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1830 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001831 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00001832 // We do not do this for things like enum constants, global variables, etc,
1833 // as they do not get snapshotted.
1834 //
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001835 if (getCurBlock() &&
Douglas Gregor9a28e842010-03-01 23:15:13 +00001836 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
Mike Stump7dafa0d2010-01-05 02:56:35 +00001837 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1838 Diag(Loc, diag::err_ref_vm_type);
1839 Diag(D->getLocation(), diag::note_declared_at);
1840 return ExprError();
1841 }
1842
Fariborz Jahanianfa24e102010-03-16 23:39:51 +00001843 if (VD->getType()->isArrayType()) {
Mike Stump8971a862010-01-05 03:10:36 +00001844 Diag(Loc, diag::err_ref_array_type);
1845 Diag(D->getLocation(), diag::note_declared_at);
1846 return ExprError();
1847 }
1848
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001849 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001850 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001851 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001852 if (VD->getAttr<BlocksAttr>())
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001853 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001854 // This is to record that a 'const' was actually synthesize and added.
1855 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001856 // Variable will be bound by-copy, make it const within the closure.
Mike Stump11289f42009-09-09 15:08:12 +00001857
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001858 ExprTy.addConst();
Fariborz Jahanian70c0b082010-07-12 17:26:57 +00001859 QualType T = VD->getType();
Fariborz Jahanianea882cd2010-06-04 21:35:44 +00001860 BlockDeclRefExpr *BDRE = new (Context) BlockDeclRefExpr(VD,
1861 ExprTy, Loc, false,
Fariborz Jahanianc289bce2010-07-12 18:12:03 +00001862 constAdded);
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00001863 if (getLangOptions().CPlusPlus) {
1864 if (!T->isDependentType() && !T->isReferenceType()) {
1865 Expr *E = new (Context)
1866 DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T,
1867 SourceLocation());
Fariborz Jahanianea882cd2010-06-04 21:35:44 +00001868
John McCalldadc5752010-08-24 06:29:42 +00001869 ExprResult Res = PerformCopyInitialization(
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00001870 InitializedEntity::InitializeBlock(VD->getLocation(),
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00001871 T, false),
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00001872 SourceLocation(),
1873 Owned(E));
1874 if (!Res.isInvalid()) {
John McCallb268a282010-08-23 23:25:46 +00001875 Res = MaybeCreateCXXExprWithTemporaries(Res.get());
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00001876 Expr *Init = Res.takeAs<Expr>();
1877 BDRE->setCopyConstructorExpr(Init);
1878 }
Fariborz Jahanianea882cd2010-06-04 21:35:44 +00001879 }
1880 }
1881 return Owned(BDRE);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001882 }
1883 // If this reference is not in a block or if the referenced variable is
1884 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00001885
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001886 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
1887 NameInfo, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00001888}
Chris Lattnere168f762006-11-10 05:29:30 +00001889
John McCalldadc5752010-08-24 06:29:42 +00001890ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlffbcf962009-01-18 18:53:16 +00001891 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00001892 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001893
Chris Lattnere168f762006-11-10 05:29:30 +00001894 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00001895 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00001896 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1897 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1898 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00001899 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00001900
Chris Lattnera81a0272008-01-12 08:14:25 +00001901 // Pre-defined identifiers are of type char[x], where x is the length of the
1902 // string.
Mike Stump11289f42009-09-09 15:08:12 +00001903
Anders Carlsson2fb08242009-09-08 18:24:21 +00001904 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00001905 if (!currentDecl && getCurBlock())
1906 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00001907 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001908 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00001909 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001910 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001911
Anders Carlsson0b209a82009-09-11 01:22:35 +00001912 QualType ResTy;
1913 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1914 ResTy = Context.DependentTy;
1915 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00001916 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001917
Anders Carlsson0b209a82009-09-11 01:22:35 +00001918 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00001919 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001920 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1921 }
Steve Narofff6009ed2009-01-21 00:14:39 +00001922 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00001923}
1924
John McCalldadc5752010-08-24 06:29:42 +00001925ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001926 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00001927 bool Invalid = false;
1928 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
1929 if (Invalid)
1930 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001931
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001932 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
1933 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00001934 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001935 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00001936
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001937 QualType Ty;
1938 if (!getLangOptions().CPlusPlus)
1939 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1940 else if (Literal.isWide())
1941 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00001942 else if (Literal.isMultiChar())
1943 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001944 else
1945 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00001946
Sebastian Redl20614a72009-01-20 22:23:13 +00001947 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1948 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001949 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00001950}
1951
John McCalldadc5752010-08-24 06:29:42 +00001952ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001953 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00001954 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1955 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00001956 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00001957 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001958 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00001959 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00001960 }
Ted Kremeneke9814182009-01-13 23:19:12 +00001961
Chris Lattner23b7eb62007-06-15 23:05:46 +00001962 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00001963 // Add padding so that NumericLiteralParser can overread by one character.
1964 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00001965 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00001966
Chris Lattner67ca9252007-05-21 01:08:44 +00001967 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00001968 bool Invalid = false;
1969 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
1970 if (Invalid)
1971 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001972
Mike Stump11289f42009-09-09 15:08:12 +00001973 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00001974 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00001975 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001976 return ExprError();
1977
Chris Lattner1c20a172007-08-26 03:42:43 +00001978 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001979
Chris Lattner1c20a172007-08-26 03:42:43 +00001980 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001981 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001982 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001983 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001984 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001985 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001986 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00001987 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001988
1989 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1990
John McCall53b93a02009-12-24 09:08:04 +00001991 using llvm::APFloat;
1992 APFloat Val(Format);
1993
1994 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00001995
1996 // Overflow is always an error, but underflow is only an error if
1997 // we underflowed to zero (APFloat reports denormals as underflow).
1998 if ((result & APFloat::opOverflow) ||
1999 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002000 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002001 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002002 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002003 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002004 APFloat::getLargest(Format).toString(buffer);
2005 } else {
John McCall62abc942010-02-26 23:35:57 +00002006 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002007 APFloat::getSmallest(Format).toString(buffer);
2008 }
2009
2010 Diag(Tok.getLocation(), diagnostic)
2011 << Ty
2012 << llvm::StringRef(buffer.data(), buffer.size());
2013 }
2014
2015 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002016 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002017
Chris Lattner1c20a172007-08-26 03:42:43 +00002018 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002019 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002020 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002021 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002022
Neil Boothac582c52007-08-29 22:00:19 +00002023 // long long is a C99 feature.
2024 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002025 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002026 Diag(Tok.getLocation(), diag::ext_longlong);
2027
Chris Lattner67ca9252007-05-21 01:08:44 +00002028 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002029 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002030
Chris Lattner67ca9252007-05-21 01:08:44 +00002031 if (Literal.GetIntegerValue(ResultVal)) {
2032 // If this value didn't fit into uintmax_t, warn and force to ull.
2033 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002034 Ty = Context.UnsignedLongLongTy;
2035 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002036 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002037 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002038 // If this value fits into a ULL, try to figure out what else it fits into
2039 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002040
Chris Lattner67ca9252007-05-21 01:08:44 +00002041 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2042 // be an unsigned int.
2043 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2044
2045 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002046 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002047 if (!Literal.isLong && !Literal.isLongLong) {
2048 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002049 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002050
Chris Lattner67ca9252007-05-21 01:08:44 +00002051 // Does it fit in a unsigned int?
2052 if (ResultVal.isIntN(IntSize)) {
2053 // Does it fit in a signed int?
2054 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002055 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002056 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002057 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002058 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002059 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002060 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002061
Chris Lattner67ca9252007-05-21 01:08:44 +00002062 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002063 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002064 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002065
Chris Lattner67ca9252007-05-21 01:08:44 +00002066 // Does it fit in a unsigned long?
2067 if (ResultVal.isIntN(LongSize)) {
2068 // Does it fit in a signed long?
2069 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002070 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002071 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002072 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002073 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002074 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002075 }
2076
Chris Lattner67ca9252007-05-21 01:08:44 +00002077 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002078 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002079 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002080
Chris Lattner67ca9252007-05-21 01:08:44 +00002081 // Does it fit in a unsigned long long?
2082 if (ResultVal.isIntN(LongLongSize)) {
2083 // Does it fit in a signed long long?
2084 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002085 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002086 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002087 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002088 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002089 }
2090 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002091
Chris Lattner67ca9252007-05-21 01:08:44 +00002092 // If we still couldn't decide a type, we probably have something that
2093 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002094 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002095 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002096 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002097 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002098 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002099
Chris Lattner55258cf2008-05-09 05:59:00 +00002100 if (ResultVal.getBitWidth() != Width)
2101 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002102 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002103 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002104 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002105
Chris Lattner1c20a172007-08-26 03:42:43 +00002106 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2107 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002108 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002109 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002110
2111 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002112}
2113
John McCalldadc5752010-08-24 06:29:42 +00002114ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002115 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002116 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002117 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002118}
2119
Steve Naroff71b59a92007-06-04 22:22:31 +00002120/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002121/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002122bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00002123 SourceLocation OpLoc,
2124 const SourceRange &ExprRange,
2125 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002126 if (exprType->isDependentType())
2127 return false;
2128
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002129 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2130 // the result is the size of the referenced type."
2131 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2132 // result shall be the alignment of the referenced type."
2133 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2134 exprType = Ref->getPointeeType();
2135
Steve Naroff043d45d2007-05-15 02:32:35 +00002136 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002137 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002138 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002139 if (isSizeof)
2140 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2141 return false;
2142 }
Mike Stump11289f42009-09-09 15:08:12 +00002143
Chris Lattner62975a72009-04-24 00:30:45 +00002144 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002145 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002146 Diag(OpLoc, diag::ext_sizeof_void_type)
2147 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002148 return false;
2149 }
Mike Stump11289f42009-09-09 15:08:12 +00002150
Chris Lattner62975a72009-04-24 00:30:45 +00002151 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002152 PDiag(diag::err_sizeof_alignof_incomplete_type)
2153 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002154 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002155
Chris Lattner62975a72009-04-24 00:30:45 +00002156 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002157 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002158 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002159 << exprType << isSizeof << ExprRange;
2160 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002161 }
Mike Stump11289f42009-09-09 15:08:12 +00002162
Douglas Gregor27887822010-05-23 19:43:23 +00002163 if (Context.hasSameUnqualifiedType(exprType, Context.OverloadTy)) {
2164 Diag(OpLoc, diag::err_sizeof_alignof_overloaded_function_type)
2165 << !isSizeof << ExprRange;
2166 return true;
2167 }
2168
Chris Lattner62975a72009-04-24 00:30:45 +00002169 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002170}
2171
Chris Lattner8dff0172009-01-24 20:17:12 +00002172bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
2173 const SourceRange &ExprRange) {
2174 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002175
Mike Stump11289f42009-09-09 15:08:12 +00002176 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002177 if (isa<DeclRefExpr>(E))
2178 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002179
2180 // Cannot know anything else if the expression is dependent.
2181 if (E->isTypeDependent())
2182 return false;
2183
Douglas Gregor71235ec2009-05-02 02:18:30 +00002184 if (E->getBitField()) {
2185 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
2186 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002187 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002188
2189 // Alignment of a field access is always okay, so long as it isn't a
2190 // bit-field.
2191 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002192 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002193 return false;
2194
Chris Lattner8dff0172009-01-24 20:17:12 +00002195 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
2196}
2197
Douglas Gregor0950e412009-03-13 21:01:28 +00002198/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002199ExprResult
John McCallbcd03502009-12-07 02:54:59 +00002200Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00002201 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002202 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002203 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002204 return ExprError();
2205
John McCallbcd03502009-12-07 02:54:59 +00002206 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002207
Douglas Gregor0950e412009-03-13 21:01:28 +00002208 if (!T->isDependentType() &&
2209 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2210 return ExprError();
2211
2212 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00002213 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00002214 Context.getSizeType(), OpLoc,
2215 R.getEnd()));
2216}
2217
2218/// \brief Build a sizeof or alignof expression given an expression
2219/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002220ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00002221Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002222 bool isSizeOf, SourceRange R) {
2223 // Verify that the operand is valid.
2224 bool isInvalid = false;
2225 if (E->isTypeDependent()) {
2226 // Delay type-checking for type-dependent expressions.
2227 } else if (!isSizeOf) {
2228 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002229 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002230 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2231 isInvalid = true;
2232 } else {
2233 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2234 }
2235
2236 if (isInvalid)
2237 return ExprError();
2238
2239 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2240 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2241 Context.getSizeType(), OpLoc,
2242 R.getEnd()));
2243}
2244
Sebastian Redl6f282892008-11-11 17:56:53 +00002245/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2246/// the same for @c alignof and @c __alignof
2247/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002248ExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00002249Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2250 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002251 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002252 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002253
Sebastian Redl6f282892008-11-11 17:56:53 +00002254 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002255 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002256 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
John McCallbcd03502009-12-07 02:54:59 +00002257 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002258 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002259
Douglas Gregor0950e412009-03-13 21:01:28 +00002260 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00002261 ExprResult Result
Douglas Gregor0950e412009-03-13 21:01:28 +00002262 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2263
Douglas Gregor0950e412009-03-13 21:01:28 +00002264 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002265}
2266
Chris Lattner709322b2009-02-17 08:12:06 +00002267QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002268 if (V->isTypeDependent())
2269 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002270
Chris Lattnere267f5d2007-08-26 05:39:26 +00002271 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00002272 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002273 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002274
Chris Lattnere267f5d2007-08-26 05:39:26 +00002275 // Otherwise they pass through real integer and floating point types here.
2276 if (V->getType()->isArithmeticType())
2277 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002278
Chris Lattnere267f5d2007-08-26 05:39:26 +00002279 // Reject anything else.
Chris Lattner709322b2009-02-17 08:12:06 +00002280 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
2281 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002282 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002283}
2284
2285
Chris Lattnere168f762006-11-10 05:29:30 +00002286
John McCalldadc5752010-08-24 06:29:42 +00002287ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002288Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002289 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002290 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002291 switch (Kind) {
2292 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002293 case tok::plusplus: Opc = UO_PostInc; break;
2294 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002295 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002296
John McCallb268a282010-08-23 23:25:46 +00002297 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002298}
2299
John McCalldadc5752010-08-24 06:29:42 +00002300ExprResult
John McCallb268a282010-08-23 23:25:46 +00002301Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2302 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002303 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002304 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002305 if (Result.isInvalid()) return ExprError();
2306 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002307
John McCallb268a282010-08-23 23:25:46 +00002308 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002309
Douglas Gregor40412ac2008-11-19 17:17:41 +00002310 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002311 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002312 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2313 Context.DependentTy, RLoc));
2314 }
2315
Mike Stump11289f42009-09-09 15:08:12 +00002316 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002317 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002318 LHSExp->getType()->isEnumeralType() ||
2319 RHSExp->getType()->isRecordType() ||
2320 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002321 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002322 }
2323
John McCallb268a282010-08-23 23:25:46 +00002324 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002325}
2326
2327
John McCalldadc5752010-08-24 06:29:42 +00002328ExprResult
John McCallb268a282010-08-23 23:25:46 +00002329Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2330 Expr *Idx, SourceLocation RLoc) {
2331 Expr *LHSExp = Base;
2332 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002333
Chris Lattner36d572b2007-07-16 00:14:47 +00002334 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002335 if (!LHSExp->getType()->getAs<VectorType>())
2336 DefaultFunctionArrayLvalueConversion(LHSExp);
2337 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002338
Chris Lattner36d572b2007-07-16 00:14:47 +00002339 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00002340
Steve Naroffc1aadb12007-03-28 21:49:40 +00002341 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002342 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002343 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002344 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002345 Expr *BaseExpr, *IndexExpr;
2346 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002347 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2348 BaseExpr = LHSExp;
2349 IndexExpr = RHSExp;
2350 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002351 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002352 BaseExpr = LHSExp;
2353 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002354 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002355 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002356 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002357 BaseExpr = RHSExp;
2358 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002359 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002360 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002361 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002362 BaseExpr = LHSExp;
2363 IndexExpr = RHSExp;
2364 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002365 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002366 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002367 // Handle the uncommon case of "123[Ptr]".
2368 BaseExpr = RHSExp;
2369 IndexExpr = LHSExp;
2370 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00002371 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00002372 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00002373 IndexExpr = RHSExp;
Nate Begemanc1bf0612009-01-18 00:45:31 +00002374
Chris Lattner36d572b2007-07-16 00:14:47 +00002375 // FIXME: need to deal with const...
2376 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002377 } else if (LHSTy->isArrayType()) {
2378 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00002379 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00002380 // wasn't promoted because of the C90 rule that doesn't
2381 // allow promoting non-lvalue arrays. Warn, then
2382 // force the promotion here.
2383 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2384 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002385 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCalle3027922010-08-25 11:45:40 +00002386 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002387 LHSTy = LHSExp->getType();
2388
2389 BaseExpr = LHSExp;
2390 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002391 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002392 } else if (RHSTy->isArrayType()) {
2393 // Same as previous, except for 123[f().a] case
2394 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2395 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002396 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCalle3027922010-08-25 11:45:40 +00002397 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002398 RHSTy = RHSExp->getType();
2399
2400 BaseExpr = RHSExp;
2401 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002402 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00002403 } else {
Chris Lattner003af242009-04-25 22:50:55 +00002404 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2405 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002406 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00002407 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002408 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00002409 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2410 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00002411
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002412 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00002413 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2414 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00002415 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2416
Douglas Gregorac1fb652009-03-24 19:52:54 +00002417 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00002418 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2419 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00002420 // incomplete types are not object types.
2421 if (ResultType->isFunctionType()) {
2422 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2423 << ResultType << BaseExpr->getSourceRange();
2424 return ExprError();
2425 }
Mike Stump11289f42009-09-09 15:08:12 +00002426
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00002427 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
2428 // GNU extension: subscripting on pointer to void
2429 Diag(LLoc, diag::ext_gnu_void_ptr)
2430 << BaseExpr->getSourceRange();
2431 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00002432 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00002433 PDiag(diag::err_subscript_incomplete_type)
2434 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00002435 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002436
Chris Lattner62975a72009-04-24 00:30:45 +00002437 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00002438 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00002439 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2440 << ResultType << BaseExpr->getSourceRange();
2441 return ExprError();
2442 }
Mike Stump11289f42009-09-09 15:08:12 +00002443
Mike Stump4e1f26a2009-02-19 03:04:26 +00002444 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Narofff6009ed2009-01-21 00:14:39 +00002445 ResultType, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00002446}
2447
Steve Narofff8fd09e2007-07-27 22:15:19 +00002448QualType Sema::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002449CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002450 const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00002451 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00002452 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2453 // see FIXME there.
2454 //
2455 // FIXME: This logic can be greatly simplified by splitting it along
2456 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00002457 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00002458
Steve Narofff8fd09e2007-07-27 22:15:19 +00002459 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002460 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002461
Mike Stump4e1f26a2009-02-19 03:04:26 +00002462 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00002463 // special names that indicate a subset of exactly half the elements are
2464 // to be selected.
2465 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002466
Nate Begemanbb70bf62009-01-18 01:47:54 +00002467 // This flag determines whether or not CompName has an 's' char prefix,
2468 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00002469 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00002470
2471 // Check that we've found one of the special components, or that the component
2472 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002473 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00002474 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2475 HalvingSwizzle = true;
Nate Begemanf322eab2008-05-09 06:41:27 +00002476 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002477 do
2478 compStr++;
2479 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begemanbb70bf62009-01-18 01:47:54 +00002480 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002481 do
2482 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002483 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner7e152db2007-08-02 22:33:49 +00002484 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002485
Mike Stump4e1f26a2009-02-19 03:04:26 +00002486 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002487 // We didn't get to the end of the string. This means the component names
2488 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner3b054132008-11-19 05:08:23 +00002489 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00002490 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002491 return QualType();
2492 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002493
Nate Begemanbb70bf62009-01-18 01:47:54 +00002494 // Ensure no component accessor exceeds the width of the vector type it
2495 // operates on.
2496 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002497 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002498
2499 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002500 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002501
2502 while (*compStr) {
2503 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2504 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2505 << baseType << SourceRange(CompLoc);
2506 return QualType();
2507 }
2508 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002509 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002510
Steve Narofff8fd09e2007-07-27 22:15:19 +00002511 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002512 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002513 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002514 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002515 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00002516 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002517 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002518 if (HexSwizzle)
2519 CompSize--;
2520
Steve Narofff8fd09e2007-07-27 22:15:19 +00002521 if (CompSize == 1)
2522 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002523
Nate Begemance4d7fc2008-04-18 23:10:10 +00002524 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002525 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00002526 // diagostics look bad. We want extended vector types to appear built-in.
2527 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2528 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2529 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00002530 }
2531 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00002532}
2533
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002534static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00002535 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002536 const Selector &Sel,
2537 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002538 if (Member)
2539 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
2540 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002541 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002542 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00002543
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002544 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2545 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002546 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
2547 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002548 return D;
2549 }
2550 return 0;
2551}
2552
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002553static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
2554 IdentifierInfo *Member,
2555 const Selector &Sel,
2556 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002557 // Check protocols on qualified interfaces.
2558 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00002559 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002560 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002561 if (Member)
2562 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
2563 GDecl = PD;
2564 break;
2565 }
2566 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002567 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002568 GDecl = OMD;
2569 break;
2570 }
2571 }
2572 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002573 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002574 E = QIdTy->qual_end(); I != E; ++I) {
2575 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002576 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
2577 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002578 if (GDecl)
2579 return GDecl;
2580 }
2581 }
2582 return GDecl;
2583}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00002584
John McCalldadc5752010-08-24 06:29:42 +00002585ExprResult
John McCallb268a282010-08-23 23:25:46 +00002586Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00002587 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002588 const CXXScopeSpec &SS,
2589 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002590 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00002591 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00002592 // Even in dependent contexts, try to diagnose base expressions with
2593 // obviously wrong types, e.g.:
2594 //
2595 // T* t;
2596 // t.f;
2597 //
2598 // In Obj-C++, however, the above expression is valid, since it could be
2599 // accessing the 'f' property if T is an Obj-C interface. The extra check
2600 // allows this, while still reporting an error if T is a struct pointer.
2601 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00002602 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00002603 if (PT && (!getLangOptions().ObjC1 ||
2604 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00002605 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002606 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00002607 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00002608 return ExprError();
2609 }
2610 }
2611
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002612 assert(BaseType->isDependentType() ||
2613 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00002614 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00002615
2616 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2617 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00002618 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00002619 IsArrow, OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002620 SS.getScopeRep(),
John McCall10eae182009-11-30 22:42:35 +00002621 SS.getRange(),
2622 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002623 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00002624}
2625
2626/// We know that the given qualified member reference points only to
2627/// declarations which do not belong to the static type of the base
2628/// expression. Diagnose the problem.
2629static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2630 Expr *BaseExpr,
2631 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002632 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002633 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00002634 // If this is an implicit member access, use a different set of
2635 // diagnostics.
2636 if (!BaseExpr)
2637 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00002638
John McCall1e67dd62010-04-27 01:43:38 +00002639 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
2640 << SS.getRange() << R.getRepresentativeDecl() << BaseType;
John McCall10eae182009-11-30 22:42:35 +00002641}
2642
2643// Check whether the declarations we found through a nested-name
2644// specifier in a member expression are actually members of the base
2645// type. The restriction here is:
2646//
2647// C++ [expr.ref]p2:
2648// ... In these cases, the id-expression shall name a
2649// member of the class or of one of its base classes.
2650//
2651// So it's perfectly legitimate for the nested-name specifier to name
2652// an unrelated class, and for us to find an overload set including
2653// decls from classes which are not superclasses, as long as the decl
2654// we actually pick through overload resolution is from a superclass.
2655bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2656 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002657 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002658 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00002659 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2660 if (!BaseRT) {
2661 // We can't check this yet because the base type is still
2662 // dependent.
2663 assert(BaseType->isDependentType());
2664 return false;
2665 }
2666 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00002667
2668 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00002669 // If this is an implicit member reference and we find a
2670 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00002671 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00002672 return false;
John McCall10eae182009-11-30 22:42:35 +00002673
John McCall2d74de92009-12-01 22:10:20 +00002674 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00002675 DeclContext *DC = (*I)->getDeclContext();
2676 while (DC->isTransparentContext())
2677 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00002678
Douglas Gregora9c3e822010-07-28 22:27:52 +00002679 if (!DC->isRecord())
2680 continue;
2681
John McCall2d74de92009-12-01 22:10:20 +00002682 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00002683 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00002684
2685 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2686 return false;
2687 }
2688
John McCallcd4b4772009-12-02 03:53:29 +00002689 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00002690 return true;
2691}
2692
2693static bool
2694LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2695 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00002696 SourceLocation OpLoc, CXXScopeSpec &SS,
2697 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00002698 RecordDecl *RDecl = RTy->getDecl();
2699 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00002700 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00002701 << BaseRange))
2702 return true;
2703
John McCalle9cccd82010-06-16 08:42:20 +00002704 if (HasTemplateArgs) {
2705 // LookupTemplateName doesn't expect these both to exist simultaneously.
2706 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
2707
2708 bool MOUS;
2709 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
2710 return false;
2711 }
2712
John McCall2d74de92009-12-01 22:10:20 +00002713 DeclContext *DC = RDecl;
2714 if (SS.isSet()) {
2715 // If the member name was a qualified-id, look into the
2716 // nested-name-specifier.
2717 DC = SemaRef.computeDeclContext(SS, false);
2718
John McCall0b66eb32010-05-01 00:40:08 +00002719 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00002720 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2721 << SS.getRange() << DC;
2722 return true;
2723 }
2724
John McCall2d74de92009-12-01 22:10:20 +00002725 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002726
John McCall2d74de92009-12-01 22:10:20 +00002727 if (!isa<TypeDecl>(DC)) {
2728 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2729 << DC << SS.getRange();
2730 return true;
John McCall10eae182009-11-30 22:42:35 +00002731 }
2732 }
2733
John McCall2d74de92009-12-01 22:10:20 +00002734 // The record definition is complete, now look up the member.
2735 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00002736
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002737 if (!R.empty())
2738 return false;
2739
2740 // We didn't find anything with the given name, so try to correct
2741 // for typos.
2742 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00002743 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002744 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002745 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2746 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2747 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00002748 << FixItHint::CreateReplacement(R.getNameLoc(),
2749 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00002750 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2751 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2752 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002753 return false;
2754 } else {
2755 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002756 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002757 }
2758
John McCall10eae182009-11-30 22:42:35 +00002759 return false;
2760}
2761
John McCalldadc5752010-08-24 06:29:42 +00002762ExprResult
John McCallb268a282010-08-23 23:25:46 +00002763Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00002764 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002765 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002766 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002767 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00002768 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00002769 if (BaseType->isDependentType() ||
2770 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00002771 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00002772 IsArrow, OpLoc,
2773 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002774 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002775
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002776 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00002777
John McCall2d74de92009-12-01 22:10:20 +00002778 // Implicit member accesses.
2779 if (!Base) {
2780 QualType RecordTy = BaseType;
2781 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2782 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2783 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00002784 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00002785 return ExprError();
2786
2787 // Explicit member accesses.
2788 } else {
John McCalldadc5752010-08-24 06:29:42 +00002789 ExprResult Result =
John McCall2d74de92009-12-01 22:10:20 +00002790 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00002791 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00002792
2793 if (Result.isInvalid()) {
2794 Owned(Base);
2795 return ExprError();
2796 }
2797
2798 if (Result.get())
2799 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00002800
2801 // LookupMemberExpr can modify Base, and thus change BaseType
2802 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00002803 }
2804
John McCallb268a282010-08-23 23:25:46 +00002805 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00002806 OpLoc, IsArrow, SS, FirstQualifierInScope,
2807 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002808}
2809
John McCalldadc5752010-08-24 06:29:42 +00002810ExprResult
John McCallb268a282010-08-23 23:25:46 +00002811Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00002812 SourceLocation OpLoc, bool IsArrow,
2813 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00002814 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00002815 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00002816 const TemplateArgumentListInfo *TemplateArgs,
2817 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00002818 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00002819 if (IsArrow) {
2820 assert(BaseType->isPointerType());
2821 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2822 }
John McCalla8ae2222010-04-06 21:38:20 +00002823 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00002824
John McCallb268a282010-08-23 23:25:46 +00002825 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002826 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
2827 DeclarationName MemberName = MemberNameInfo.getName();
2828 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00002829
2830 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00002831 return ExprError();
2832
John McCall10eae182009-11-30 22:42:35 +00002833 if (R.empty()) {
2834 // Rederive where we looked up.
2835 DeclContext *DC = (SS.isSet()
2836 ? computeDeclContext(SS, false)
2837 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00002838
John McCall10eae182009-11-30 22:42:35 +00002839 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00002840 << MemberName << DC
2841 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00002842 return ExprError();
2843 }
2844
John McCall38836f02010-01-15 08:34:02 +00002845 // Diagnose lookups that find only declarations from a non-base
2846 // type. This is possible for either qualified lookups (which may
2847 // have been qualified with an unrelated type) or implicit member
2848 // expressions (which were found with unqualified lookup and thus
2849 // may have come from an enclosing scope). Note that it's okay for
2850 // lookup to find declarations from a non-base type as long as those
2851 // aren't the ones picked by overload resolution.
2852 if ((SS.isSet() || !BaseExpr ||
2853 (isa<CXXThisExpr>(BaseExpr) &&
2854 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00002855 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00002856 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00002857 return ExprError();
2858
2859 // Construct an unresolved result if we in fact got an unresolved
2860 // result.
2861 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall2d74de92009-12-01 22:10:20 +00002862 bool Dependent =
John McCall71739032009-12-19 02:05:44 +00002863 BaseExprType->isDependentType() ||
John McCall2d74de92009-12-01 22:10:20 +00002864 R.isUnresolvableResult() ||
John McCall1acbbb52010-02-02 06:20:04 +00002865 OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002866
John McCall58cc69d2010-01-27 01:50:18 +00002867 // Suppress any lookup-related diagnostics; we'll do these when we
2868 // pick a member.
2869 R.suppressDiagnostics();
2870
John McCall10eae182009-11-30 22:42:35 +00002871 UnresolvedMemberExpr *MemExpr
2872 = UnresolvedMemberExpr::Create(Context, Dependent,
2873 R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00002874 BaseExpr, BaseExprType,
2875 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002876 Qualifier, SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002877 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002878 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00002879
2880 return Owned(MemExpr);
2881 }
2882
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002883 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00002884 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00002885 NamedDecl *MemberDecl = R.getFoundDecl();
2886
2887 // FIXME: diagnose the presence of template arguments now.
2888
2889 // If the decl being referenced had an error, return an error for this
2890 // sub-expr without emitting another error, in order to avoid cascading
2891 // error cases.
2892 if (MemberDecl->isInvalidDecl())
2893 return ExprError();
2894
John McCall2d74de92009-12-01 22:10:20 +00002895 // Handle the implicit-member-access case.
2896 if (!BaseExpr) {
2897 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00002898 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002899 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00002900
Douglas Gregorb15af892010-01-07 23:12:05 +00002901 SourceLocation Loc = R.getNameLoc();
2902 if (SS.getRange().isValid())
2903 Loc = SS.getRange().getBegin();
2904 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00002905 }
2906
John McCall10eae182009-11-30 22:42:35 +00002907 bool ShouldCheckUse = true;
2908 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2909 // Don't diagnose the use of a virtual member function unless it's
2910 // explicitly qualified.
2911 if (MD->isVirtual() && !SS.isSet())
2912 ShouldCheckUse = false;
2913 }
2914
2915 // Check the use of this member.
2916 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2917 Owned(BaseExpr);
2918 return ExprError();
2919 }
2920
2921 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2922 // We may have found a field within an anonymous union or struct
2923 // (C++ [class.union]).
Eli Friedman78cde142009-12-04 07:18:51 +00002924 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2925 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall10eae182009-11-30 22:42:35 +00002926 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2927 BaseExpr, OpLoc);
2928
2929 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2930 QualType MemberType = FD->getType();
2931 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2932 MemberType = Ref->getPointeeType();
2933 else {
2934 Qualifiers BaseQuals = BaseType.getQualifiers();
2935 BaseQuals.removeObjCGCAttr();
2936 if (FD->isMutable()) BaseQuals.removeConst();
2937
2938 Qualifiers MemberQuals
2939 = Context.getCanonicalType(MemberType).getQualifiers();
2940
2941 Qualifiers Combined = BaseQuals + MemberQuals;
2942 if (Combined != MemberQuals)
2943 MemberType = Context.getQualifiedType(MemberType, Combined);
2944 }
2945
2946 MarkDeclarationReferenced(MemberLoc, FD);
John McCall16df1e52010-03-30 21:47:33 +00002947 if (PerformObjectMemberConversion(BaseExpr, Qualifier, FoundDecl, FD))
John McCall10eae182009-11-30 22:42:35 +00002948 return ExprError();
2949 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002950 FD, FoundDecl, MemberNameInfo,
2951 MemberType));
John McCall10eae182009-11-30 22:42:35 +00002952 }
2953
2954 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2955 MarkDeclarationReferenced(MemberLoc, Var);
2956 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002957 Var, FoundDecl, MemberNameInfo,
John McCall10eae182009-11-30 22:42:35 +00002958 Var->getType().getNonReferenceType()));
2959 }
2960
2961 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2962 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2963 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002964 MemberFn, FoundDecl, MemberNameInfo,
John McCall10eae182009-11-30 22:42:35 +00002965 MemberFn->getType()));
2966 }
2967
2968 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2969 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2970 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002971 Enum, FoundDecl, MemberNameInfo,
2972 Enum->getType()));
John McCall10eae182009-11-30 22:42:35 +00002973 }
2974
2975 Owned(BaseExpr);
2976
Douglas Gregor861eb802010-04-25 20:55:08 +00002977 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00002978 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002979 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00002980 << MemberName << BaseType << int(IsArrow);
2981 else
2982 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
2983 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00002984
Douglas Gregor861eb802010-04-25 20:55:08 +00002985 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
2986 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00002987 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00002988 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00002989}
2990
2991/// Look up the given member of the given non-type-dependent
2992/// expression. This can return in one of two ways:
2993/// * If it returns a sentinel null-but-valid result, the caller will
2994/// assume that lookup was performed and the results written into
2995/// the provided structure. It will take over from there.
2996/// * Otherwise, the returned expression will be produced in place of
2997/// an ordinary member expression.
2998///
2999/// The ObjCImpDecl bit is a gross hack that will need to be properly
3000/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00003001ExprResult
John McCall10eae182009-11-30 22:42:35 +00003002Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00003003 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003004 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00003005 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003006 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00003007
Steve Naroffeaaae462007-12-16 21:42:28 +00003008 // Perform default conversions.
3009 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003010
Steve Naroff185616f2007-07-26 03:11:44 +00003011 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00003012 assert(!BaseType->isDependentType());
3013
3014 DeclarationName MemberName = R.getLookupName();
3015 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00003016
3017 // If the user is trying to apply -> or . to a function pointer
John McCall10eae182009-11-30 22:42:35 +00003018 // type, it's probably because they forgot parentheses to call that
Douglas Gregord82ae382009-11-06 06:30:47 +00003019 // function. Suggest the addition of those parentheses, build the
3020 // call, and continue on.
3021 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
3022 if (const FunctionProtoType *Fun
3023 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
3024 QualType ResultTy = Fun->getResultType();
3025 if (Fun->getNumArgs() == 0 &&
John McCall10eae182009-11-30 22:42:35 +00003026 ((!IsArrow && ResultTy->isRecordType()) ||
3027 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregord82ae382009-11-06 06:30:47 +00003028 ResultTy->getAs<PointerType>()->getPointeeType()
3029 ->isRecordType()))) {
3030 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
3031 Diag(Loc, diag::err_member_reference_needs_call)
3032 << QualType(Fun, 0)
Douglas Gregora771f462010-03-31 17:46:05 +00003033 << FixItHint::CreateInsertion(Loc, "()");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003034
John McCalldadc5752010-08-24 06:29:42 +00003035 ExprResult NewBase
Douglas Gregorce5aa332010-09-09 16:33:13 +00003036 = ActOnCallExpr(0, BaseExpr, Loc, MultiExprArg(*this, 0, 0), Loc);
Douglas Gregor143d3672010-06-21 22:46:46 +00003037 BaseExpr = 0;
Douglas Gregord82ae382009-11-06 06:30:47 +00003038 if (NewBase.isInvalid())
John McCall10eae182009-11-30 22:42:35 +00003039 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003040
Douglas Gregord82ae382009-11-06 06:30:47 +00003041 BaseExpr = NewBase.takeAs<Expr>();
3042 DefaultFunctionArrayConversion(BaseExpr);
3043 BaseType = BaseExpr->getType();
3044 }
3045 }
3046 }
3047
David Chisnall9f57c292009-08-17 16:35:33 +00003048 // If this is an Objective-C pseudo-builtin and a definition is provided then
3049 // use that.
3050 if (BaseType->isObjCIdType()) {
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00003051 if (IsArrow) {
3052 // Handle the following exceptional case PObj->isa.
3053 if (const ObjCObjectPointerType *OPT =
3054 BaseType->getAs<ObjCObjectPointerType>()) {
John McCall8b07ec22010-05-15 11:32:37 +00003055 if (OPT->getObjectType()->isObjCId() &&
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00003056 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00003057 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
3058 Context.getObjCClassType()));
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00003059 }
3060 }
David Chisnall9f57c292009-08-17 16:35:33 +00003061 // We have an 'id' type. Rather than fall through, we check if this
3062 // is a reference to 'isa'.
3063 if (BaseType != Context.ObjCIdRedefinitionType) {
3064 BaseType = Context.ObjCIdRedefinitionType;
John McCalle3027922010-08-25 11:45:40 +00003065 ImpCastExprToType(BaseExpr, BaseType, CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003066 }
David Chisnall9f57c292009-08-17 16:35:33 +00003067 }
John McCall10eae182009-11-30 22:42:35 +00003068
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00003069 // If this is an Objective-C pseudo-builtin and a definition is provided then
3070 // use that.
3071 if (Context.isObjCSelType(BaseType)) {
3072 // We have an 'SEL' type. Rather than fall through, we check if this
3073 // is a reference to 'sel_id'.
3074 if (BaseType != Context.ObjCSelRedefinitionType) {
3075 BaseType = Context.ObjCSelRedefinitionType;
John McCalle3027922010-08-25 11:45:40 +00003076 ImpCastExprToType(BaseExpr, BaseType, CK_BitCast);
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00003077 }
3078 }
John McCall10eae182009-11-30 22:42:35 +00003079
Steve Naroff185616f2007-07-26 03:11:44 +00003080 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003081
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003082 // Handle properties on ObjC 'Class' types.
John McCall10eae182009-11-30 22:42:35 +00003083 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003084 // Also must look for a getter name which uses property syntax.
3085 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3086 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3087 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3088 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3089 ObjCMethodDecl *Getter;
3090 // FIXME: need to also look locally in the implementation.
3091 if ((Getter = IFace->lookupClassMethod(Sel))) {
3092 // Check the use of this method.
3093 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3094 return ExprError();
3095 }
3096 // If we found a getter then this may be a valid dot-reference, we
3097 // will look for the matching setter, in case it is needed.
3098 Selector SetterSel =
3099 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3100 PP.getSelectorTable(), Member);
3101 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3102 if (!Setter) {
3103 // If this reference is in an @implementation, also check for 'private'
3104 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00003105 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003106 }
3107 // Look through local category implementations associated with the class.
3108 if (!Setter)
3109 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003110
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003111 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3112 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003113
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003114 if (Getter || Setter) {
3115 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003116
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003117 if (Getter)
Douglas Gregor603d81b2010-07-13 08:18:22 +00003118 PType = Getter->getSendResultType();
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003119 else
3120 // Get the expression type from Setter's incoming parameter.
3121 PType = (*(Setter->param_end() -1))->getType();
3122 // FIXME: we must check that the setter has property type.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003123 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003124 PType,
3125 Setter, MemberLoc, BaseExpr));
3126 }
3127 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3128 << MemberName << BaseType);
3129 }
3130 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003131
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003132 if (BaseType->isObjCClassType() &&
3133 BaseType != Context.ObjCClassRedefinitionType) {
3134 BaseType = Context.ObjCClassRedefinitionType;
John McCalle3027922010-08-25 11:45:40 +00003135 ImpCastExprToType(BaseExpr, BaseType, CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003136 }
Mike Stump11289f42009-09-09 15:08:12 +00003137
John McCall10eae182009-11-30 22:42:35 +00003138 if (IsArrow) {
3139 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00003140 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00003141 else if (BaseType->isObjCObjectPointerType())
3142 ;
John McCalla928c652009-12-07 22:46:59 +00003143 else if (BaseType->isRecordType()) {
3144 // Recover from arrow accesses to records, e.g.:
3145 // struct MyRecord foo;
3146 // foo->bar
3147 // This is actually well-formed in C++ if MyRecord has an
3148 // overloaded operator->, but that should have been dealt with
3149 // by now.
3150 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3151 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003152 << FixItHint::CreateReplacement(OpLoc, ".");
John McCalla928c652009-12-07 22:46:59 +00003153 IsArrow = false;
3154 } else {
John McCall10eae182009-11-30 22:42:35 +00003155 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3156 << BaseType << BaseExpr->getSourceRange();
3157 return ExprError();
Anders Carlsson524d5a42009-05-16 20:31:20 +00003158 }
John McCalla928c652009-12-07 22:46:59 +00003159 } else {
3160 // Recover from dot accesses to pointers, e.g.:
3161 // type *foo;
3162 // foo.bar
3163 // This is actually well-formed in two cases:
3164 // - 'type' is an Objective C type
3165 // - 'bar' is a pseudo-destructor name which happens to refer to
3166 // the appropriate pointer type
3167 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3168 const PointerType *PT = BaseType->getAs<PointerType>();
3169 if (PT && PT->getPointeeType()->isRecordType()) {
3170 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3171 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003172 << FixItHint::CreateReplacement(OpLoc, "->");
John McCalla928c652009-12-07 22:46:59 +00003173 BaseType = PT->getPointeeType();
3174 IsArrow = true;
3175 }
3176 }
John McCall10eae182009-11-30 22:42:35 +00003177 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003178
John McCall8b07ec22010-05-15 11:32:37 +00003179 // Handle field access to simple records.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003180 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCall2d74de92009-12-01 22:10:20 +00003181 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
John McCalle9cccd82010-06-16 08:42:20 +00003182 RTy, OpLoc, SS, HasTemplateArgs))
Douglas Gregordd430f72009-01-19 19:26:10 +00003183 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003184 return Owned((Expr*) 0);
Chris Lattnerb63a7452008-07-21 04:28:12 +00003185 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003186
Chris Lattnerdc420f42008-07-21 04:59:05 +00003187 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
3188 // (*Obj).ivar.
John McCall10eae182009-11-30 22:42:35 +00003189 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00003190 (!IsArrow && BaseType->isObjCObjectType())) {
John McCall9dd450b2009-09-21 23:43:11 +00003191 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
John McCall8b07ec22010-05-15 11:32:37 +00003192 ObjCInterfaceDecl *IDecl =
3193 OPT ? OPT->getInterfaceDecl()
3194 : BaseType->getAs<ObjCObjectType>()->getInterface();
3195 if (IDecl) {
Anders Carlssonf571c112009-08-26 18:25:21 +00003196 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3197
Steve Naroffa057ba92009-07-16 00:25:06 +00003198 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00003199 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00003200
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003201 if (!IV) {
3202 // Attempt to correct for typos in ivar names.
3203 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3204 LookupMemberName);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003205 if (CorrectTypo(Res, 0, 0, IDecl, false, CTC_MemberLookup) &&
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003206 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003207 Diag(R.getNameLoc(),
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003208 diag::err_typecheck_member_reference_ivar_suggest)
3209 << IDecl->getDeclName() << MemberName << IV->getDeclName()
Douglas Gregora771f462010-03-31 17:46:05 +00003210 << FixItHint::CreateReplacement(R.getNameLoc(),
3211 IV->getNameAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003212 Diag(IV->getLocation(), diag::note_previous_decl)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003213 << IV->getDeclName();
Douglas Gregorc048c522010-06-29 19:27:42 +00003214 } else {
3215 Res.clear();
3216 Res.setLookupName(Member);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003217 }
3218 }
3219
Steve Naroffa057ba92009-07-16 00:25:06 +00003220 if (IV) {
3221 // If the decl being referenced had an error, return an error for this
3222 // sub-expr without emitting another error, in order to avoid cascading
3223 // error cases.
3224 if (IV->isInvalidDecl())
3225 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003226
Steve Naroffa057ba92009-07-16 00:25:06 +00003227 // Check whether we can reference this field.
3228 if (DiagnoseUseOfDecl(IV, MemberLoc))
3229 return ExprError();
3230 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3231 IV->getAccessControl() != ObjCIvarDecl::Package) {
3232 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3233 if (ObjCMethodDecl *MD = getCurMethodDecl())
3234 ClassOfMethodDecl = MD->getClassInterface();
3235 else if (ObjCImpDecl && getCurFunctionDecl()) {
3236 // Case of a c-function declared inside an objc implementation.
3237 // FIXME: For a c-style function nested inside an objc implementation
3238 // class, there is no implementation context available, so we pass
3239 // down the context as argument to this routine. Ideally, this context
3240 // need be passed down in the AST node and somehow calculated from the
3241 // AST for a function decl.
Mike Stump11289f42009-09-09 15:08:12 +00003242 if (ObjCImplementationDecl *IMPD =
John McCall48871652010-08-21 09:40:31 +00003243 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
Steve Naroffa057ba92009-07-16 00:25:06 +00003244 ClassOfMethodDecl = IMPD->getClassInterface();
3245 else if (ObjCCategoryImplDecl* CatImplClass =
John McCall48871652010-08-21 09:40:31 +00003246 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
Steve Naroffa057ba92009-07-16 00:25:06 +00003247 ClassOfMethodDecl = CatImplClass->getClassInterface();
3248 }
Mike Stump11289f42009-09-09 15:08:12 +00003249
3250 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3251 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00003252 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00003253 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00003254 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00003255 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3256 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00003257 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00003258 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00003259 }
Steve Naroffa057ba92009-07-16 00:25:06 +00003260
3261 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3262 MemberLoc, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00003263 IsArrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00003264 }
Steve Naroffa057ba92009-07-16 00:25:06 +00003265 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00003266 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00003267 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00003268 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00003269 }
Steve Naroff1329fa02009-07-15 18:40:39 +00003270 // Handle properties on 'id' and qualified "id".
John McCall10eae182009-11-30 22:42:35 +00003271 if (!IsArrow && (BaseType->isObjCIdType() ||
3272 BaseType->isObjCQualifiedIdType())) {
John McCall9dd450b2009-09-21 23:43:11 +00003273 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00003274 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003275
Steve Naroff7cae42b2009-07-10 23:34:53 +00003276 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00003277 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003278 if (Decl *PMDecl = FindGetterSetterNameDecl(QIdTy, Member, Sel,
3279 Context)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003280 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3281 // Check the use of this declaration
3282 if (DiagnoseUseOfDecl(PD, MemberLoc))
3283 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003284
Steve Naroff7cae42b2009-07-10 23:34:53 +00003285 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3286 MemberLoc, BaseExpr));
3287 }
3288 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3289 // Check the use of this method.
3290 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3291 return ExprError();
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003292 Selector SetterSel =
3293 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3294 PP.getSelectorTable(), Member);
3295 ObjCMethodDecl *SMD = 0;
3296 if (Decl *SDecl = FindGetterSetterNameDecl(QIdTy, /*Property id*/0,
3297 SetterSel, Context))
3298 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3299 QualType PType = OMD->getSendResultType();
3300 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(OMD, PType,
3301 SMD,
3302 MemberLoc,
3303 BaseExpr));
Steve Naroff7cae42b2009-07-10 23:34:53 +00003304 }
3305 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003306
Steve Naroff7cae42b2009-07-10 23:34:53 +00003307 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00003308 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003309 }
Alexis Huntc46382e2010-04-28 23:02:27 +00003310
Chris Lattnerdc420f42008-07-21 04:59:05 +00003311 // Handle Objective-C property access, which is "Obj.property" where Obj is a
3312 // pointer to a (potentially qualified) interface type.
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00003313 if (!IsArrow)
3314 if (const ObjCObjectPointerType *OPT =
3315 BaseType->getAsObjCInterfacePointerType())
Chris Lattner90c58fa2010-04-11 07:51:10 +00003316 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003317
Steve Naroffe87026a2009-07-24 17:54:45 +00003318 // Handle the following exceptional case (*Obj).isa.
John McCall10eae182009-11-30 22:42:35 +00003319 if (!IsArrow &&
John McCall8b07ec22010-05-15 11:32:37 +00003320 BaseType->isObjCObjectType() &&
3321 BaseType->getAs<ObjCObjectType>()->isObjCId() &&
Anders Carlssonf571c112009-08-26 18:25:21 +00003322 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00003323 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00003324 Context.getObjCClassType()));
Steve Naroffe87026a2009-07-24 17:54:45 +00003325
Chris Lattnerb63a7452008-07-21 04:28:12 +00003326 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003327 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00003328 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerb63a7452008-07-21 04:28:12 +00003329 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3330 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003331 return ExprError();
Anders Carlssonf571c112009-08-26 18:25:21 +00003332 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Narofff6009ed2009-01-21 00:14:39 +00003333 MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003334 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003335
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003336 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3337 << BaseType << BaseExpr->getSourceRange();
3338
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003339 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00003340}
3341
John McCall10eae182009-11-30 22:42:35 +00003342/// The main callback when the parser finds something like
3343/// expression . [nested-name-specifier] identifier
3344/// expression -> [nested-name-specifier] identifier
3345/// where 'identifier' encompasses a fairly broad spectrum of
3346/// possibilities, including destructor and operator references.
3347///
3348/// \param OpKind either tok::arrow or tok::period
3349/// \param HasTrailingLParen whether the next token is '(', which
3350/// is used to diagnose mis-uses of special members that can
3351/// only be called
3352/// \param ObjCImpDecl the current ObjC @implementation decl;
3353/// this is an ugly hack around the fact that ObjC @implementations
3354/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00003355ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall10eae182009-11-30 22:42:35 +00003356 SourceLocation OpLoc,
3357 tok::TokenKind OpKind,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003358 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003359 UnqualifiedId &Id,
John McCall48871652010-08-21 09:40:31 +00003360 Decl *ObjCImpDecl,
John McCall10eae182009-11-30 22:42:35 +00003361 bool HasTrailingLParen) {
3362 if (SS.isSet() && SS.isInvalid())
3363 return ExprError();
3364
3365 TemplateArgumentListInfo TemplateArgsBuffer;
3366
3367 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003368 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00003369 const TemplateArgumentListInfo *TemplateArgs;
3370 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003371 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003372
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003373 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00003374 bool IsArrow = (OpKind == tok::arrow);
3375
3376 NamedDecl *FirstQualifierInScope
3377 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3378 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3379
3380 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003381 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003382 if (Result.isInvalid()) return ExprError();
3383 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00003384
Douglas Gregor41f90302010-04-12 20:54:26 +00003385 if (Base->getType()->isDependentType() || Name.isDependentName() ||
3386 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00003387 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00003388 IsArrow, OpLoc,
3389 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003390 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003391 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003392 LookupResult R(*this, NameInfo, LookupMemberName);
John McCalle9cccd82010-06-16 08:42:20 +00003393 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3394 SS, ObjCImpDecl, TemplateArgs != 0);
Alexis Huntc46382e2010-04-28 23:02:27 +00003395
John McCalle9cccd82010-06-16 08:42:20 +00003396 if (Result.isInvalid()) {
3397 Owned(Base);
3398 return ExprError();
3399 }
John McCall10eae182009-11-30 22:42:35 +00003400
John McCalle9cccd82010-06-16 08:42:20 +00003401 if (Result.get()) {
3402 // The only way a reference to a destructor can be used is to
3403 // immediately call it, which falls into this case. If the
3404 // next token is not a '(', produce a diagnostic and build the
3405 // call now.
3406 if (!HasTrailingLParen &&
3407 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00003408 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00003409
John McCalle9cccd82010-06-16 08:42:20 +00003410 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00003411 }
3412
John McCallb268a282010-08-23 23:25:46 +00003413 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00003414 OpLoc, IsArrow, SS, FirstQualifierInScope,
3415 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003416 }
3417
3418 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003419}
3420
John McCalldadc5752010-08-24 06:29:42 +00003421ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Anders Carlsson355933d2009-08-25 03:49:14 +00003422 FunctionDecl *FD,
3423 ParmVarDecl *Param) {
3424 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003425 Diag(CallLoc,
Anders Carlsson355933d2009-08-25 03:49:14 +00003426 diag::err_use_of_default_argument_to_function_declared_later) <<
3427 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003428 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-08-25 03:49:14 +00003429 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003430 return ExprError();
3431 }
3432
3433 if (Param->hasUninstantiatedDefaultArg()) {
3434 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003435
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003436 // Instantiate the expression.
3437 MultiLevelTemplateArgumentList ArgList
3438 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003439
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003440 std::pair<const TemplateArgument *, unsigned> Innermost
3441 = ArgList.getInnermost();
3442 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3443 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003444
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003445 ExprResult Result = SubstExpr(UninstExpr, ArgList);
3446 if (Result.isInvalid())
3447 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003448
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003449 // Check the expression as an initializer for the parameter.
3450 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003451 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003452 InitializationKind Kind
3453 = InitializationKind::CreateCopy(Param->getLocation(),
3454 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3455 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003456
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003457 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3458 Result = InitSeq.Perform(*this, Entity, Kind,
3459 MultiExprArg(*this, &ResultE, 1));
3460 if (Result.isInvalid())
3461 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003462
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003463 // Build the default argument expression.
3464 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3465 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003466 }
3467
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003468 // If the default expression creates temporaries, we need to
3469 // push them to the current stack of expression temporaries so they'll
3470 // be properly destroyed.
3471 // FIXME: We should really be rebuilding the default argument with new
3472 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003473 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3474 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3475 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3476 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3477 ExprTemporaries.push_back(Temporary);
3478 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003479
3480 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003481 // Just mark all of the declarations in this potentially-evaluated expression
3482 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003483 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003484 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003485}
3486
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003487/// ConvertArgumentsForCall - Converts the arguments specified in
3488/// Args/NumArgs to the parameter types of the function FDecl with
3489/// function prototype Proto. Call is the call expression itself, and
3490/// Fn is the function expression. For a C++ member function, this
3491/// routine does not attempt to convert the object argument. Returns
3492/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003493bool
3494Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003495 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003496 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003497 Expr **Args, unsigned NumArgs,
3498 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003499 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003500 // assignment, to the types of the corresponding parameter, ...
3501 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003502 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003503
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003504 // If too few arguments are available (and we don't have default
3505 // arguments for the remaining parameters), don't make the call.
3506 if (NumArgs < NumArgsInProto) {
3507 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3508 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003509 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003510 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003511 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003512 }
3513
3514 // If too many are passed and not variadic, error on the extras and drop
3515 // them.
3516 if (NumArgs > NumArgsInProto) {
3517 if (!Proto->isVariadic()) {
3518 Diag(Args[NumArgsInProto]->getLocStart(),
3519 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003520 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003521 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003522 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3523 Args[NumArgs-1]->getLocEnd());
3524 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003525 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003526 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003527 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003528 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003529 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003530 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003531 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3532 if (Fn->getType()->isBlockPointerType())
3533 CallType = VariadicBlock; // Block
3534 else if (isa<MemberExpr>(Fn))
3535 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003536 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003537 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003538 if (Invalid)
3539 return true;
3540 unsigned TotalNumArgs = AllArgs.size();
3541 for (unsigned i = 0; i < TotalNumArgs; ++i)
3542 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003543
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003544 return false;
3545}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003546
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003547bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3548 FunctionDecl *FDecl,
3549 const FunctionProtoType *Proto,
3550 unsigned FirstProtoArg,
3551 Expr **Args, unsigned NumArgs,
3552 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003553 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003554 unsigned NumArgsInProto = Proto->getNumArgs();
3555 unsigned NumArgsToCheck = NumArgs;
3556 bool Invalid = false;
3557 if (NumArgs != NumArgsInProto)
3558 // Use default arguments for missing arguments
3559 NumArgsToCheck = NumArgsInProto;
3560 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003561 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003562 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003563 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003564
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003565 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003566 if (ArgIx < NumArgs) {
3567 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003568
Eli Friedman3164fb12009-03-22 22:00:50 +00003569 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3570 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003571 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003572 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003573 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003574
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003575 // Pass the argument
3576 ParmVarDecl *Param = 0;
3577 if (FDecl && i < FDecl->getNumParams())
3578 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003579
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003580 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003581 Param? InitializedEntity::InitializeParameter(Context, Param)
3582 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00003583 ExprResult ArgE = PerformCopyInitialization(Entity,
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003584 SourceLocation(),
3585 Owned(Arg));
3586 if (ArgE.isInvalid())
3587 return true;
3588
3589 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003590 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003591 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003592
John McCalldadc5752010-08-24 06:29:42 +00003593 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003594 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003595 if (ArgExpr.isInvalid())
3596 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003597
Anders Carlsson355933d2009-08-25 03:49:14 +00003598 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003599 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003600 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003601 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003602
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003603 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003604 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003605 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00003606 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003607 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00003608 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003609 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003610 }
3611 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003612 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003613}
3614
Steve Naroff83895f72007-09-16 03:34:24 +00003615/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003616/// This provides the location of the left/right parens and a list of comma
3617/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003618ExprResult
John McCallb268a282010-08-23 23:25:46 +00003619Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003620 MultiExprArg args, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003621 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003622
3623 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003624 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003625 if (Result.isInvalid()) return ExprError();
3626 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003627
John McCallb268a282010-08-23 23:25:46 +00003628 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003629
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003630 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003631 // If this is a pseudo-destructor expression, build the call immediately.
3632 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3633 if (NumArgs > 0) {
3634 // Pseudo-destructor calls should not have any arguments.
3635 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003636 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003637 SourceRange(Args[0]->getLocStart(),
3638 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003639
Douglas Gregorad8a3362009-09-04 17:36:40 +00003640 NumArgs = 0;
3641 }
Mike Stump11289f42009-09-09 15:08:12 +00003642
Douglas Gregorad8a3362009-09-04 17:36:40 +00003643 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3644 RParenLoc));
3645 }
Mike Stump11289f42009-09-09 15:08:12 +00003646
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003647 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003648 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003649 // FIXME: Will need to cache the results of name lookup (including ADL) in
3650 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003651 bool Dependent = false;
3652 if (Fn->isTypeDependent())
3653 Dependent = true;
3654 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3655 Dependent = true;
3656
3657 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003658 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003659 Context.DependentTy, RParenLoc));
3660
3661 // Determine whether this is a call to an object (C++ [over.call.object]).
3662 if (Fn->getType()->isRecordType())
3663 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003664 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003665
John McCall10eae182009-11-30 22:42:35 +00003666 Expr *NakedFn = Fn->IgnoreParens();
3667
3668 // Determine whether this is a call to an unresolved member function.
3669 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3670 // If lookup was unresolved but not dependent (i.e. didn't find
3671 // an unresolved using declaration), it has to be an overloaded
3672 // function set, which means it must contain either multiple
3673 // declarations (all methods or method templates) or a single
3674 // method template.
3675 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00003676 isa<FunctionTemplateDecl>(
3677 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00003678 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00003679
John McCall2d74de92009-12-01 22:10:20 +00003680 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003681 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003682 }
3683
Douglas Gregore254f902009-02-04 00:32:51 +00003684 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00003685 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003686 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00003687 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00003688 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003689 RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003690 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003691
Anders Carlsson61914b52009-10-03 17:40:22 +00003692 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00003693 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCalle3027922010-08-25 11:45:40 +00003694 if (BO->getOpcode() == BO_PtrMemD ||
3695 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00003696 if (const FunctionProtoType *FPT
3697 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00003698 QualType ResultTy = FPT->getCallResultType(Context);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003699
John McCallb268a282010-08-23 23:25:46 +00003700 CXXMemberCallExpr *TheCall
3701 = new (Context) CXXMemberCallExpr(Context, BO, Args,
3702 NumArgs, ResultTy,
3703 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003704
3705 if (CheckCallReturnType(FPT->getResultType(),
3706 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00003707 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003708 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00003709
John McCallb268a282010-08-23 23:25:46 +00003710 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003711 RParenLoc))
3712 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00003713
John McCallb268a282010-08-23 23:25:46 +00003714 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003715 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003716 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003717 diag::err_typecheck_call_not_function)
3718 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00003719 }
3720 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003721 }
3722
Douglas Gregore254f902009-02-04 00:32:51 +00003723 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003724 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00003725 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003726
Eli Friedmane14b1992009-12-26 03:35:45 +00003727 Expr *NakedFn = Fn->IgnoreParens();
John McCall57500772009-12-16 12:17:52 +00003728 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3729 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
Douglas Gregor2fb18b72010-04-14 20:27:54 +00003730 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003731 RParenLoc);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003732 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003733
John McCall57500772009-12-16 12:17:52 +00003734 NamedDecl *NDecl = 0;
3735 if (isa<DeclRefExpr>(NakedFn))
3736 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3737
John McCall2d74de92009-12-01 22:10:20 +00003738 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3739}
3740
John McCall57500772009-12-16 12:17:52 +00003741/// BuildResolvedCallExpr - Build a call to a resolved expression,
3742/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003743/// unary-convert to an expression of function-pointer or
3744/// block-pointer type.
3745///
3746/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003747ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003748Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3749 SourceLocation LParenLoc,
3750 Expr **Args, unsigned NumArgs,
3751 SourceLocation RParenLoc) {
3752 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3753
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003754 // Promote the function operand.
3755 UsualUnaryConversions(Fn);
3756
Chris Lattner08464942007-12-28 05:29:59 +00003757 // Make the call expr early, before semantic checks. This guarantees cleanup
3758 // of arguments and function on error.
John McCallb268a282010-08-23 23:25:46 +00003759 CallExpr *TheCall = new (Context) CallExpr(Context, Fn,
3760 Args, NumArgs,
3761 Context.BoolTy,
3762 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003763
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003764 const FunctionType *FuncT;
3765 if (!Fn->getType()->isBlockPointerType()) {
3766 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3767 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003768 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003769 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003770 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3771 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00003772 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003773 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003774 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00003775 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003776 }
Chris Lattner08464942007-12-28 05:29:59 +00003777 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003778 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3779 << Fn->getType() << Fn->getSourceRange());
3780
Eli Friedman3164fb12009-03-22 22:00:50 +00003781 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003782 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003783 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003784 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003785 return ExprError();
3786
Chris Lattner08464942007-12-28 05:29:59 +00003787 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003788 TheCall->setType(FuncT->getCallResultType(Context));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003789
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003790 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003791 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003792 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003793 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003794 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003795 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003796
Douglas Gregord8e97de2009-04-02 15:37:10 +00003797 if (FDecl) {
3798 // Check if we have too few/too many template arguments, based
3799 // on our knowledge of the function definition.
3800 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003801 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003802 const FunctionProtoType *Proto =
John McCall9dd450b2009-09-21 23:43:11 +00003803 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003804 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3805 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3806 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3807 }
3808 }
Douglas Gregord8e97de2009-04-02 15:37:10 +00003809 }
3810
Steve Naroff0b661582007-08-28 23:30:39 +00003811 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003812 for (unsigned i = 0; i != NumArgs; i++) {
3813 Expr *Arg = Args[i];
3814 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00003815 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3816 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00003817 PDiag(diag::err_call_incomplete_argument)
3818 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003819 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003820 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003821 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003822 }
Chris Lattner08464942007-12-28 05:29:59 +00003823
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003824 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3825 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003826 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3827 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003828
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003829 // Check for sentinels
3830 if (NDecl)
3831 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003832
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003833 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003834 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003835 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003836 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003837
Douglas Gregor15fc9562009-09-12 00:22:50 +00003838 if (unsigned BuiltinID = FDecl->getBuiltinID())
John McCallb268a282010-08-23 23:25:46 +00003839 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003840 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003841 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003842 return ExprError();
3843 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003844
John McCallb268a282010-08-23 23:25:46 +00003845 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003846}
3847
John McCalldadc5752010-08-24 06:29:42 +00003848ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003849Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003850 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003851 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003852 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003853 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003854
3855 TypeSourceInfo *TInfo;
3856 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3857 if (!TInfo)
3858 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3859
John McCallb268a282010-08-23 23:25:46 +00003860 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003861}
3862
John McCalldadc5752010-08-24 06:29:42 +00003863ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003864Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00003865 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003866 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003867
Eli Friedman37a186d2008-05-20 05:22:08 +00003868 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003869 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003870 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3871 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003872 } else if (!literalType->isDependentType() &&
3873 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003874 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003875 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003876 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003877 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003878
Douglas Gregor85dabae2009-12-16 01:38:02 +00003879 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003880 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003881 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003882 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00003883 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00003884 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003885 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00003886 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003887 &literalType);
3888 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003889 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00003890 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003891
Chris Lattner79413952008-12-04 23:50:19 +00003892 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003893 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003894 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003895 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003896 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003897
John McCall5d7aa7f2010-01-19 22:33:45 +00003898 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Steve Narofff6009ed2009-01-21 00:14:39 +00003899 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003900}
3901
John McCalldadc5752010-08-24 06:29:42 +00003902ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00003903Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003904 SourceLocation RBraceLoc) {
3905 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00003906 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003907
Steve Naroff30d242c2007-09-15 18:49:24 +00003908 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003909 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003910
Ted Kremenekac034612010-04-13 23:39:13 +00003911 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3912 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003913 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003914 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003915}
3916
John McCalle3027922010-08-25 11:45:40 +00003917static CastKind getScalarCastKind(ASTContext &Context,
Anders Carlsson094c4592009-10-18 18:12:03 +00003918 QualType SrcTy, QualType DestTy) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003919 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003920 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003921
3922 if (SrcTy->hasPointerRepresentation()) {
3923 if (DestTy->hasPointerRepresentation())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003924 return DestTy->isObjCObjectPointerType() ?
John McCalle3027922010-08-25 11:45:40 +00003925 CK_AnyPointerToObjCPointerCast :
3926 CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003927 if (DestTy->isIntegerType())
John McCalle3027922010-08-25 11:45:40 +00003928 return CK_PointerToIntegral;
Anders Carlsson094c4592009-10-18 18:12:03 +00003929 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003930
Anders Carlsson094c4592009-10-18 18:12:03 +00003931 if (SrcTy->isIntegerType()) {
3932 if (DestTy->isIntegerType())
John McCalle3027922010-08-25 11:45:40 +00003933 return CK_IntegralCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003934 if (DestTy->hasPointerRepresentation())
John McCalle3027922010-08-25 11:45:40 +00003935 return CK_IntegralToPointer;
Anders Carlsson094c4592009-10-18 18:12:03 +00003936 if (DestTy->isRealFloatingType())
John McCalle3027922010-08-25 11:45:40 +00003937 return CK_IntegralToFloating;
Anders Carlsson094c4592009-10-18 18:12:03 +00003938 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003939
Anders Carlsson094c4592009-10-18 18:12:03 +00003940 if (SrcTy->isRealFloatingType()) {
3941 if (DestTy->isRealFloatingType())
John McCalle3027922010-08-25 11:45:40 +00003942 return CK_FloatingCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003943 if (DestTy->isIntegerType())
John McCalle3027922010-08-25 11:45:40 +00003944 return CK_FloatingToIntegral;
Anders Carlsson094c4592009-10-18 18:12:03 +00003945 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003946
Anders Carlsson094c4592009-10-18 18:12:03 +00003947 // FIXME: Assert here.
3948 // assert(false && "Unhandled cast combination!");
John McCalle3027922010-08-25 11:45:40 +00003949 return CK_Unknown;
Anders Carlsson094c4592009-10-18 18:12:03 +00003950}
3951
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003952/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003953bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
John McCalle3027922010-08-25 11:45:40 +00003954 CastKind& Kind,
John McCallcf142162010-08-07 06:22:56 +00003955 CXXCastPath &BasePath,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003956 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003957 if (getLangOptions().CPlusPlus)
Anders Carlssona70cff62010-04-24 19:06:50 +00003958 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, BasePath,
3959 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003960
Douglas Gregorb92a1562010-02-03 00:27:59 +00003961 DefaultFunctionArrayLvalueConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003962
3963 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3964 // type needs to be scalar.
3965 if (castType->isVoidType()) {
3966 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00003967 Kind = CK_ToVoid;
Anders Carlssonef918ac2009-10-16 02:35:04 +00003968 return false;
3969 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003970
Eli Friedmane98194d2010-07-17 20:43:49 +00003971 if (RequireCompleteType(TyR.getBegin(), castType,
3972 diag::err_typecheck_cast_to_incomplete))
3973 return true;
3974
Anders Carlssonef918ac2009-10-16 02:35:04 +00003975 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003976 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003977 (castType->isStructureType() || castType->isUnionType())) {
3978 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003979 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003980 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3981 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003982 Kind = CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003983 return false;
3984 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003985
Anders Carlsson525b76b2009-10-16 02:48:28 +00003986 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003987 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003988 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003989 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003990 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003991 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003992 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00003993 castExpr->getType()) &&
3994 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003995 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3996 << castExpr->getSourceRange();
3997 break;
3998 }
3999 }
4000 if (Field == FieldEnd)
4001 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4002 << castExpr->getType() << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004003 Kind = CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00004004 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004005 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004006
Anders Carlsson525b76b2009-10-16 02:48:28 +00004007 // Reject any other conversions to non-scalar types.
4008 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
4009 << castType << castExpr->getSourceRange();
4010 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004011
4012 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00004013 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004014 return Diag(castExpr->getLocStart(),
4015 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004016 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004017 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004018
4019 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00004020 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004021
Anders Carlsson525b76b2009-10-16 02:48:28 +00004022 if (castType->isVectorType())
4023 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
4024 if (castExpr->getType()->isVectorType())
4025 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
4026
Anders Carlsson43d70f82009-10-16 05:23:41 +00004027 if (isa<ObjCSelectorExpr>(castExpr))
4028 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004029
Anders Carlsson525b76b2009-10-16 02:48:28 +00004030 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004031 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00004032 if (!castExprType->isIntegralType(Context) &&
Douglas Gregorb90df602010-06-16 00:17:44 +00004033 castExprType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004034 return Diag(castExpr->getLocStart(),
4035 diag::err_cast_pointer_from_non_pointer_int)
4036 << castExprType << castExpr->getSourceRange();
4037 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004038 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004039 return Diag(castExpr->getLocStart(),
4040 diag::err_cast_pointer_to_non_pointer_int)
4041 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004042 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004043
4044 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
John McCall2b5c1b22010-08-12 21:44:57 +00004045
John McCalle3027922010-08-25 11:45:40 +00004046 if (Kind == CK_Unknown || Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004047 CheckCastAlign(castExpr, castType, TyR);
4048
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004049 return false;
4050}
4051
Anders Carlsson525b76b2009-10-16 02:48:28 +00004052bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004053 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004054 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004055
Anders Carlssonde71adf2007-11-27 05:51:55 +00004056 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004057 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004058 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004059 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004060 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004061 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004062 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004063 } else
4064 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004065 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004066 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004067
John McCalle3027922010-08-25 11:45:40 +00004068 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004069 return false;
4070}
4071
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004072bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCalle3027922010-08-25 11:45:40 +00004073 CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004074 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004075
Anders Carlsson43d70f82009-10-16 05:23:41 +00004076 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004077
Nate Begemanc8961a42009-06-27 22:05:55 +00004078 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4079 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004080 if (SrcTy->isVectorType()) {
4081 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
4082 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4083 << DestTy << SrcTy << R;
John McCalle3027922010-08-25 11:45:40 +00004084 Kind = CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00004085 return false;
4086 }
4087
Nate Begemanbd956c42009-06-28 02:36:38 +00004088 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004089 // conversion will take place first from scalar to elt type, and then
4090 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004091 if (SrcTy->isPointerType())
4092 return Diag(R.getBegin(),
4093 diag::err_invalid_conversion_between_vector_and_scalar)
4094 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004095
4096 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4097 ImpCastExprToType(CastExpr, DestElemTy,
4098 getScalarCastKind(Context, SrcTy, DestElemTy));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004099
John McCalle3027922010-08-25 11:45:40 +00004100 Kind = CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00004101 return false;
4102}
4103
John McCalldadc5752010-08-24 06:29:42 +00004104ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004105Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004106 SourceLocation RParenLoc, Expr *castExpr) {
4107 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004108 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004109
John McCall97513962010-01-15 18:39:57 +00004110 TypeSourceInfo *castTInfo;
4111 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4112 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00004113 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00004114
Nate Begeman5ec4b312009-08-10 23:49:36 +00004115 // If the Expr being casted is a ParenListExpr, handle it specially.
4116 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00004117 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00004118 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00004119
John McCallb268a282010-08-23 23:25:46 +00004120 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004121}
4122
John McCalldadc5752010-08-24 06:29:42 +00004123ExprResult
John McCallebe54742010-01-15 18:56:44 +00004124Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004125 SourceLocation RParenLoc, Expr *castExpr) {
John McCalle3027922010-08-25 11:45:40 +00004126 CastKind Kind = CK_Unknown;
John McCallcf142162010-08-07 06:22:56 +00004127 CXXCastPath BasePath;
John McCallebe54742010-01-15 18:56:44 +00004128 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
Anders Carlssona70cff62010-04-24 19:06:50 +00004129 Kind, BasePath))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004130 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00004131
John McCallcf142162010-08-07 06:22:56 +00004132 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +00004133 Ty->getType().getNonLValueExprType(Context),
John McCallcf142162010-08-07 06:22:56 +00004134 Kind, castExpr, &BasePath, Ty,
4135 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004136}
4137
Nate Begeman5ec4b312009-08-10 23:49:36 +00004138/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4139/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004140ExprResult
John McCallb268a282010-08-23 23:25:46 +00004141Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004142 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4143 if (!E)
4144 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004145
John McCalldadc5752010-08-24 06:29:42 +00004146 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004147
Nate Begeman5ec4b312009-08-10 23:49:36 +00004148 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004149 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4150 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004151
John McCallb268a282010-08-23 23:25:46 +00004152 if (Result.isInvalid()) return ExprError();
4153
4154 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004155}
4156
John McCalldadc5752010-08-24 06:29:42 +00004157ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00004158Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00004159 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00004160 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00004161 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00004162 QualType Ty = TInfo->getType();
John Thompson781ad172010-06-30 22:55:51 +00004163 bool isAltiVecLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00004164
John Thompson781ad172010-06-30 22:55:51 +00004165 // Check for an altivec literal,
4166 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004167 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4168 if (PE->getNumExprs() == 0) {
4169 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4170 return ExprError();
4171 }
John Thompson781ad172010-06-30 22:55:51 +00004172 if (PE->getNumExprs() == 1) {
4173 if (!PE->getExpr(0)->getType()->isVectorType())
4174 isAltiVecLiteral = true;
4175 }
4176 else
4177 isAltiVecLiteral = true;
4178 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004179
John Thompson781ad172010-06-30 22:55:51 +00004180 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
4181 // then handle it as such.
4182 if (isAltiVecLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004183 llvm::SmallVector<Expr *, 8> initExprs;
4184 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4185 initExprs.push_back(PE->getExpr(i));
4186
4187 // FIXME: This means that pretty-printing the final AST will produce curly
4188 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00004189 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4190 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00004191 initExprs.size(), RParenLoc);
4192 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00004193 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004194 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004195 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00004196 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00004197 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00004198 if (Result.isInvalid()) return ExprError();
4199 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004200 }
4201}
4202
John McCalldadc5752010-08-24 06:29:42 +00004203ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004204 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004205 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00004206 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004207 unsigned nexprs = Val.size();
4208 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004209 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4210 Expr *expr;
4211 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4212 expr = new (Context) ParenExpr(L, R, exprs[0]);
4213 else
4214 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004215 return Owned(expr);
4216}
4217
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004218/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4219/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004220/// C99 6.5.15
4221QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00004222 Expr *&SAVE,
Chris Lattner2c486602009-02-18 04:38:20 +00004223 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004224 // C++ is sufficiently different to merit its own checker.
4225 if (getLangOptions().CPlusPlus)
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00004226 return CXXCheckConditionalOperands(Cond, LHS, RHS, SAVE, QuestionLoc);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004227
Chris Lattner432cff52009-02-18 04:28:32 +00004228 UsualUnaryConversions(Cond);
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00004229 if (SAVE) {
4230 SAVE = LHS = Cond;
4231 }
4232 else
4233 UsualUnaryConversions(LHS);
Chris Lattner432cff52009-02-18 04:28:32 +00004234 UsualUnaryConversions(RHS);
4235 QualType CondTy = Cond->getType();
4236 QualType LHSTy = LHS->getType();
4237 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004238
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004239 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004240 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00004241 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4242 // Throw an error if its not either.
4243 if (getLangOptions().OpenCL) {
4244 if (!CondTy->isVectorType()) {
4245 Diag(Cond->getLocStart(),
4246 diag::err_typecheck_cond_expect_scalar_or_vector)
4247 << CondTy;
4248 return QualType();
4249 }
4250 }
4251 else {
4252 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4253 << CondTy;
4254 return QualType();
4255 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004256 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004257
Chris Lattnere2949f42008-01-06 22:42:25 +00004258 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004259 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4260 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00004261
Nate Begemanabb5a732010-09-20 22:41:17 +00004262 // OpenCL: If the condition is a vector, and both operands are scalar,
4263 // attempt to implicity convert them to the vector type to act like the
4264 // built in select.
4265 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4266 // Both operands should be of scalar type.
4267 if (!LHSTy->isScalarType()) {
4268 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4269 << CondTy;
4270 return QualType();
4271 }
4272 if (!RHSTy->isScalarType()) {
4273 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4274 << CondTy;
4275 return QualType();
4276 }
4277 // Implicity convert these scalars to the type of the condition.
4278 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
4279 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
4280 }
4281
Chris Lattnere2949f42008-01-06 22:42:25 +00004282 // If both operands have arithmetic type, do the usual arithmetic conversions
4283 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004284 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4285 UsualArithmeticConversions(LHS, RHS);
4286 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004287 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004288
Chris Lattnere2949f42008-01-06 22:42:25 +00004289 // If both operands are the same structure or union type, the result is that
4290 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004291 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4292 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004293 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004294 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004295 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004296 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004297 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004298 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004299
Chris Lattnere2949f42008-01-06 22:42:25 +00004300 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004301 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004302 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4303 if (!LHSTy->isVoidType())
4304 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4305 << RHS->getSourceRange();
4306 if (!RHSTy->isVoidType())
4307 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4308 << LHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004309 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
4310 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004311 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004312 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004313 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4314 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004315 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004316 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004317 // promote the null to a pointer.
John McCalle3027922010-08-25 11:45:40 +00004318 ImpCastExprToType(RHS, LHSTy, CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00004319 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004320 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004321 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004322 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCalle3027922010-08-25 11:45:40 +00004323 ImpCastExprToType(LHS, RHSTy, CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00004324 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004325 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004326
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004327 // All objective-c pointer type analysis is done here.
4328 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4329 QuestionLoc);
4330 if (!compositeType.isNull())
4331 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004332
4333
Steve Naroff05efa972009-07-01 14:36:47 +00004334 // Handle block pointer types.
4335 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4336 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4337 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4338 QualType destType = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00004339 ImpCastExprToType(LHS, destType, CK_BitCast);
4340 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004341 return destType;
4342 }
4343 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004344 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004345 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004346 }
Steve Naroff05efa972009-07-01 14:36:47 +00004347 // We have 2 block pointer types.
4348 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4349 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004350 return LHSTy;
4351 }
Steve Naroff05efa972009-07-01 14:36:47 +00004352 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004353 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4354 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004355
Steve Naroff05efa972009-07-01 14:36:47 +00004356 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4357 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004358 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004359 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004360 // In this situation, we assume void* type. No especially good
4361 // reason, but this is what gcc does, and we do have to pick
4362 // to get a consistent AST.
4363 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00004364 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
4365 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004366 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004367 }
Steve Naroff05efa972009-07-01 14:36:47 +00004368 // The block pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00004369 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
4370 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004371 return LHSTy;
4372 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004373
Steve Naroff05efa972009-07-01 14:36:47 +00004374 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4375 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4376 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004377 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4378 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004379
4380 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4381 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4382 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004383 QualType destPointee
4384 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004385 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004386 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00004387 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004388 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00004389 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004390 return destType;
4391 }
4392 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004393 QualType destPointee
4394 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004395 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004396 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00004397 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004398 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00004399 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004400 return destType;
4401 }
4402
4403 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4404 // Two identical pointer types are always compatible.
4405 return LHSTy;
4406 }
4407 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4408 rhptee.getUnqualifiedType())) {
4409 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4410 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4411 // In this situation, we assume void* type. No especially good
4412 // reason, but this is what gcc does, and we do have to pick
4413 // to get a consistent AST.
4414 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00004415 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
4416 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004417 return incompatTy;
4418 }
4419 // The pointer types are compatible.
4420 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4421 // differently qualified versions of compatible types, the result type is
4422 // a pointer to an appropriately qualified version of the *composite*
4423 // type.
4424 // FIXME: Need to calculate the composite type.
4425 // FIXME: Need to add qualifiers
John McCalle3027922010-08-25 11:45:40 +00004426 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
4427 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004428 return LHSTy;
4429 }
Mike Stump11289f42009-09-09 15:08:12 +00004430
Steve Naroff05efa972009-07-01 14:36:47 +00004431 // GCC compatibility: soften pointer/integer mismatch.
4432 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4433 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4434 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004435 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004436 return RHSTy;
4437 }
4438 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4439 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4440 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004441 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004442 return LHSTy;
4443 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004444
Chris Lattnere2949f42008-01-06 22:42:25 +00004445 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004446 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4447 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004448 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004449}
4450
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004451/// FindCompositeObjCPointerType - Helper method to find composite type of
4452/// two objective-c pointer types of the two input expressions.
4453QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4454 SourceLocation QuestionLoc) {
4455 QualType LHSTy = LHS->getType();
4456 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004457
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004458 // Handle things like Class and struct objc_class*. Here we case the result
4459 // to the pseudo-builtin, because that will be implicitly cast back to the
4460 // redefinition type if an attempt is made to access its fields.
4461 if (LHSTy->isObjCClassType() &&
4462 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
John McCalle3027922010-08-25 11:45:40 +00004463 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004464 return LHSTy;
4465 }
4466 if (RHSTy->isObjCClassType() &&
4467 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
John McCalle3027922010-08-25 11:45:40 +00004468 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004469 return RHSTy;
4470 }
4471 // And the same for struct objc_object* / id
4472 if (LHSTy->isObjCIdType() &&
4473 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
John McCalle3027922010-08-25 11:45:40 +00004474 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004475 return LHSTy;
4476 }
4477 if (RHSTy->isObjCIdType() &&
4478 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
John McCalle3027922010-08-25 11:45:40 +00004479 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004480 return RHSTy;
4481 }
4482 // And the same for struct objc_selector* / SEL
4483 if (Context.isObjCSelType(LHSTy) &&
4484 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
John McCalle3027922010-08-25 11:45:40 +00004485 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004486 return LHSTy;
4487 }
4488 if (Context.isObjCSelType(RHSTy) &&
4489 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
John McCalle3027922010-08-25 11:45:40 +00004490 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004491 return RHSTy;
4492 }
4493 // Check constraints for Objective-C object pointers types.
4494 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004495
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004496 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4497 // Two identical object pointer types are always compatible.
4498 return LHSTy;
4499 }
4500 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4501 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4502 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004503
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004504 // If both operands are interfaces and either operand can be
4505 // assigned to the other, use that type as the composite
4506 // type. This allows
4507 // xxx ? (A*) a : (B*) b
4508 // where B is a subclass of A.
4509 //
4510 // Additionally, as for assignment, if either type is 'id'
4511 // allow silent coercion. Finally, if the types are
4512 // incompatible then make sure to use 'id' as the composite
4513 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004514
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004515 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4516 // It could return the composite type.
4517 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4518 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4519 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4520 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4521 } else if ((LHSTy->isObjCQualifiedIdType() ||
4522 RHSTy->isObjCQualifiedIdType()) &&
4523 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4524 // Need to handle "id<xx>" explicitly.
4525 // GCC allows qualified id and any Objective-C type to devolve to
4526 // id. Currently localizing to here until clear this should be
4527 // part of ObjCQualifiedIdTypesAreCompatible.
4528 compositeType = Context.getObjCIdType();
4529 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4530 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004531 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004532 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4533 ;
4534 else {
4535 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4536 << LHSTy << RHSTy
4537 << LHS->getSourceRange() << RHS->getSourceRange();
4538 QualType incompatTy = Context.getObjCIdType();
John McCalle3027922010-08-25 11:45:40 +00004539 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
4540 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004541 return incompatTy;
4542 }
4543 // The object pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00004544 ImpCastExprToType(LHS, compositeType, CK_BitCast);
4545 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004546 return compositeType;
4547 }
4548 // Check Objective-C object pointer types and 'void *'
4549 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4550 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4551 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4552 QualType destPointee
4553 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4554 QualType destType = Context.getPointerType(destPointee);
4555 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00004556 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004557 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00004558 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004559 return destType;
4560 }
4561 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4562 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4563 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4564 QualType destPointee
4565 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4566 QualType destType = Context.getPointerType(destPointee);
4567 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00004568 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004569 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00004570 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004571 return destType;
4572 }
4573 return QualType();
4574}
4575
Steve Naroff83895f72007-09-16 03:34:24 +00004576/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004577/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00004578ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004579 SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +00004580 Expr *CondExpr, Expr *LHSExpr,
4581 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00004582 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4583 // was the condition.
4584 bool isLHSNull = LHSExpr == 0;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004585 Expr *SAVEExpr = 0;
4586 if (isLHSNull) {
4587 LHSExpr = SAVEExpr = CondExpr;
4588 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00004589
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00004590 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
4591 SAVEExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00004592 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004593 return ExprError();
4594
Douglas Gregor7e112b02009-08-26 14:37:04 +00004595 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004596 LHSExpr, ColonLoc,
4597 RHSExpr, SAVEExpr,
4598 result));
Chris Lattnere168f762006-11-10 05:29:30 +00004599}
4600
Steve Naroff3f597292007-05-11 22:18:03 +00004601// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004602// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004603// routine is it effectively iqnores the qualifiers on the top level pointee.
4604// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4605// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004606Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004607Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00004608 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004609
David Chisnall9f57c292009-08-17 16:35:33 +00004610 if ((lhsType->isObjCClassType() &&
4611 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4612 (rhsType->isObjCClassType() &&
4613 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4614 return Compatible;
4615 }
4616
Steve Naroff1f4d7272007-05-11 04:00:31 +00004617 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004618 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4619 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004620
Steve Naroff1f4d7272007-05-11 04:00:31 +00004621 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00004622 lhptee = Context.getCanonicalType(lhptee);
4623 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00004624
Chris Lattner9bad62c2008-01-04 18:04:52 +00004625 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004626
4627 // C99 6.5.16.1p1: This following citation is common to constraints
4628 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4629 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00004630 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00004631 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00004632 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00004633
Mike Stump4e1f26a2009-02-19 03:04:26 +00004634 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4635 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004636 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004637 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004638 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004639 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004640
Chris Lattner0a788432008-01-03 22:56:36 +00004641 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004642 assert(rhptee->isFunctionType());
4643 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004644 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004645
Chris Lattner0a788432008-01-03 22:56:36 +00004646 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004647 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004648 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004649
4650 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004651 assert(lhptee->isFunctionType());
4652 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004653 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004654 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00004655 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00004656 lhptee = lhptee.getUnqualifiedType();
4657 rhptee = rhptee.getUnqualifiedType();
4658 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4659 // Check if the pointee types are compatible ignoring the sign.
4660 // We explicitly check for char so that we catch "char" vs
4661 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00004662 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004663 lhptee = Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00004664 else if (lhptee->hasSignedIntegerRepresentation())
Eli Friedman80160bd2009-03-22 23:59:44 +00004665 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004666
Chris Lattnerec3a1562009-10-17 20:33:28 +00004667 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004668 rhptee = Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00004669 else if (rhptee->hasSignedIntegerRepresentation())
Eli Friedman80160bd2009-03-22 23:59:44 +00004670 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004671
Eli Friedman80160bd2009-03-22 23:59:44 +00004672 if (lhptee == rhptee) {
4673 // Types are compatible ignoring the sign. Qualifier incompatibility
4674 // takes priority over sign incompatibility because the sign
4675 // warning can be disabled.
4676 if (ConvTy != Compatible)
4677 return ConvTy;
4678 return IncompatiblePointerSign;
4679 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004680
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004681 // If we are a multi-level pointer, it's possible that our issue is simply
4682 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4683 // the eventual target type is the same and the pointers have the same
4684 // level of indirection, this must be the issue.
4685 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4686 do {
4687 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4688 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004689
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004690 lhptee = Context.getCanonicalType(lhptee);
4691 rhptee = Context.getCanonicalType(rhptee);
4692 } while (lhptee->isPointerType() && rhptee->isPointerType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004693
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004694 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00004695 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004696 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004697
Eli Friedman80160bd2009-03-22 23:59:44 +00004698 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00004699 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00004700 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004701 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00004702}
4703
Steve Naroff081c7422008-09-04 15:10:53 +00004704/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4705/// block pointer types are compatible or whether a block and normal pointer
4706/// are compatible. It is more restrict than comparing two function pointer
4707// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004708Sema::AssignConvertType
4709Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00004710 QualType rhsType) {
4711 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004712
Steve Naroff081c7422008-09-04 15:10:53 +00004713 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004714 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4715 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004716
Steve Naroff081c7422008-09-04 15:10:53 +00004717 // make sure we operate on the canonical type
4718 lhptee = Context.getCanonicalType(lhptee);
4719 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004720
Steve Naroff081c7422008-09-04 15:10:53 +00004721 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004722
Steve Naroff081c7422008-09-04 15:10:53 +00004723 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004724 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00004725 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004726
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004727 if (!getLangOptions().CPlusPlus) {
4728 if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
4729 return IncompatibleBlockPointer;
4730 }
4731 else if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004732 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00004733 return ConvTy;
4734}
4735
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004736/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4737/// for assignment compatibility.
4738Sema::AssignConvertType
4739Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00004740 if (lhsType->isObjCBuiltinType()) {
4741 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00004742 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
4743 !rhsType->isObjCQualifiedClassType())
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00004744 return IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004745 return Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00004746 }
4747 if (rhsType->isObjCBuiltinType()) {
4748 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00004749 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
4750 !lhsType->isObjCQualifiedClassType())
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00004751 return IncompatiblePointer;
4752 return Compatible;
4753 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004754 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004755 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004756 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004757 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4758 // make sure we operate on the canonical type
4759 lhptee = Context.getCanonicalType(lhptee);
4760 rhptee = Context.getCanonicalType(rhptee);
4761 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4762 return CompatiblePointerDiscardsQualifiers;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004763
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004764 if (Context.typesAreCompatible(lhsType, rhsType))
4765 return Compatible;
4766 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4767 return IncompatibleObjCQualifiedId;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004768 return IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004769}
4770
Mike Stump4e1f26a2009-02-19 03:04:26 +00004771/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4772/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00004773/// pointers. Here are some objectionable examples that GCC considers warnings:
4774///
4775/// int a, *pint;
4776/// short *pshort;
4777/// struct foo *pfoo;
4778///
4779/// pint = pshort; // warning: assignment from incompatible pointer type
4780/// a = pint; // warning: assignment makes integer from pointer without a cast
4781/// pint = a; // warning: assignment makes pointer from integer without a cast
4782/// pint = pfoo; // warning: assignment from incompatible pointer type
4783///
4784/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00004785/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00004786///
Chris Lattner9bad62c2008-01-04 18:04:52 +00004787Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004788Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00004789 // Get canonical types. We're not formatting these types, just comparing
4790 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00004791 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4792 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00004793
4794 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00004795 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00004796
David Chisnall9f57c292009-08-17 16:35:33 +00004797 if ((lhsType->isObjCClassType() &&
4798 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4799 (rhsType->isObjCClassType() &&
4800 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4801 return Compatible;
4802 }
4803
Douglas Gregor6b754842008-10-28 00:22:11 +00004804 // If the left-hand side is a reference type, then we are in a
4805 // (rare!) case where we've allowed the use of references in C,
4806 // e.g., as a parameter type in a built-in function. In this case,
4807 // just make sure that the type referenced is compatible with the
4808 // right-hand side type. The caller is responsible for adjusting
4809 // lhsType so that the resulting expression does not have reference
4810 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004811 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00004812 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00004813 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004814 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00004815 }
Nate Begemanbd956c42009-06-28 02:36:38 +00004816 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4817 // to the same ExtVector type.
4818 if (lhsType->isExtVectorType()) {
4819 if (rhsType->isExtVectorType())
4820 return lhsType == rhsType ? Compatible : Incompatible;
Douglas Gregora3208f92010-06-22 23:41:02 +00004821 if (rhsType->isArithmeticType())
Nate Begemanbd956c42009-06-28 02:36:38 +00004822 return Compatible;
4823 }
Mike Stump11289f42009-09-09 15:08:12 +00004824
Nate Begeman191a6b12008-07-14 18:02:46 +00004825 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004826 if (lhsType->isVectorType() && rhsType->isVectorType()) {
4827 // If we are allowing lax vector conversions, and LHS and RHS are both
4828 // vectors, the total size only needs to be the same. This is a bitcast;
4829 // no bits are changed but the result type is different.
4830 if (getLangOptions().LaxVectorConversions &&
4831 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004832 return IncompatibleVectors;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004833
4834 // Allow assignments of an AltiVec vector type to an equivalent GCC
4835 // vector type and vice versa
4836 if (Context.areCompatibleVectorTypes(lhsType, rhsType))
4837 return Compatible;
Chris Lattner881a2122008-01-04 23:32:24 +00004838 }
4839 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004840 }
Eli Friedman3360d892008-05-30 18:07:22 +00004841
Douglas Gregorbea453a2010-05-23 21:53:47 +00004842 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
4843 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType()))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004844 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00004845
Chris Lattnerec646832008-04-07 06:49:41 +00004846 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004847 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004848 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00004849
Chris Lattnerec646832008-04-07 06:49:41 +00004850 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004851 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004852
Steve Naroffaccc4882009-07-20 17:56:53 +00004853 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004854 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004855 if (lhsType->isVoidPointerType()) // an exception to the rule.
4856 return Compatible;
4857 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004858 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004859 if (rhsType->getAs<BlockPointerType>()) {
4860 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004861 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00004862
4863 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004864 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004865 return Compatible;
4866 }
Steve Naroff081c7422008-09-04 15:10:53 +00004867 return Incompatible;
4868 }
4869
4870 if (isa<BlockPointerType>(lhsType)) {
4871 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00004872 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004873
Steve Naroff32d072c2008-09-29 18:10:17 +00004874 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004875 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004876 return Compatible;
4877
Steve Naroff081c7422008-09-04 15:10:53 +00004878 if (rhsType->isBlockPointerType())
4879 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004880
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004881 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00004882 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004883 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00004884 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00004885 return Incompatible;
4886 }
4887
Steve Naroff7cae42b2009-07-10 23:34:53 +00004888 if (isa<ObjCObjectPointerType>(lhsType)) {
4889 if (rhsType->isIntegerType())
4890 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00004891
Steve Naroffaccc4882009-07-20 17:56:53 +00004892 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004893 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004894 if (rhsType->isVoidPointerType()) // an exception to the rule.
4895 return Compatible;
4896 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004897 }
4898 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004899 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004900 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004901 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004902 if (RHSPT->getPointeeType()->isVoidType())
4903 return Compatible;
4904 }
4905 // Treat block pointers as objects.
4906 if (rhsType->isBlockPointerType())
4907 return Compatible;
4908 return Incompatible;
4909 }
Chris Lattnerec646832008-04-07 06:49:41 +00004910 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004911 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00004912 if (lhsType == Context.BoolTy)
4913 return Compatible;
4914
4915 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004916 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00004917
Mike Stump4e1f26a2009-02-19 03:04:26 +00004918 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004919 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004920
4921 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004922 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004923 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004924 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004925 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004926 if (isa<ObjCObjectPointerType>(rhsType)) {
4927 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4928 if (lhsType == Context.BoolTy)
4929 return Compatible;
4930
4931 if (lhsType->isIntegerType())
4932 return PointerToInt;
4933
Steve Naroffaccc4882009-07-20 17:56:53 +00004934 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004935 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004936 if (lhsType->isVoidPointerType()) // an exception to the rule.
4937 return Compatible;
4938 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004939 }
4940 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004941 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004942 return Compatible;
4943 return Incompatible;
4944 }
Eli Friedman3360d892008-05-30 18:07:22 +00004945
Chris Lattnera52c2f22008-01-04 23:18:45 +00004946 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00004947 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004948 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00004949 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00004950 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00004951}
4952
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004953/// \brief Constructs a transparent union from an expression that is
4954/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00004955static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004956 QualType UnionType, FieldDecl *Field) {
4957 // Build an initializer list that designates the appropriate member
4958 // of the transparent union.
Ted Kremenekac034612010-04-13 23:39:13 +00004959 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00004960 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004961 SourceLocation());
4962 Initializer->setType(UnionType);
4963 Initializer->setInitializedFieldInUnion(Field);
4964
4965 // Build a compound literal constructing a value of the transparent
4966 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00004967 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00004968 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCalle15bbff2010-01-18 19:35:47 +00004969 Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004970}
4971
4972Sema::AssignConvertType
4973Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4974 QualType FromType = rExpr->getType();
4975
Mike Stump11289f42009-09-09 15:08:12 +00004976 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004977 // transparent_union GCC extension.
4978 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004979 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004980 return Incompatible;
4981
4982 // The field to initialize within the transparent union.
4983 RecordDecl *UD = UT->getDecl();
4984 FieldDecl *InitField = 0;
4985 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004986 for (RecordDecl::field_iterator it = UD->field_begin(),
4987 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004988 it != itend; ++it) {
4989 if (it->getType()->isPointerType()) {
4990 // If the transparent union contains a pointer type, we allow:
4991 // 1) void pointer
4992 // 2) null pointer constant
4993 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004994 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +00004995 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004996 InitField = *it;
4997 break;
4998 }
Mike Stump11289f42009-09-09 15:08:12 +00004999
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005000 if (rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005001 Expr::NPC_ValueDependentIsNull)) {
John McCalle3027922010-08-25 11:45:40 +00005002 ImpCastExprToType(rExpr, it->getType(), CK_IntegralToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005003 InitField = *it;
5004 break;
5005 }
5006 }
5007
5008 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
5009 == Compatible) {
Daniel Dunbar60785eb2010-09-17 23:21:43 +00005010 ImpCastExprToType(rExpr, it->getType(), CK_Unknown);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005011 InitField = *it;
5012 break;
5013 }
5014 }
5015
5016 if (!InitField)
5017 return Incompatible;
5018
5019 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
5020 return Compatible;
5021}
5022
Chris Lattner9bad62c2008-01-04 18:04:52 +00005023Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005024Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005025 if (getLangOptions().CPlusPlus) {
5026 if (!lhsType->isRecordType()) {
5027 // C++ 5.17p3: If the left operand is not of class type, the
5028 // expression is implicitly converted (C++ 4) to the
5029 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00005030 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005031 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00005032 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00005033 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00005034 }
5035
5036 // FIXME: Currently, we fall through and treat C++ classes like C
5037 // structures.
5038 }
5039
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005040 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5041 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00005042 if ((lhsType->isPointerType() ||
5043 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00005044 lhsType->isBlockPointerType())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005045 && rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005046 Expr::NPC_ValueDependentIsNull)) {
John McCalle3027922010-08-25 11:45:40 +00005047 ImpCastExprToType(rExpr, lhsType, CK_Unknown);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005048 return Compatible;
5049 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005050
Chris Lattnere6dcd502007-10-16 02:55:40 +00005051 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005052 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005053 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005054 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005055 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005056 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00005057 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00005058 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005059
Chris Lattner9bad62c2008-01-04 18:04:52 +00005060 Sema::AssignConvertType result =
5061 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005062
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005063 // C99 6.5.16.1p2: The value of the right operand is converted to the
5064 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005065 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5066 // so that we can use references in built-in functions even in C.
5067 // The getNonReferenceType() call makes sure that the resulting expression
5068 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005069 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregora8a089b2010-07-13 18:40:04 +00005070 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context),
John McCalle3027922010-08-25 11:45:40 +00005071 CK_Unknown);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005072 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005073}
5074
Chris Lattner326f7572008-11-18 01:30:42 +00005075QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005076 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005077 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00005078 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005079 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005080}
5081
Chris Lattnerfaa54172010-01-12 21:23:57 +00005082QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005083 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005084 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00005085 QualType lhsType =
5086 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
5087 QualType rhsType =
5088 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005089
Nate Begeman191a6b12008-07-14 18:02:46 +00005090 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005091 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00005092 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005093
Nate Begeman191a6b12008-07-14 18:02:46 +00005094 // Handle the case of a vector & extvector type of the same size and element
5095 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005096 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00005097 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00005098 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00005099 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005100 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005101 if (lhsType->isExtVectorType()) {
John McCalle3027922010-08-25 11:45:40 +00005102 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005103 return lhsType;
5104 }
5105
John McCalle3027922010-08-25 11:45:40 +00005106 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005107 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00005108 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
5109 // If we are allowing lax vector conversions, and LHS and RHS are both
5110 // vectors, the total size only needs to be the same. This is a
5111 // bitcast; no bits are changed but the result type is different.
5112 ImpCastExprToType(rex, lhsType, CK_BitCast);
5113 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005114 }
Eric Christophera613f562010-08-26 00:42:16 +00005115 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00005116 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005117 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005118
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005119 // Handle the case of equivalent AltiVec and GCC vector types
5120 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5121 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCalle3027922010-08-25 11:45:40 +00005122 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005123 return rhsType;
5124 }
5125
Nate Begemanbd956c42009-06-28 02:36:38 +00005126 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5127 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5128 bool swapped = false;
5129 if (rhsType->isExtVectorType()) {
5130 swapped = true;
5131 std::swap(rex, lex);
5132 std::swap(rhsType, lhsType);
5133 }
Mike Stump11289f42009-09-09 15:08:12 +00005134
Nate Begeman886448d2009-06-28 19:12:57 +00005135 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005136 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005137 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005138 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005139 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
John McCalle3027922010-08-25 11:45:40 +00005140 ImpCastExprToType(rex, lhsType, CK_IntegralCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00005141 if (swapped) std::swap(rex, lex);
5142 return lhsType;
5143 }
5144 }
5145 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5146 rhsType->isRealFloatingType()) {
5147 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
John McCalle3027922010-08-25 11:45:40 +00005148 ImpCastExprToType(rex, lhsType, CK_FloatingCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00005149 if (swapped) std::swap(rex, lex);
5150 return lhsType;
5151 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005152 }
5153 }
Mike Stump11289f42009-09-09 15:08:12 +00005154
Nate Begeman886448d2009-06-28 19:12:57 +00005155 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00005156 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005157 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00005158 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005159 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005160}
5161
Chris Lattnerfaa54172010-01-12 21:23:57 +00005162QualType Sema::CheckMultiplyDivideOperands(
5163 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00005164 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005165 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005166
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005167 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005168
Chris Lattnerfaa54172010-01-12 21:23:57 +00005169 if (!lex->getType()->isArithmeticType() ||
5170 !rex->getType()->isArithmeticType())
5171 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005172
Chris Lattnerfaa54172010-01-12 21:23:57 +00005173 // Check for division by zero.
5174 if (isDiv &&
5175 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005176 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattner70117952010-01-12 21:30:55 +00005177 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005178
Chris Lattnerfaa54172010-01-12 21:23:57 +00005179 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005180}
5181
Chris Lattnerfaa54172010-01-12 21:23:57 +00005182QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005183 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005184 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005185 if (lex->getType()->hasIntegerRepresentation() &&
5186 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005187 return CheckVectorOperands(Loc, lex, rex);
5188 return InvalidOperands(Loc, lex, rex);
5189 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005190
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005191 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005192
Chris Lattnerfaa54172010-01-12 21:23:57 +00005193 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
5194 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005195
Chris Lattnerfaa54172010-01-12 21:23:57 +00005196 // Check for remainder by zero.
5197 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00005198 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
5199 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005200
Chris Lattnerfaa54172010-01-12 21:23:57 +00005201 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005202}
5203
Chris Lattnerfaa54172010-01-12 21:23:57 +00005204QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00005205 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005206 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5207 QualType compType = CheckVectorOperands(Loc, lex, rex);
5208 if (CompLHSTy) *CompLHSTy = compType;
5209 return compType;
5210 }
Steve Naroff7a5af782007-07-13 16:58:59 +00005211
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005212 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00005213
Steve Naroffe4718892007-04-27 18:30:00 +00005214 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005215 if (lex->getType()->isArithmeticType() &&
5216 rex->getType()->isArithmeticType()) {
5217 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005218 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005219 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00005220
Eli Friedman8e122982008-05-18 18:08:51 +00005221 // Put any potential pointer into PExp
5222 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00005223 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00005224 std::swap(PExp, IExp);
5225
Steve Naroff6b712a72009-07-14 18:25:06 +00005226 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005227
Eli Friedman8e122982008-05-18 18:08:51 +00005228 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005229 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005230
Chris Lattner12bdebb2009-04-24 23:50:08 +00005231 // Check for arithmetic on pointers to incomplete types.
5232 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00005233 if (getLangOptions().CPlusPlus) {
5234 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00005235 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00005236 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005237 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005238
5239 // GNU extension: arithmetic on pointer to void
5240 Diag(Loc, diag::ext_gnu_void_ptr)
5241 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00005242 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00005243 if (getLangOptions().CPlusPlus) {
5244 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5245 << lex->getType() << lex->getSourceRange();
5246 return QualType();
5247 }
5248
5249 // GNU extension: arithmetic on pointer to function
5250 Diag(Loc, diag::ext_gnu_ptr_func_arith)
5251 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00005252 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005253 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00005254 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00005255 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005256 PExp->getType()->isObjCObjectPointerType()) &&
5257 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00005258 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5259 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005260 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005261 return QualType();
5262 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00005263 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005264 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005265 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5266 << PointeeTy << PExp->getSourceRange();
5267 return QualType();
5268 }
Mike Stump11289f42009-09-09 15:08:12 +00005269
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005270 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00005271 QualType LHSTy = Context.isPromotableBitField(lex);
5272 if (LHSTy.isNull()) {
5273 LHSTy = lex->getType();
5274 if (LHSTy->isPromotableIntegerType())
5275 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005276 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005277 *CompLHSTy = LHSTy;
5278 }
Eli Friedman8e122982008-05-18 18:08:51 +00005279 return PExp->getType();
5280 }
5281 }
5282
Chris Lattner326f7572008-11-18 01:30:42 +00005283 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005284}
5285
Chris Lattner2a3569b2008-04-07 05:30:13 +00005286// C99 6.5.6
5287QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005288 SourceLocation Loc, QualType* CompLHSTy) {
5289 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5290 QualType compType = CheckVectorOperands(Loc, lex, rex);
5291 if (CompLHSTy) *CompLHSTy = compType;
5292 return compType;
5293 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005294
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005295 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005296
Chris Lattner4d62f422007-12-09 21:53:25 +00005297 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005298
Chris Lattner4d62f422007-12-09 21:53:25 +00005299 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00005300 if (lex->getType()->isArithmeticType()
5301 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005302 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005303 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005304 }
Mike Stump11289f42009-09-09 15:08:12 +00005305
Chris Lattner4d62f422007-12-09 21:53:25 +00005306 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00005307 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00005308 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005309
Douglas Gregorac1fb652009-03-24 19:52:54 +00005310 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005311
Douglas Gregorac1fb652009-03-24 19:52:54 +00005312 bool ComplainAboutVoid = false;
5313 Expr *ComplainAboutFunc = 0;
5314 if (lpointee->isVoidType()) {
5315 if (getLangOptions().CPlusPlus) {
5316 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5317 << lex->getSourceRange() << rex->getSourceRange();
5318 return QualType();
5319 }
5320
5321 // GNU C extension: arithmetic on pointer to void
5322 ComplainAboutVoid = true;
5323 } else if (lpointee->isFunctionType()) {
5324 if (getLangOptions().CPlusPlus) {
5325 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005326 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005327 return QualType();
5328 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005329
5330 // GNU C extension: arithmetic on pointer to function
5331 ComplainAboutFunc = lex;
5332 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00005333 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005334 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00005335 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005336 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005337 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005338
Chris Lattner12bdebb2009-04-24 23:50:08 +00005339 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005340 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005341 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5342 << lpointee << lex->getSourceRange();
5343 return QualType();
5344 }
Mike Stump11289f42009-09-09 15:08:12 +00005345
Chris Lattner4d62f422007-12-09 21:53:25 +00005346 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00005347 if (rex->getType()->isIntegerType()) {
5348 if (ComplainAboutVoid)
5349 Diag(Loc, diag::ext_gnu_void_ptr)
5350 << lex->getSourceRange() << rex->getSourceRange();
5351 if (ComplainAboutFunc)
5352 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005353 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005354 << ComplainAboutFunc->getSourceRange();
5355
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005356 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005357 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005358 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005359
Chris Lattner4d62f422007-12-09 21:53:25 +00005360 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005361 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00005362 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005363
Douglas Gregorac1fb652009-03-24 19:52:54 +00005364 // RHS must be a completely-type object type.
5365 // Handle the GNU void* extension.
5366 if (rpointee->isVoidType()) {
5367 if (getLangOptions().CPlusPlus) {
5368 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5369 << lex->getSourceRange() << rex->getSourceRange();
5370 return QualType();
5371 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005372
Douglas Gregorac1fb652009-03-24 19:52:54 +00005373 ComplainAboutVoid = true;
5374 } else if (rpointee->isFunctionType()) {
5375 if (getLangOptions().CPlusPlus) {
5376 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005377 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005378 return QualType();
5379 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005380
5381 // GNU extension: arithmetic on pointer to function
5382 if (!ComplainAboutFunc)
5383 ComplainAboutFunc = rex;
5384 } else if (!rpointee->isDependentType() &&
5385 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005386 PDiag(diag::err_typecheck_sub_ptr_object)
5387 << rex->getSourceRange()
5388 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005389 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005390
Eli Friedman168fe152009-05-16 13:54:38 +00005391 if (getLangOptions().CPlusPlus) {
5392 // Pointee types must be the same: C++ [expr.add]
5393 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5394 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5395 << lex->getType() << rex->getType()
5396 << lex->getSourceRange() << rex->getSourceRange();
5397 return QualType();
5398 }
5399 } else {
5400 // Pointee types must be compatible C99 6.5.6p3
5401 if (!Context.typesAreCompatible(
5402 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5403 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5404 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5405 << lex->getType() << rex->getType()
5406 << lex->getSourceRange() << rex->getSourceRange();
5407 return QualType();
5408 }
Chris Lattner4d62f422007-12-09 21:53:25 +00005409 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005410
Douglas Gregorac1fb652009-03-24 19:52:54 +00005411 if (ComplainAboutVoid)
5412 Diag(Loc, diag::ext_gnu_void_ptr)
5413 << lex->getSourceRange() << rex->getSourceRange();
5414 if (ComplainAboutFunc)
5415 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005416 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005417 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005418
5419 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005420 return Context.getPointerDiffType();
5421 }
5422 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005423
Chris Lattner326f7572008-11-18 01:30:42 +00005424 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005425}
5426
Douglas Gregor0bf31402010-10-08 23:50:27 +00005427static bool isScopedEnumerationType(QualType T) {
5428 if (const EnumType *ET = dyn_cast<EnumType>(T))
5429 return ET->getDecl()->isScoped();
5430 return false;
5431}
5432
Chris Lattner2a3569b2008-04-07 05:30:13 +00005433// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00005434QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00005435 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00005436 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005437 if (!lex->getType()->hasIntegerRepresentation() ||
5438 !rex->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00005439 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005440
Douglas Gregor0bf31402010-10-08 23:50:27 +00005441 // C++0x: Don't allow scoped enums. FIXME: Use something better than
5442 // hasIntegerRepresentation() above instead of this.
5443 if (isScopedEnumerationType(lex->getType()) ||
5444 isScopedEnumerationType(rex->getType())) {
5445 return InvalidOperands(Loc, lex, rex);
5446 }
5447
Nate Begemane46ee9a2009-10-25 02:26:48 +00005448 // Vector shifts promote their scalar inputs to vector type.
5449 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5450 return CheckVectorOperands(Loc, lex, rex);
5451
Chris Lattner5c11c412007-12-12 05:47:28 +00005452 // Shifts don't perform usual arithmetic conversions, they just do integer
5453 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00005454 QualType LHSTy = Context.isPromotableBitField(lex);
5455 if (LHSTy.isNull()) {
5456 LHSTy = lex->getType();
5457 if (LHSTy->isPromotableIntegerType())
5458 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005459 }
Chris Lattner3c133402007-12-13 07:28:16 +00005460 if (!isCompAssign)
John McCalle3027922010-08-25 11:45:40 +00005461 ImpCastExprToType(lex, LHSTy, CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005462
Chris Lattner5c11c412007-12-12 05:47:28 +00005463 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005464
Ryan Flynnf53fab82009-08-07 16:20:20 +00005465 // Sanity-check shift operands
5466 llvm::APSInt Right;
5467 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00005468 if (!rex->isValueDependent() &&
5469 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00005470 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00005471 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5472 else {
5473 llvm::APInt LeftBits(Right.getBitWidth(),
5474 Context.getTypeSize(lex->getType()));
5475 if (Right.uge(LeftBits))
5476 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5477 }
5478 }
5479
Chris Lattner5c11c412007-12-12 05:47:28 +00005480 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005481 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005482}
5483
Chandler Carruth17773fc2010-07-10 12:30:03 +00005484static bool IsWithinTemplateSpecialization(Decl *D) {
5485 if (DeclContext *DC = D->getDeclContext()) {
5486 if (isa<ClassTemplateSpecializationDecl>(DC))
5487 return true;
5488 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
5489 return FD->isFunctionTemplateSpecialization();
5490 }
5491 return false;
5492}
5493
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005494// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00005495QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005496 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00005497 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005498
Chris Lattner9a152e22009-12-05 05:40:13 +00005499 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00005500 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005501 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005502
Steve Naroff31090012007-07-16 21:54:35 +00005503 QualType lType = lex->getType();
5504 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005505
Douglas Gregor4ffbad12010-06-22 22:12:46 +00005506 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00005507 !(lType->isBlockPointerType() && isRelational) &&
5508 !lex->getLocStart().isMacroID() &&
5509 !rex->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00005510 // For non-floating point types, check for self-comparisons of the form
5511 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5512 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00005513 //
5514 // NOTE: Don't warn about comparison expressions resulting from macro
5515 // expansion. Also don't warn about comparisons which are only self
5516 // comparisons within a template specialization. The warnings should catch
5517 // obvious cases in the definition of the template anyways. The idea is to
5518 // warn when the typed comparison operator will always evaluate to the same
5519 // result.
Chris Lattner222b8bd2009-03-08 19:39:53 +00005520 Expr *LHSStripped = lex->IgnoreParens();
5521 Expr *RHSStripped = rex->IgnoreParens();
Chandler Carruth17773fc2010-07-10 12:30:03 +00005522 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00005523 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00005524 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00005525 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregorec170db2010-06-08 19:50:34 +00005526 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
5527 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00005528 << (Opc == BO_EQ
5529 || Opc == BO_LE
5530 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00005531 } else if (lType->isArrayType() && rType->isArrayType() &&
5532 !DRL->getDecl()->getType()->isReferenceType() &&
5533 !DRR->getDecl()->getType()->isReferenceType()) {
5534 // what is it always going to eval to?
5535 char always_evals_to;
5536 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00005537 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00005538 always_evals_to = 0; // false
5539 break;
John McCalle3027922010-08-25 11:45:40 +00005540 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00005541 always_evals_to = 1; // true
5542 break;
5543 default:
5544 // best we can say is 'a constant'
5545 always_evals_to = 2; // e.g. array1 <= array2
5546 break;
5547 }
5548 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
5549 << 1 // array
5550 << always_evals_to);
5551 }
5552 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00005553 }
Mike Stump11289f42009-09-09 15:08:12 +00005554
Chris Lattner222b8bd2009-03-08 19:39:53 +00005555 if (isa<CastExpr>(LHSStripped))
5556 LHSStripped = LHSStripped->IgnoreParenCasts();
5557 if (isa<CastExpr>(RHSStripped))
5558 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005559
Chris Lattner222b8bd2009-03-08 19:39:53 +00005560 // Warn about comparisons against a string constant (unless the other
5561 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005562 Expr *literalString = 0;
5563 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00005564 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005565 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005566 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005567 literalString = lex;
5568 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00005569 } else if ((isa<StringLiteral>(RHSStripped) ||
5570 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005571 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005572 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005573 literalString = rex;
5574 literalStringStripped = RHSStripped;
5575 }
5576
5577 if (literalString) {
5578 std::string resultComparison;
5579 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00005580 case BO_LT: resultComparison = ") < 0"; break;
5581 case BO_GT: resultComparison = ") > 0"; break;
5582 case BO_LE: resultComparison = ") <= 0"; break;
5583 case BO_GE: resultComparison = ") >= 0"; break;
5584 case BO_EQ: resultComparison = ") == 0"; break;
5585 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005586 default: assert(false && "Invalid comparison operator");
5587 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005588
Douglas Gregor49862b82010-01-12 23:18:54 +00005589 DiagRuntimeBehavior(Loc,
5590 PDiag(diag::warn_stringcompare)
5591 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00005592 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005593 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00005594 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005595
Douglas Gregorec170db2010-06-08 19:50:34 +00005596 // C99 6.5.8p3 / C99 6.5.9p4
5597 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5598 UsualArithmeticConversions(lex, rex);
5599 else {
5600 UsualUnaryConversions(lex);
5601 UsualUnaryConversions(rex);
5602 }
5603
5604 lType = lex->getType();
5605 rType = rex->getType();
5606
Douglas Gregorca63811b2008-11-19 03:25:36 +00005607 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00005608 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00005609
Chris Lattnerb620c342007-08-26 01:18:55 +00005610 if (isRelational) {
5611 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005612 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005613 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00005614 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00005615 if (lType->hasFloatingRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00005616 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005617
Chris Lattnerb620c342007-08-26 01:18:55 +00005618 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005619 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005620 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005621
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005622 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005623 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005624 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005625 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005626
Douglas Gregorf267edd2010-06-15 21:38:40 +00005627 // All of the following pointer-related warnings are GCC extensions, except
5628 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00005629 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00005630 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005631 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00005632 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005633 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005634
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005635 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00005636 if (LCanPointeeTy == RCanPointeeTy)
5637 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005638 if (!isRelational &&
5639 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5640 // Valid unless comparison between non-null pointer and function pointer
5641 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00005642 // In a SFINAE context, we treat this as a hard error to maintain
5643 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005644 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5645 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00005646 Diag(Loc,
5647 isSFINAEContext()?
5648 diag::err_typecheck_comparison_of_fptr_to_void
5649 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005650 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00005651
5652 if (isSFINAEContext())
5653 return QualType();
5654
John McCalle3027922010-08-25 11:45:40 +00005655 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005656 return ResultTy;
5657 }
5658 }
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005659 // C++ [expr.rel]p2:
5660 // [...] Pointer conversions (4.10) and qualification
5661 // conversions (4.4) are performed on pointer operands (or on
5662 // a pointer operand and a null pointer constant) to bring
5663 // them to their composite pointer type. [...]
5664 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005665 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005666 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005667 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005668 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005669 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005670 if (T.isNull()) {
5671 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5672 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5673 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005674 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005675 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005676 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005677 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005678 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005679 }
5680
John McCalle3027922010-08-25 11:45:40 +00005681 ImpCastExprToType(lex, T, CK_BitCast);
5682 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005683 return ResultTy;
5684 }
Eli Friedman16c209612009-08-23 00:27:47 +00005685 // C99 6.5.9p2 and C99 6.5.8p2
5686 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5687 RCanPointeeTy.getUnqualifiedType())) {
5688 // Valid unless a relational comparison of function pointers
5689 if (isRelational && LCanPointeeTy->isFunctionType()) {
5690 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5691 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5692 }
5693 } else if (!isRelational &&
5694 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5695 // Valid unless comparison between non-null pointer and function pointer
5696 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5697 && !LHSIsNull && !RHSIsNull) {
5698 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5699 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5700 }
5701 } else {
5702 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00005703 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005704 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00005705 }
Eli Friedman16c209612009-08-23 00:27:47 +00005706 if (LCanPointeeTy != RCanPointeeTy)
John McCalle3027922010-08-25 11:45:40 +00005707 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005708 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005709 }
Mike Stump11289f42009-09-09 15:08:12 +00005710
Sebastian Redl576fd422009-05-10 18:38:11 +00005711 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00005712 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005713 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00005714 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005715 (lType->isPointerType() ||
5716 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00005717 ImpCastExprToType(rex, lType,
5718 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00005719 ? CK_NullToMemberPointer
5720 : CK_IntegralToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005721 return ResultTy;
5722 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005723 if (LHSIsNull &&
5724 (rType->isPointerType() ||
5725 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00005726 ImpCastExprToType(lex, rType,
5727 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00005728 ? CK_NullToMemberPointer
5729 : CK_IntegralToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005730 return ResultTy;
5731 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005732
5733 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00005734 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005735 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5736 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005737 // In addition, pointers to members can be compared, or a pointer to
5738 // member and a null pointer constant. Pointer to member conversions
5739 // (4.11) and qualification conversions (4.4) are performed to bring
5740 // them to a common type. If one operand is a null pointer constant,
5741 // the common type is the type of the other operand. Otherwise, the
5742 // common type is a pointer to member type similar (4.4) to the type
5743 // of one of the operands, with a cv-qualification signature (4.4)
5744 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005745 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005746 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005747 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005748 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005749 if (T.isNull()) {
5750 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005751 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005752 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005753 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005754 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005755 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005756 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005757 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005758 }
Mike Stump11289f42009-09-09 15:08:12 +00005759
John McCalle3027922010-08-25 11:45:40 +00005760 ImpCastExprToType(lex, T, CK_BitCast);
5761 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005762 return ResultTy;
5763 }
Mike Stump11289f42009-09-09 15:08:12 +00005764
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005765 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00005766 if (lType->isNullPtrType() && rType->isNullPtrType())
5767 return ResultTy;
5768 }
Mike Stump11289f42009-09-09 15:08:12 +00005769
Steve Naroff081c7422008-09-04 15:10:53 +00005770 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00005771 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005772 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5773 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005774
Steve Naroff081c7422008-09-04 15:10:53 +00005775 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00005776 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005777 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005778 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00005779 }
John McCalle3027922010-08-25 11:45:40 +00005780 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005781 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00005782 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00005783 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00005784 if (!isRelational
5785 && ((lType->isBlockPointerType() && rType->isPointerType())
5786 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00005787 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005788 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005789 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005790 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005791 ->getPointeeType()->isVoidType())))
5792 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5793 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00005794 }
John McCalle3027922010-08-25 11:45:40 +00005795 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005796 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00005797 }
Steve Naroff081c7422008-09-04 15:10:53 +00005798
Steve Naroff7cae42b2009-07-10 23:34:53 +00005799 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005800 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005801 const PointerType *LPT = lType->getAs<PointerType>();
5802 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005803 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005804 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005805 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005806 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005807
Steve Naroff753567f2008-11-17 19:49:16 +00005808 if (!LPtrToVoid && !RPtrToVoid &&
5809 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005810 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005811 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005812 }
John McCalle3027922010-08-25 11:45:40 +00005813 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005814 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00005815 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005816 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005817 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005818 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5819 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005820 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005821 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00005822 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00005823 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00005824 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
5825 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005826 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00005827 bool isError = false;
5828 if ((LHSIsNull && lType->isIntegerType()) ||
5829 (RHSIsNull && rType->isIntegerType())) {
5830 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00005831 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00005832 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00005833 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00005834 else if (getLangOptions().CPlusPlus) {
5835 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
5836 isError = true;
5837 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00005838 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005839
Chris Lattnerd99bd522009-08-23 00:03:44 +00005840 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005841 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005842 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00005843 if (isError)
5844 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005845 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00005846
5847 if (lType->isIntegerType())
John McCalle3027922010-08-25 11:45:40 +00005848 ImpCastExprToType(lex, rType, CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00005849 else
John McCalle3027922010-08-25 11:45:40 +00005850 ImpCastExprToType(rex, lType, CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005851 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00005852 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00005853
Steve Naroff4b191572008-09-04 16:56:14 +00005854 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00005855 if (!isRelational && RHSIsNull
5856 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCalle3027922010-08-25 11:45:40 +00005857 ImpCastExprToType(rex, lType, CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005858 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005859 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00005860 if (!isRelational && LHSIsNull
5861 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00005862 ImpCastExprToType(lex, rType, CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005863 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005864 }
Chris Lattner326f7572008-11-18 01:30:42 +00005865 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005866}
5867
Nate Begeman191a6b12008-07-14 18:02:46 +00005868/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00005869/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00005870/// like a scalar comparison, a vector comparison produces a vector of integer
5871/// types.
5872QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00005873 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00005874 bool isRelational) {
5875 // Check to make sure we're operating on vectors of the same type and width,
5876 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00005877 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005878 if (vType.isNull())
5879 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005880
Nate Begeman191a6b12008-07-14 18:02:46 +00005881 QualType lType = lex->getType();
5882 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005883
Nate Begeman191a6b12008-07-14 18:02:46 +00005884 // For non-floating point types, check for self-comparisons of the form
5885 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5886 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00005887 if (!lType->hasFloatingRepresentation()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00005888 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5889 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5890 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregorec170db2010-06-08 19:50:34 +00005891 DiagRuntimeBehavior(Loc,
5892 PDiag(diag::warn_comparison_always)
5893 << 0 // self-
5894 << 2 // "a constant"
5895 );
Nate Begeman191a6b12008-07-14 18:02:46 +00005896 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005897
Nate Begeman191a6b12008-07-14 18:02:46 +00005898 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00005899 if (!isRelational && lType->hasFloatingRepresentation()) {
5900 assert (rType->hasFloatingRepresentation());
Chris Lattner326f7572008-11-18 01:30:42 +00005901 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005902 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005903
Nate Begeman191a6b12008-07-14 18:02:46 +00005904 // Return the type for the comparison, which is the same as vector type for
5905 // integer vectors, or an integer type of identical size and number of
5906 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005907 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00005908 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005909
John McCall9dd450b2009-09-21 23:43:11 +00005910 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00005911 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005912 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00005913 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00005914 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005915 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5916
Mike Stump4e1f26a2009-02-19 03:04:26 +00005917 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005918 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00005919 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5920}
5921
Steve Naroff218bc2b2007-05-04 21:54:46 +00005922inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005923 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005924 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5925 if (lex->getType()->hasIntegerRepresentation() &&
5926 rex->getType()->hasIntegerRepresentation())
5927 return CheckVectorOperands(Loc, lex, rex);
5928
5929 return InvalidOperands(Loc, lex, rex);
5930 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005931
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005932 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005933
Douglas Gregor0bf31402010-10-08 23:50:27 +00005934 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
5935 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005936 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00005937 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005938}
5939
Steve Naroff218bc2b2007-05-04 21:54:46 +00005940inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner8406c512010-07-13 19:41:32 +00005941 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
5942
5943 // Diagnose cases where the user write a logical and/or but probably meant a
5944 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
5945 // is a constant.
5946 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman6b197e02010-07-27 19:14:53 +00005947 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00005948 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00005949 !Loc.isMacroID()) {
5950 // If the RHS can be constant folded, and if it constant folds to something
5951 // that isn't 0 or 1 (which indicate a potential logical operation that
5952 // happened to fold to true/false) then warn.
5953 Expr::EvalResult Result;
5954 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
5955 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
5956 Diag(Loc, diag::warn_logical_instead_of_bitwise)
5957 << rex->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00005958 << (Opc == BO_LAnd ? "&&" : "||")
5959 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00005960 }
5961 }
Chris Lattner8406c512010-07-13 19:41:32 +00005962
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005963 if (!Context.getLangOptions().CPlusPlus) {
5964 UsualUnaryConversions(lex);
5965 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005966
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005967 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5968 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005969
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005970 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00005971 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005972
John McCall4a2429a2010-06-04 00:29:51 +00005973 // The following is safe because we only use this method for
5974 // non-overloadable operands.
5975
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005976 // C++ [expr.log.and]p1
5977 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00005978 // The operands are both contextually converted to type bool.
5979 if (PerformContextuallyConvertToBool(lex) ||
5980 PerformContextuallyConvertToBool(rex))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005981 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005982
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005983 // C++ [expr.log.and]p2
5984 // C++ [expr.log.or]p2
5985 // The result is a bool.
5986 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00005987}
5988
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005989/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5990/// is a read-only property; return true if so. A readonly property expression
5991/// depends on various declarations and thus must be treated specially.
5992///
Mike Stump11289f42009-09-09 15:08:12 +00005993static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005994 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5995 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5996 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5997 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005998 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00005999 BaseType->getAsObjCInterfacePointerType())
6000 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6001 if (S.isPropertyReadonly(PDecl, IFace))
6002 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006003 }
6004 }
6005 return false;
6006}
6007
Chris Lattner30bd3272008-11-18 01:22:49 +00006008/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6009/// emit an error and return true. If so, return false.
6010static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006011 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006012 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006013 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006014 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6015 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00006016 if (IsLV == Expr::MLV_Valid)
6017 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006018
Chris Lattner30bd3272008-11-18 01:22:49 +00006019 unsigned Diag = 0;
6020 bool NeedType = false;
6021 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00006022 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006023 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006024 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6025 NeedType = true;
6026 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006027 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006028 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6029 NeedType = true;
6030 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006031 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006032 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6033 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006034 case Expr::MLV_Valid:
6035 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006036 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006037 case Expr::MLV_MemberFunction:
6038 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006039 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6040 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006041 case Expr::MLV_IncompleteType:
6042 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006043 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006044 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006045 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006046 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006047 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6048 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006049 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006050 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6051 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006052 case Expr::MLV_ReadonlyProperty:
6053 Diag = diag::error_readonly_property_assignment;
6054 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006055 case Expr::MLV_NoSetterProperty:
6056 Diag = diag::error_nosetter_property_assignment;
6057 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006058 case Expr::MLV_SubObjCPropertySetting:
6059 Diag = diag::error_no_subobject_property_setting;
6060 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006061 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006062
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006063 SourceRange Assign;
6064 if (Loc != OrigLoc)
6065 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006066 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006067 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006068 else
Mike Stump11289f42009-09-09 15:08:12 +00006069 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006070 return true;
6071}
6072
6073
6074
6075// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00006076QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
6077 SourceLocation Loc,
6078 QualType CompoundType) {
6079 // Verify that LHS is a modifiable lvalue, and emit error if not.
6080 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00006081 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00006082
6083 QualType LHSType = LHS->getType();
6084 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006085 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00006086 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006087 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006088 // Simple assignment "x = y".
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00006089 ConvertPropertyAssignment(LHS, RHS, LHSTy);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006090 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006091 // Special case of NSObject attributes on c-style pointer types.
6092 if (ConvTy == IncompatiblePointer &&
6093 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006094 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006095 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006096 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006097 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006098
Chris Lattnerea714382008-08-21 18:04:13 +00006099 // If the RHS is a unary plus or minus, check to see if they = and + are
6100 // right next to each other. If so, the user may have typo'd "x =+ 4"
6101 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00006102 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00006103 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6104 RHSCheck = ICE->getSubExpr();
6105 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00006106 if ((UO->getOpcode() == UO_Plus ||
6107 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00006108 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00006109 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00006110 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6111 // And there is a space or other character before the subexpr of the
6112 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00006113 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6114 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006115 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00006116 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00006117 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00006118 }
Chris Lattnerea714382008-08-21 18:04:13 +00006119 }
6120 } else {
6121 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00006122 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006123 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006124
Chris Lattner326f7572008-11-18 01:30:42 +00006125 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006126 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00006127 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006128
Chris Lattner39561062010-07-07 06:14:23 +00006129
6130 // Check to see if the destination operand is a dereferenced null pointer. If
6131 // so, and if not volatile-qualified, this is undefined behavior that the
6132 // optimizer will delete, so warn about it. People sometimes try to use this
6133 // to get a deterministic trap and are surprised by clang's behavior. This
6134 // only handles the pattern "*null = whatever", which is a very syntactic
6135 // check.
6136 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCalle3027922010-08-25 11:45:40 +00006137 if (UO->getOpcode() == UO_Deref &&
Chris Lattner39561062010-07-07 06:14:23 +00006138 UO->getSubExpr()->IgnoreParenCasts()->
6139 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
6140 !UO->getType().isVolatileQualified()) {
6141 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
6142 << UO->getSubExpr()->getSourceRange();
6143 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
6144 }
6145
Steve Naroff98cf3e92007-06-06 18:38:38 +00006146 // C99 6.5.16p3: The type of an assignment expression is the type of the
6147 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00006148 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00006149 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6150 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00006151 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00006152 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00006153 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00006154}
6155
Chris Lattner326f7572008-11-18 01:30:42 +00006156// C99 6.5.17
6157QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00006158 DiagnoseUnusedExprResult(LHS);
6159
Chris Lattnerf6e1e302008-07-25 20:54:07 +00006160 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00006161 // C++ does not perform this conversion (C++ [expr.comma]p1).
6162 if (!getLangOptions().CPlusPlus)
6163 DefaultFunctionArrayLvalueConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00006164
6165 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
6166 // incomplete in C++).
6167
Chris Lattner326f7572008-11-18 01:30:42 +00006168 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00006169}
6170
Steve Naroff7a5af782007-07-13 16:58:59 +00006171/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6172/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00006173QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
Alexis Huntc46382e2010-04-28 23:02:27 +00006174 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006175 if (Op->isTypeDependent())
6176 return Context.DependentTy;
6177
Chris Lattner6b0cf142008-11-21 07:05:48 +00006178 QualType ResType = Op->getType();
6179 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00006180
Sebastian Redle10c2c32008-12-20 09:35:34 +00006181 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
6182 // Decrement of bool is not allowed.
6183 if (!isInc) {
6184 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
6185 return QualType();
6186 }
6187 // Increment of bool sets it to true, but is deprecated.
6188 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
6189 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006190 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00006191 } else if (ResType->isAnyPointerType()) {
6192 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006193
Chris Lattner6b0cf142008-11-21 07:05:48 +00006194 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00006195 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006196 if (getLangOptions().CPlusPlus) {
6197 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
6198 << Op->getSourceRange();
6199 return QualType();
6200 }
6201
6202 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00006203 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006204 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006205 if (getLangOptions().CPlusPlus) {
6206 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
6207 << Op->getType() << Op->getSourceRange();
6208 return QualType();
6209 }
6210
6211 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006212 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006213 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00006214 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00006215 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006216 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00006217 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006218 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006219 else if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006220 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6221 << PointeeTy << Op->getSourceRange();
6222 return QualType();
6223 }
Eli Friedman090addd2010-01-03 00:20:48 +00006224 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006225 // C99 does not support ++/-- on complex types, we allow as an extension.
6226 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006227 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00006228 } else {
6229 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00006230 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00006231 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00006232 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006233 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00006234 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00006235 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00006236 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00006237 // In C++, a prefix increment is the same type as the operand. Otherwise
6238 // (in C or with postfix), the increment is the unqualified type of the
6239 // operand.
6240 return isPrefix && getLangOptions().CPlusPlus
6241 ? ResType : ResType.getUnqualifiedType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006242}
6243
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00006244void Sema::ConvertPropertyAssignment(Expr *LHS, Expr *&RHS, QualType& LHSTy) {
6245 bool copyInit = false;
6246 if (const ObjCImplicitSetterGetterRefExpr *OISGE =
6247 dyn_cast<ObjCImplicitSetterGetterRefExpr>(LHS)) {
6248 // If using property-dot syntax notation for assignment, and there is a
6249 // setter, RHS expression is being passed to the setter argument. So,
6250 // type conversion (and comparison) is RHS to setter's argument type.
6251 if (const ObjCMethodDecl *SetterMD = OISGE->getSetterMethod()) {
6252 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
6253 LHSTy = (*P)->getType();
6254 }
6255 copyInit = (getLangOptions().CPlusPlus && LHSTy->isRecordType());
6256 }
6257 else
6258 copyInit = (getLangOptions().CPlusPlus && isa<ObjCPropertyRefExpr>(LHS) &&
6259 LHSTy->isRecordType());
6260 if (copyInit) {
6261 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00006262 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00006263 Expr *Arg = RHS;
6264 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
6265 Owned(Arg));
6266 if (!ArgE.isInvalid())
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00006267 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00006268 }
6269}
6270
6271
Anders Carlsson806700f2008-02-01 07:15:58 +00006272/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00006273/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00006274/// where the declaration is needed for type checking. We only need to
6275/// handle cases when the expression references a function designator
6276/// or is an lvalue. Here are some examples:
6277/// - &(x) => x
6278/// - &*****f => f for f a function designator.
6279/// - &s.xx => s
6280/// - &s.zz[1].yy -> s, if zz is an array
6281/// - *(x + 1) -> x, if x is an array
6282/// - &"123"[2] -> 0
6283/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006284static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006285 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00006286 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006287 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00006288 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00006289 // If this is an arrow operator, the address is an offset from
6290 // the base's value, so the object the base refers to is
6291 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006292 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00006293 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00006294 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006295 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00006296 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00006297 // FIXME: This code shouldn't be necessary! We should catch the implicit
6298 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00006299 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
6300 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
6301 if (ICE->getSubExpr()->getType()->isArrayType())
6302 return getPrimaryDecl(ICE->getSubExpr());
6303 }
6304 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00006305 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00006306 case Stmt::UnaryOperatorClass: {
6307 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006308
Daniel Dunbarb692ef42008-08-04 20:02:37 +00006309 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00006310 case UO_Real:
6311 case UO_Imag:
6312 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00006313 return getPrimaryDecl(UO->getSubExpr());
6314 default:
6315 return 0;
6316 }
6317 }
Steve Naroff47500512007-04-19 23:00:49 +00006318 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006319 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00006320 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00006321 // If the result of an implicit cast is an l-value, we care about
6322 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006323 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00006324 default:
6325 return 0;
6326 }
6327}
6328
6329/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00006330/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00006331/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006332/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00006333/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006334/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00006335/// we allow the '&' but retain the overloaded-function type.
John McCall8d08b9b2010-08-27 09:08:28 +00006336QualType Sema::CheckAddressOfOperand(Expr *OrigOp, SourceLocation OpLoc) {
6337 if (OrigOp->isTypeDependent())
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00006338 return Context.DependentTy;
John McCall8d08b9b2010-08-27 09:08:28 +00006339 if (OrigOp->getType() == Context.OverloadTy)
6340 return Context.OverloadTy;
6341
6342 // Make sure to ignore parentheses in subsequent checks
6343 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00006344
Steve Naroff826e91a2008-01-13 17:10:08 +00006345 if (getLangOptions().C99) {
6346 // Implement C99-only parts of addressof rules.
6347 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00006348 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00006349 // Per C99 6.5.3.2, the address of a deref always returns a valid result
6350 // (assuming the deref expression is valid).
6351 return uOp->getSubExpr()->getType();
6352 }
6353 // Technically, there should be a check for array subscript
6354 // expressions here, but the result of one is always an lvalue anyway.
6355 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006356 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00006357 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00006358
Chris Lattner9156f1b2010-07-05 19:17:26 +00006359 if (lval == Expr::LV_ClassTemporary) {
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006360 Diag(OpLoc, isSFINAEContext()? diag::err_typecheck_addrof_class_temporary
6361 : diag::ext_typecheck_addrof_class_temporary)
6362 << op->getType() << op->getSourceRange();
6363 if (isSFINAEContext())
6364 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00006365 } else if (isa<ObjCSelectorExpr>(op)) {
Chris Lattner9156f1b2010-07-05 19:17:26 +00006366 return Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00006367 } else if (lval == Expr::LV_MemberFunction) {
6368 // If it's an instance method, make a member pointer.
6369 // The expression must have exactly the form &A::foo.
6370
6371 // If the underlying expression isn't a decl ref, give up.
6372 if (!isa<DeclRefExpr>(op)) {
6373 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
6374 << OrigOp->getSourceRange();
6375 return QualType();
6376 }
6377 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
6378 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
6379
6380 // The id-expression was parenthesized.
6381 if (OrigOp != DRE) {
6382 Diag(OpLoc, diag::err_parens_pointer_member_function)
6383 << OrigOp->getSourceRange();
6384
6385 // The method was named without a qualifier.
6386 } else if (!DRE->getQualifier()) {
6387 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
6388 << op->getSourceRange();
6389 }
6390
6391 return Context.getMemberPointerType(op->getType(),
6392 Context.getTypeDeclType(MD->getParent()).getTypePtr());
6393 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00006394 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00006395 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00006396 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00006397 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00006398 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
6399 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00006400 return QualType();
6401 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00006402 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00006403 // The operand cannot be a bit-field
6404 Diag(OpLoc, diag::err_typecheck_address_of)
6405 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00006406 return QualType();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00006407 } else if (op->refersToVectorElement()) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00006408 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00006409 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00006410 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00006411 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00006412 } else if (isa<ObjCPropertyRefExpr>(op)) {
6413 // cannot take address of a property expression.
6414 Diag(OpLoc, diag::err_typecheck_address_of)
6415 << "property expression" << op->getSourceRange();
6416 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00006417 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
6418 // FIXME: Can LHS ever be null here?
Anders Carlsson01ccf992009-09-15 16:03:44 +00006419 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
6420 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
Steve Naroffb96e4ab62008-02-29 23:30:25 +00006421 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00006422 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00006423 // with the register storage-class specifier.
6424 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00006425 // in C++ it is not error to take address of a register
6426 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00006427 if (vd->getStorageClass() == SC_Register &&
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00006428 !getLangOptions().CPlusPlus) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006429 Diag(OpLoc, diag::err_typecheck_address_of)
6430 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00006431 return QualType();
6432 }
John McCalld14a8642009-11-21 08:51:07 +00006433 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006434 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00006435 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00006436 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006437 // Could be a pointer to member, though, if there is an explicit
6438 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006439 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006440 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00006441 if (Ctx && Ctx->isRecord()) {
6442 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006443 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00006444 diag::err_cannot_form_pointer_to_member_of_reference_type)
6445 << FD->getDeclName() << FD->getType();
6446 return QualType();
6447 }
Mike Stump11289f42009-09-09 15:08:12 +00006448
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006449 return Context.getMemberPointerType(op->getType(),
6450 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00006451 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006452 }
Anders Carlsson5b535762009-05-16 21:43:42 +00006453 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00006454 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00006455 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006456
Eli Friedmance7f9002009-05-16 23:27:50 +00006457 if (lval == Expr::LV_IncompleteVoidType) {
6458 // Taking the address of a void variable is technically illegal, but we
6459 // allow it in cases which are otherwise valid.
6460 // Example: "extern void x; void* y = &x;".
6461 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
6462 }
6463
Steve Naroff47500512007-04-19 23:00:49 +00006464 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00006465 if (op->getType()->isObjCObjectType())
6466 return Context.getObjCObjectPointerType(op->getType());
Steve Naroff35d85152007-05-07 00:24:15 +00006467 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00006468}
6469
Chris Lattner9156f1b2010-07-05 19:17:26 +00006470/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006471QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006472 if (Op->isTypeDependent())
6473 return Context.DependentTy;
6474
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006475 UsualUnaryConversions(Op);
Chris Lattner9156f1b2010-07-05 19:17:26 +00006476 QualType OpTy = Op->getType();
6477 QualType Result;
6478
6479 // Note that per both C89 and C99, indirection is always legal, even if OpTy
6480 // is an incomplete type or void. It would be possible to warn about
6481 // dereferencing a void pointer, but it's completely well-defined, and such a
6482 // warning is unlikely to catch any mistakes.
6483 if (const PointerType *PT = OpTy->getAs<PointerType>())
6484 Result = PT->getPointeeType();
6485 else if (const ObjCObjectPointerType *OPT =
6486 OpTy->getAs<ObjCObjectPointerType>())
6487 Result = OPT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006488
Chris Lattner9156f1b2010-07-05 19:17:26 +00006489 if (Result.isNull()) {
6490 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
6491 << OpTy << Op->getSourceRange();
6492 return QualType();
6493 }
6494
6495 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00006496}
Steve Naroff218bc2b2007-05-04 21:54:46 +00006497
John McCalle3027922010-08-25 11:45:40 +00006498static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00006499 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00006500 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006501 switch (Kind) {
6502 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00006503 case tok::periodstar: Opc = BO_PtrMemD; break;
6504 case tok::arrowstar: Opc = BO_PtrMemI; break;
6505 case tok::star: Opc = BO_Mul; break;
6506 case tok::slash: Opc = BO_Div; break;
6507 case tok::percent: Opc = BO_Rem; break;
6508 case tok::plus: Opc = BO_Add; break;
6509 case tok::minus: Opc = BO_Sub; break;
6510 case tok::lessless: Opc = BO_Shl; break;
6511 case tok::greatergreater: Opc = BO_Shr; break;
6512 case tok::lessequal: Opc = BO_LE; break;
6513 case tok::less: Opc = BO_LT; break;
6514 case tok::greaterequal: Opc = BO_GE; break;
6515 case tok::greater: Opc = BO_GT; break;
6516 case tok::exclaimequal: Opc = BO_NE; break;
6517 case tok::equalequal: Opc = BO_EQ; break;
6518 case tok::amp: Opc = BO_And; break;
6519 case tok::caret: Opc = BO_Xor; break;
6520 case tok::pipe: Opc = BO_Or; break;
6521 case tok::ampamp: Opc = BO_LAnd; break;
6522 case tok::pipepipe: Opc = BO_LOr; break;
6523 case tok::equal: Opc = BO_Assign; break;
6524 case tok::starequal: Opc = BO_MulAssign; break;
6525 case tok::slashequal: Opc = BO_DivAssign; break;
6526 case tok::percentequal: Opc = BO_RemAssign; break;
6527 case tok::plusequal: Opc = BO_AddAssign; break;
6528 case tok::minusequal: Opc = BO_SubAssign; break;
6529 case tok::lesslessequal: Opc = BO_ShlAssign; break;
6530 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
6531 case tok::ampequal: Opc = BO_AndAssign; break;
6532 case tok::caretequal: Opc = BO_XorAssign; break;
6533 case tok::pipeequal: Opc = BO_OrAssign; break;
6534 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006535 }
6536 return Opc;
6537}
6538
John McCalle3027922010-08-25 11:45:40 +00006539static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00006540 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00006541 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00006542 switch (Kind) {
6543 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00006544 case tok::plusplus: Opc = UO_PreInc; break;
6545 case tok::minusminus: Opc = UO_PreDec; break;
6546 case tok::amp: Opc = UO_AddrOf; break;
6547 case tok::star: Opc = UO_Deref; break;
6548 case tok::plus: Opc = UO_Plus; break;
6549 case tok::minus: Opc = UO_Minus; break;
6550 case tok::tilde: Opc = UO_Not; break;
6551 case tok::exclaim: Opc = UO_LNot; break;
6552 case tok::kw___real: Opc = UO_Real; break;
6553 case tok::kw___imag: Opc = UO_Imag; break;
6554 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006555 }
6556 return Opc;
6557}
6558
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006559/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6560/// operator @p Opc at location @c TokLoc. This routine only supports
6561/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00006562ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00006563 unsigned Op,
6564 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006565 QualType ResultTy; // Result type of the binary operator.
John McCalle3027922010-08-25 11:45:40 +00006566 BinaryOperatorKind Opc = (BinaryOperatorKind) Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006567 // The following two variables are used for compound assignment operators
6568 QualType CompLHSTy; // Type of LHS after promotions for computation
6569 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006570
6571 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006572 case BO_Assign:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006573 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6574 break;
John McCalle3027922010-08-25 11:45:40 +00006575 case BO_PtrMemD:
6576 case BO_PtrMemI:
Sebastian Redl112a97662009-02-07 00:15:38 +00006577 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00006578 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00006579 break;
John McCalle3027922010-08-25 11:45:40 +00006580 case BO_Mul:
6581 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00006582 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00006583 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006584 break;
John McCalle3027922010-08-25 11:45:40 +00006585 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006586 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6587 break;
John McCalle3027922010-08-25 11:45:40 +00006588 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006589 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6590 break;
John McCalle3027922010-08-25 11:45:40 +00006591 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006592 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6593 break;
John McCalle3027922010-08-25 11:45:40 +00006594 case BO_Shl:
6595 case BO_Shr:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006596 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6597 break;
John McCalle3027922010-08-25 11:45:40 +00006598 case BO_LE:
6599 case BO_LT:
6600 case BO_GE:
6601 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006602 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006603 break;
John McCalle3027922010-08-25 11:45:40 +00006604 case BO_EQ:
6605 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006606 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006607 break;
John McCalle3027922010-08-25 11:45:40 +00006608 case BO_And:
6609 case BO_Xor:
6610 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006611 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6612 break;
John McCalle3027922010-08-25 11:45:40 +00006613 case BO_LAnd:
6614 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00006615 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006616 break;
John McCalle3027922010-08-25 11:45:40 +00006617 case BO_MulAssign:
6618 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00006619 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCalle3027922010-08-25 11:45:40 +00006620 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006621 CompLHSTy = CompResultTy;
6622 if (!CompResultTy.isNull())
6623 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006624 break;
John McCalle3027922010-08-25 11:45:40 +00006625 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006626 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6627 CompLHSTy = CompResultTy;
6628 if (!CompResultTy.isNull())
6629 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006630 break;
John McCalle3027922010-08-25 11:45:40 +00006631 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006632 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6633 if (!CompResultTy.isNull())
6634 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006635 break;
John McCalle3027922010-08-25 11:45:40 +00006636 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006637 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6638 if (!CompResultTy.isNull())
6639 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006640 break;
John McCalle3027922010-08-25 11:45:40 +00006641 case BO_ShlAssign:
6642 case BO_ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006643 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6644 CompLHSTy = CompResultTy;
6645 if (!CompResultTy.isNull())
6646 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006647 break;
John McCalle3027922010-08-25 11:45:40 +00006648 case BO_AndAssign:
6649 case BO_XorAssign:
6650 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006651 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6652 CompLHSTy = CompResultTy;
6653 if (!CompResultTy.isNull())
6654 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006655 break;
John McCalle3027922010-08-25 11:45:40 +00006656 case BO_Comma:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006657 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6658 break;
6659 }
6660 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006661 return ExprError();
Fariborz Jahanian99311ba2010-08-16 21:51:12 +00006662 if (ResultTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
John McCalle3027922010-08-25 11:45:40 +00006663 if (Opc >= BO_Assign && Opc <= BO_OrAssign)
Fariborz Jahanian99311ba2010-08-16 21:51:12 +00006664 Diag(OpLoc, diag::err_assignment_requires_nonfragile_object)
6665 << ResultTy;
6666 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006667 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00006668 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6669 else
6670 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006671 CompLHSTy, CompResultTy,
6672 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006673}
6674
Sebastian Redl44615072009-10-27 12:10:02 +00006675/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6676/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006677static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6678 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006679 const PartialDiagnostic &FirstNote,
6680 SourceRange FirstParenRange,
6681 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00006682 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006683 Self.Diag(Loc, PD);
6684
6685 if (!FirstNote.getDiagID())
6686 return;
6687
6688 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
6689 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6690 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006691 return;
6692 }
6693
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006694 Self.Diag(Loc, FirstNote)
6695 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00006696 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006697
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006698 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006699 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006700
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006701 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6702 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6703 // We can't display the parentheses, so just dig the
6704 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006705 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006706 return;
6707 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006708
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006709 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00006710 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6711 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006712}
6713
Sebastian Redl44615072009-10-27 12:10:02 +00006714/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6715/// operators are mixed in a way that suggests that the programmer forgot that
6716/// comparison operators have higher precedence. The most typical example of
6717/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00006718static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00006719 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006720 typedef BinaryOperator BinOp;
6721 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6722 rhsopc = static_cast<BinOp::Opcode>(-1);
6723 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006724 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00006725 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006726 rhsopc = BO->getOpcode();
6727
6728 // Subs are not binary operators.
6729 if (lhsopc == -1 && rhsopc == -1)
6730 return;
6731
6732 // Bitwise operations are sometimes used as eager logical ops.
6733 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00006734 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6735 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00006736 return;
6737
Sebastian Redl44615072009-10-27 12:10:02 +00006738 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006739 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006740 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006741 << SourceRange(lhs->getLocStart(), OpLoc)
6742 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00006743 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006744 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006745 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
6746 Self.PDiag(diag::note_precedence_bitwise_silence)
6747 << BinOp::getOpcodeStr(lhsopc),
6748 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00006749 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006750 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006751 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006752 << SourceRange(OpLoc, rhs->getLocEnd())
6753 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00006754 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006755 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006756 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
6757 Self.PDiag(diag::note_precedence_bitwise_silence)
6758 << BinOp::getOpcodeStr(rhsopc),
6759 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00006760}
6761
6762/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6763/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6764/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
John McCalle3027922010-08-25 11:45:40 +00006765static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00006766 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006767 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl43028242009-10-26 15:24:15 +00006768 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6769}
6770
Steve Naroff218bc2b2007-05-04 21:54:46 +00006771// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00006772ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00006773 tok::TokenKind Kind,
6774 Expr *lhs, Expr *rhs) {
6775 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00006776 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6777 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00006778
Sebastian Redl43028242009-10-26 15:24:15 +00006779 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6780 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6781
Douglas Gregor5287f092009-11-05 00:51:44 +00006782 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6783}
6784
John McCalldadc5752010-08-24 06:29:42 +00006785ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00006786 BinaryOperatorKind Opc,
6787 Expr *lhs, Expr *rhs) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006788 if (getLangOptions().CPlusPlus &&
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00006789 ((!isa<ObjCImplicitSetterGetterRefExpr>(lhs) &&
6790 !isa<ObjCPropertyRefExpr>(lhs))
Fariborz Jahanianaaf44b22010-09-17 20:45:45 +00006791 || rhs->isTypeDependent() || Opc != BO_Assign) &&
Mike Stump11289f42009-09-09 15:08:12 +00006792 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006793 rhs->getType()->isOverloadableType())) {
6794 // Find all of the overloaded operators visible from this
6795 // point. We perform both an operator-name lookup from the local
6796 // scope and an argument-dependent lookup based on the types of
6797 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00006798 UnresolvedSet<16> Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006799 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00006800 if (S && OverOp != OO_None)
6801 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6802 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006803
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006804 // Build the (potentially-overloaded, potentially-dependent)
6805 // binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006806 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00006807 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006808
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006809 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006810 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006811}
6812
John McCalldadc5752010-08-24 06:29:42 +00006813ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006814 unsigned OpcIn,
John McCallb268a282010-08-23 23:25:46 +00006815 Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00006816 UnaryOperatorKind Opc = static_cast<UnaryOperatorKind>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00006817
Steve Naroff35d85152007-05-07 00:24:15 +00006818 QualType resultType;
6819 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006820 case UO_PreInc:
6821 case UO_PreDec:
6822 case UO_PostInc:
6823 case UO_PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00006824 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00006825 Opc == UO_PreInc ||
6826 Opc == UO_PostInc,
6827 Opc == UO_PreInc ||
6828 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00006829 break;
John McCalle3027922010-08-25 11:45:40 +00006830 case UO_AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00006831 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006832 break;
John McCalle3027922010-08-25 11:45:40 +00006833 case UO_Deref:
Douglas Gregorb92a1562010-02-03 00:27:59 +00006834 DefaultFunctionArrayLvalueConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00006835 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006836 break;
John McCalle3027922010-08-25 11:45:40 +00006837 case UO_Plus:
6838 case UO_Minus:
Steve Naroff31090012007-07-16 21:54:35 +00006839 UsualUnaryConversions(Input);
6840 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006841 if (resultType->isDependentType())
6842 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00006843 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
6844 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00006845 break;
6846 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6847 resultType->isEnumeralType())
6848 break;
6849 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00006850 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00006851 resultType->isPointerType())
6852 break;
6853
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006854 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6855 << resultType << Input->getSourceRange());
John McCalle3027922010-08-25 11:45:40 +00006856 case UO_Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00006857 UsualUnaryConversions(Input);
6858 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006859 if (resultType->isDependentType())
6860 break;
Chris Lattner0d707612008-07-25 23:52:49 +00006861 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6862 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6863 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00006864 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006865 << resultType << Input->getSourceRange();
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006866 else if (!resultType->hasIntegerRepresentation())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006867 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6868 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006869 break;
John McCalle3027922010-08-25 11:45:40 +00006870 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00006871 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00006872 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00006873 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006874 if (resultType->isDependentType())
6875 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006876 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006877 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6878 << resultType << Input->getSourceRange());
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00006879
6880 // Do not accept &f if f is overloaded
6881 // i.e. void f(int); void f(char); bool b = &f;
6882 if (resultType == Context.OverloadTy &&
6883 PerformContextuallyConvertToBool(Input))
6884 return ExprError(); // Diagnostic is uttered above
6885
Chris Lattnerbe31ed82007-06-02 19:11:33 +00006886 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006887 // In C++, it's bool. C++ 5.3.1p8
6888 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00006889 break;
John McCalle3027922010-08-25 11:45:40 +00006890 case UO_Real:
6891 case UO_Imag:
6892 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UO_Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00006893 break;
John McCalle3027922010-08-25 11:45:40 +00006894 case UO_Extension:
Chris Lattner86554282007-06-08 22:32:33 +00006895 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00006896 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006897 }
6898 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006899 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00006900
Steve Narofff6009ed2009-01-21 00:14:39 +00006901 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00006902}
Chris Lattnereefa10e2007-05-28 06:56:27 +00006903
John McCalldadc5752010-08-24 06:29:42 +00006904ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00006905 UnaryOperatorKind Opc,
6906 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00006907 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00006908 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006909 // Find all of the overloaded operators visible from this
6910 // point. We perform both an operator-name lookup from the local
6911 // scope and an argument-dependent lookup based on the types of
6912 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00006913 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00006914 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00006915 if (S && OverOp != OO_None)
6916 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6917 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006918
John McCallb268a282010-08-23 23:25:46 +00006919 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00006920 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006921
John McCallb268a282010-08-23 23:25:46 +00006922 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00006923}
6924
Douglas Gregor5287f092009-11-05 00:51:44 +00006925// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00006926ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00006927 tok::TokenKind Op, Expr *Input) {
6928 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00006929}
6930
Steve Naroff66356bd2007-09-16 14:56:35 +00006931/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
John McCalldadc5752010-08-24 06:29:42 +00006932ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006933 SourceLocation LabLoc,
6934 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00006935 // Look up the record for this label identifier.
John McCallaab3e412010-08-25 08:40:02 +00006936 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00006937
Daniel Dunbar88402ce2008-08-04 16:51:22 +00006938 // If we haven't seen this label yet, create a forward reference. It
6939 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00006940 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00006941 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006942
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00006943 LabelDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00006944 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006945 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6946 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00006947}
6948
John McCalldadc5752010-08-24 06:29:42 +00006949ExprResult
John McCallb268a282010-08-23 23:25:46 +00006950Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006951 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00006952 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6953 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6954
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00006955 bool isFileScope
6956 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00006957 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006958 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00006959
Chris Lattner366727f2007-07-24 16:58:17 +00006960 // FIXME: there are a variety of strange constraints to enforce here, for
6961 // example, it is not possible to goto into a stmt expression apparently.
6962 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006963
Chris Lattner366727f2007-07-24 16:58:17 +00006964 // If there are sub stmts in the compound stmt, take the type of the last one
6965 // as the type of the stmtexpr.
6966 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006967
Chris Lattner944d3062008-07-26 19:51:01 +00006968 if (!Compound->body_empty()) {
6969 Stmt *LastStmt = Compound->body_back();
6970 // If LastStmt is a label, skip down through into the body.
6971 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6972 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006973
Chris Lattner944d3062008-07-26 19:51:01 +00006974 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00006975 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00006976 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006977
Eli Friedmanba961a92009-03-23 00:24:07 +00006978 // FIXME: Check that expression type is complete/non-abstract; statement
6979 // expressions are not lvalues.
6980
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006981 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00006982}
Steve Naroff78864672007-08-01 22:05:33 +00006983
John McCalldadc5752010-08-24 06:29:42 +00006984ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
Douglas Gregor882211c2010-04-28 22:16:22 +00006985 TypeSourceInfo *TInfo,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006986 OffsetOfComponent *CompPtr,
6987 unsigned NumComponents,
Douglas Gregor882211c2010-04-28 22:16:22 +00006988 SourceLocation RParenLoc) {
6989 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006990 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006991 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00006992
Chris Lattnerf17bd422007-08-30 17:45:32 +00006993 // We must have at least one component that refers to the type, and the first
6994 // one is known to be a field designator. Verify that the ArgTy represents
6995 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006996 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00006997 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
6998 << ArgTy << TypeRange);
6999
7000 // Type must be complete per C99 7.17p3 because a declaring a variable
7001 // with an incomplete type would be ill-formed.
7002 if (!Dependent
7003 && RequireCompleteType(BuiltinLoc, ArgTy,
7004 PDiag(diag::err_offsetof_incomplete_type)
7005 << TypeRange))
7006 return ExprError();
7007
Chris Lattner78502cf2007-08-31 21:49:13 +00007008 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
7009 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00007010 // FIXME: This diagnostic isn't actually visible because the location is in
7011 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00007012 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00007013 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
7014 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00007015
7016 bool DidWarnAboutNonPOD = false;
7017 QualType CurrentType = ArgTy;
7018 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
7019 llvm::SmallVector<OffsetOfNode, 4> Comps;
7020 llvm::SmallVector<Expr*, 4> Exprs;
7021 for (unsigned i = 0; i != NumComponents; ++i) {
7022 const OffsetOfComponent &OC = CompPtr[i];
7023 if (OC.isBrackets) {
7024 // Offset of an array sub-field. TODO: Should we allow vector elements?
7025 if (!CurrentType->isDependentType()) {
7026 const ArrayType *AT = Context.getAsArrayType(CurrentType);
7027 if(!AT)
7028 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
7029 << CurrentType);
7030 CurrentType = AT->getElementType();
7031 } else
7032 CurrentType = Context.DependentTy;
7033
7034 // The expression must be an integral expression.
7035 // FIXME: An integral constant expression?
7036 Expr *Idx = static_cast<Expr*>(OC.U.E);
7037 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
7038 !Idx->getType()->isIntegerType())
7039 return ExprError(Diag(Idx->getLocStart(),
7040 diag::err_typecheck_subscript_not_integer)
7041 << Idx->getSourceRange());
7042
7043 // Record this array index.
7044 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
7045 Exprs.push_back(Idx);
7046 continue;
7047 }
7048
7049 // Offset of a field.
7050 if (CurrentType->isDependentType()) {
7051 // We have the offset of a field, but we can't look into the dependent
7052 // type. Just record the identifier of the field.
7053 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
7054 CurrentType = Context.DependentTy;
7055 continue;
7056 }
7057
7058 // We need to have a complete type to look into.
7059 if (RequireCompleteType(OC.LocStart, CurrentType,
7060 diag::err_offsetof_incomplete_type))
7061 return ExprError();
7062
7063 // Look for the designated field.
7064 const RecordType *RC = CurrentType->getAs<RecordType>();
7065 if (!RC)
7066 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
7067 << CurrentType);
7068 RecordDecl *RD = RC->getDecl();
7069
7070 // C++ [lib.support.types]p5:
7071 // The macro offsetof accepts a restricted set of type arguments in this
7072 // International Standard. type shall be a POD structure or a POD union
7073 // (clause 9).
7074 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7075 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
7076 DiagRuntimeBehavior(BuiltinLoc,
7077 PDiag(diag::warn_offsetof_non_pod_type)
7078 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
7079 << CurrentType))
7080 DidWarnAboutNonPOD = true;
7081 }
7082
7083 // Look for the field.
7084 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
7085 LookupQualifiedName(R, RD);
7086 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
7087 if (!MemberDecl)
7088 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
7089 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
7090 OC.LocEnd));
7091
Douglas Gregor10982ea2010-04-28 22:36:06 +00007092 // C99 7.17p3:
7093 // (If the specified member is a bit-field, the behavior is undefined.)
7094 //
7095 // We diagnose this as an error.
7096 if (MemberDecl->getBitWidth()) {
7097 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
7098 << MemberDecl->getDeclName()
7099 << SourceRange(BuiltinLoc, RParenLoc);
7100 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
7101 return ExprError();
7102 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00007103
7104 RecordDecl *Parent = MemberDecl->getParent();
7105 bool AnonStructUnion = Parent->isAnonymousStructOrUnion();
7106 if (AnonStructUnion) {
7107 do {
7108 Parent = cast<RecordDecl>(Parent->getParent());
7109 } while (Parent->isAnonymousStructOrUnion());
7110 }
7111
Douglas Gregord1702062010-04-29 00:18:15 +00007112 // If the member was found in a base class, introduce OffsetOfNodes for
7113 // the base class indirections.
7114 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
7115 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00007116 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00007117 CXXBasePath &Path = Paths.front();
7118 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
7119 B != BEnd; ++B)
7120 Comps.push_back(OffsetOfNode(B->Base));
7121 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00007122
7123 if (AnonStructUnion) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007124 llvm::SmallVector<FieldDecl*, 4> Path;
7125 BuildAnonymousStructUnionMemberPath(MemberDecl, Path);
7126 unsigned n = Path.size();
7127 for (int j = n - 1; j > -1; --j)
7128 Comps.push_back(OffsetOfNode(OC.LocStart, Path[j], OC.LocEnd));
7129 } else {
7130 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
7131 }
7132 CurrentType = MemberDecl->getType().getNonReferenceType();
7133 }
7134
7135 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
7136 TInfo, Comps.data(), Comps.size(),
7137 Exprs.data(), Exprs.size(), RParenLoc));
7138}
Mike Stump4e1f26a2009-02-19 03:04:26 +00007139
John McCalldadc5752010-08-24 06:29:42 +00007140ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
Douglas Gregor882211c2010-04-28 22:16:22 +00007141 SourceLocation BuiltinLoc,
7142 SourceLocation TypeLoc,
John McCallba7bf592010-08-24 05:47:05 +00007143 ParsedType argty,
Douglas Gregor882211c2010-04-28 22:16:22 +00007144 OffsetOfComponent *CompPtr,
7145 unsigned NumComponents,
7146 SourceLocation RPLoc) {
7147
7148 TypeSourceInfo *ArgTInfo;
7149 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
7150 if (ArgTy.isNull())
7151 return ExprError();
7152
Eli Friedman06dcfd92010-08-05 10:15:45 +00007153 if (!ArgTInfo)
7154 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
7155
7156 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
7157 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00007158}
7159
7160
John McCalldadc5752010-08-24 06:29:42 +00007161ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00007162 ParsedType arg1,ParsedType arg2,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007163 SourceLocation RPLoc) {
Abramo Bagnara092990a2010-08-10 08:50:03 +00007164 TypeSourceInfo *argTInfo1;
7165 QualType argT1 = GetTypeFromParser(arg1, &argTInfo1);
7166 TypeSourceInfo *argTInfo2;
7167 QualType argT2 = GetTypeFromParser(arg2, &argTInfo2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007168
Steve Naroff78864672007-08-01 22:05:33 +00007169 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00007170
Abramo Bagnara092990a2010-08-10 08:50:03 +00007171 return BuildTypesCompatibleExpr(BuiltinLoc, argTInfo1, argTInfo2, RPLoc);
7172}
7173
John McCalldadc5752010-08-24 06:29:42 +00007174ExprResult
Abramo Bagnara092990a2010-08-10 08:50:03 +00007175Sema::BuildTypesCompatibleExpr(SourceLocation BuiltinLoc,
7176 TypeSourceInfo *argTInfo1,
7177 TypeSourceInfo *argTInfo2,
7178 SourceLocation RPLoc) {
Douglas Gregorf907cbf2009-05-19 22:28:02 +00007179 if (getLangOptions().CPlusPlus) {
7180 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
7181 << SourceRange(BuiltinLoc, RPLoc);
7182 return ExprError();
7183 }
7184
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007185 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
Abramo Bagnara092990a2010-08-10 08:50:03 +00007186 argTInfo1, argTInfo2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00007187}
7188
Abramo Bagnara092990a2010-08-10 08:50:03 +00007189
John McCalldadc5752010-08-24 06:29:42 +00007190ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCallb268a282010-08-23 23:25:46 +00007191 Expr *CondExpr,
7192 Expr *LHSExpr, Expr *RHSExpr,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007193 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00007194 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
7195
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007196 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00007197 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00007198 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007199 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00007200 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007201 } else {
7202 // The conditional expression is required to be a constant expression.
7203 llvm::APSInt condEval(32);
7204 SourceLocation ExpLoc;
7205 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007206 return ExprError(Diag(ExpLoc,
7207 diag::err_typecheck_choose_expr_requires_constant)
7208 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00007209
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007210 // If the condition is > zero, then the AST type is the same as the LSHExpr.
7211 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregor56751b52009-09-25 04:25:58 +00007212 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
7213 : RHSExpr->isValueDependent();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007214 }
7215
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007216 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregor56751b52009-09-25 04:25:58 +00007217 resType, RPLoc,
7218 resType->isDependentType(),
7219 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00007220}
7221
Steve Naroffc540d662008-09-03 18:15:37 +00007222//===----------------------------------------------------------------------===//
7223// Clang Extensions.
7224//===----------------------------------------------------------------------===//
7225
7226/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00007227void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00007228 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
7229 PushBlockScope(BlockScope, Block);
7230 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00007231 if (BlockScope)
7232 PushDeclContext(BlockScope, Block);
7233 else
7234 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00007235}
7236
Mike Stump82f071f2009-02-04 22:31:32 +00007237void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00007238 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Douglas Gregor9a28e842010-03-01 23:15:13 +00007239 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007240
John McCall8cb7bdf2010-06-04 23:28:52 +00007241 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCalla3ccba02010-06-04 11:21:44 +00007242 CurBlock->TheDecl->setSignatureAsWritten(Sig);
John McCall8cb7bdf2010-06-04 23:28:52 +00007243 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00007244
John McCall8e346702010-06-04 19:02:56 +00007245 bool isVariadic;
John McCalla3ccba02010-06-04 11:21:44 +00007246 QualType RetTy;
7247 if (const FunctionType *Fn = T->getAs<FunctionType>()) {
John McCall8e346702010-06-04 19:02:56 +00007248 CurBlock->FunctionType = T;
John McCalla3ccba02010-06-04 11:21:44 +00007249 RetTy = Fn->getResultType();
John McCall8e346702010-06-04 19:02:56 +00007250 isVariadic =
John McCalla3ccba02010-06-04 11:21:44 +00007251 !isa<FunctionProtoType>(Fn) || cast<FunctionProtoType>(Fn)->isVariadic();
7252 } else {
7253 RetTy = T;
John McCall8e346702010-06-04 19:02:56 +00007254 isVariadic = false;
John McCalla3ccba02010-06-04 11:21:44 +00007255 }
Mike Stump11289f42009-09-09 15:08:12 +00007256
John McCall8e346702010-06-04 19:02:56 +00007257 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00007258
John McCalla3ccba02010-06-04 11:21:44 +00007259 // Don't allow returning an array by value.
7260 if (RetTy->isArrayType()) {
7261 Diag(ParamInfo.getSourceRange().getBegin(), diag::err_block_returns_array);
Mike Stump82f071f2009-02-04 22:31:32 +00007262 return;
7263 }
7264
John McCalla3ccba02010-06-04 11:21:44 +00007265 // Don't allow returning a objc interface by value.
7266 if (RetTy->isObjCObjectType()) {
7267 Diag(ParamInfo.getSourceRange().getBegin(),
7268 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
7269 return;
7270 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007271
John McCalla3ccba02010-06-04 11:21:44 +00007272 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00007273 // return type. TODO: what should we do with declarators like:
7274 // ^ * { ... }
7275 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00007276 if (RetTy != Context.DependentTy)
7277 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007278
John McCalla3ccba02010-06-04 11:21:44 +00007279 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00007280 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCalla3ccba02010-06-04 11:21:44 +00007281 if (isa<FunctionProtoType>(T)) {
7282 FunctionProtoTypeLoc TL = cast<FunctionProtoTypeLoc>(Sig->getTypeLoc());
7283 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
7284 ParmVarDecl *Param = TL.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00007285 if (Param->getIdentifier() == 0 &&
7286 !Param->isImplicit() &&
7287 !Param->isInvalidDecl() &&
7288 !getLangOptions().CPlusPlus)
7289 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00007290 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00007291 }
John McCalla3ccba02010-06-04 11:21:44 +00007292
7293 // Fake up parameter variables if we have a typedef, like
7294 // ^ fntype { ... }
7295 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
7296 for (FunctionProtoType::arg_type_iterator
7297 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
7298 ParmVarDecl *Param =
7299 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
7300 ParamInfo.getSourceRange().getBegin(),
7301 *I);
John McCall8e346702010-06-04 19:02:56 +00007302 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00007303 }
Steve Naroffc540d662008-09-03 18:15:37 +00007304 }
John McCalla3ccba02010-06-04 11:21:44 +00007305
John McCall8e346702010-06-04 19:02:56 +00007306 // Set the parameters on the block decl.
7307 if (!Params.empty())
7308 CurBlock->TheDecl->setParams(Params.data(), Params.size());
John McCalla3ccba02010-06-04 11:21:44 +00007309
7310 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00007311 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00007312
John McCall8e346702010-06-04 19:02:56 +00007313 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00007314 Diag(ParamInfo.getAttributes()->getLoc(),
7315 diag::warn_attribute_sentinel_not_variadic) << 1;
7316 // FIXME: remove the attribute.
7317 }
7318
7319 // Put the parameter variables in scope. We can bail out immediately
7320 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00007321 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00007322 return;
7323
John McCalldf8b37c2010-03-22 09:20:08 +00007324 bool ShouldCheckShadow =
7325 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
7326
Steve Naroff1d95e5a2008-10-10 01:28:17 +00007327 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00007328 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
7329 (*AI)->setOwningFunction(CurBlock->TheDecl);
7330
Steve Naroff1d95e5a2008-10-10 01:28:17 +00007331 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00007332 if ((*AI)->getIdentifier()) {
7333 if (ShouldCheckShadow)
7334 CheckShadow(CurBlock->TheScope, *AI);
7335
Steve Naroff1d95e5a2008-10-10 01:28:17 +00007336 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00007337 }
John McCallf7b2fb52010-01-22 00:28:27 +00007338 }
Steve Naroffc540d662008-09-03 18:15:37 +00007339}
7340
7341/// ActOnBlockError - If there is an error parsing a block, this callback
7342/// is invoked to pop the information about the block from the action impl.
7343void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00007344 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00007345 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00007346 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00007347 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00007348}
7349
7350/// ActOnBlockStmtExpr - This is called when the body of a block statement
7351/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00007352ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
John McCallb268a282010-08-23 23:25:46 +00007353 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00007354 // If blocks are disabled, emit an error.
7355 if (!LangOpts.Blocks)
7356 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00007357
Douglas Gregor9a28e842010-03-01 23:15:13 +00007358 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00007359
Steve Naroff1d95e5a2008-10-10 01:28:17 +00007360 PopDeclContext();
7361
Steve Naroffc540d662008-09-03 18:15:37 +00007362 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00007363 if (!BSI->ReturnType.isNull())
7364 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007365
Mike Stump3bf1ab42009-07-28 22:04:01 +00007366 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00007367 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00007368
7369 // If the user wrote a function type in some form, try to use that.
7370 if (!BSI->FunctionType.isNull()) {
7371 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
7372
7373 FunctionType::ExtInfo Ext = FTy->getExtInfo();
7374 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
7375
7376 // Turn protoless block types into nullary block types.
7377 if (isa<FunctionNoProtoType>(FTy)) {
7378 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
7379 false, false, 0, 0, Ext);
7380
7381 // Otherwise, if we don't need to change anything about the function type,
7382 // preserve its sugar structure.
7383 } else if (FTy->getResultType() == RetTy &&
7384 (!NoReturn || FTy->getNoReturnAttr())) {
7385 BlockTy = BSI->FunctionType;
7386
7387 // Otherwise, make the minimal modifications to the function type.
7388 } else {
7389 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
7390 BlockTy = Context.getFunctionType(RetTy,
7391 FPT->arg_type_begin(),
7392 FPT->getNumArgs(),
7393 FPT->isVariadic(),
7394 /*quals*/ 0,
7395 FPT->hasExceptionSpec(),
7396 FPT->hasAnyExceptionSpec(),
7397 FPT->getNumExceptions(),
7398 FPT->exception_begin(),
7399 Ext);
7400 }
7401
7402 // If we don't have a function type, just build one from nothing.
7403 } else {
7404 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
7405 false, false, 0, 0,
7406 FunctionType::ExtInfo(NoReturn, 0, CC_Default));
7407 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007408
Eli Friedmanba961a92009-03-23 00:24:07 +00007409 // FIXME: Check that return/parameter types are complete/non-abstract
John McCall8e346702010-06-04 19:02:56 +00007410 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
7411 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00007412 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007413
Chris Lattner45542ea2009-04-19 05:28:12 +00007414 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00007415 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00007416 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00007417
John McCallb268a282010-08-23 23:25:46 +00007418 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Mike Stump314825b2010-01-19 23:08:01 +00007419
7420 bool Good = true;
7421 // Check goto/label use.
7422 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
7423 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
7424 LabelStmt *L = I->second;
7425
7426 // Verify that we have no forward references left. If so, there was a goto
7427 // or address of a label taken, but no definition of it.
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00007428 if (L->getSubStmt() != 0) {
7429 if (!L->isUsed())
7430 Diag(L->getIdentLoc(), diag::warn_unused_label) << L->getName();
Mike Stump314825b2010-01-19 23:08:01 +00007431 continue;
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00007432 }
Mike Stump314825b2010-01-19 23:08:01 +00007433
7434 // Emit error.
7435 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
7436 Good = false;
7437 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00007438 if (!Good) {
7439 PopFunctionOrBlockScope();
Mike Stump314825b2010-01-19 23:08:01 +00007440 return ExprError();
Douglas Gregor9a28e842010-03-01 23:15:13 +00007441 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007442
John McCall1d570a72010-08-25 05:56:39 +00007443 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
7444 BSI->hasBlockDeclRefExprs);
7445
Ted Kremenek918fe842010-03-20 21:06:02 +00007446 // Issue any analysis-based warnings.
Ted Kremenek0b405322010-03-23 00:13:23 +00007447 const sema::AnalysisBasedWarnings::Policy &WP =
7448 AnalysisWarnings.getDefaultPolicy();
John McCall1d570a72010-08-25 05:56:39 +00007449 AnalysisWarnings.IssueWarnings(WP, Result);
Ted Kremenek918fe842010-03-20 21:06:02 +00007450
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007451 PopFunctionOrBlockScope();
Douglas Gregor9a28e842010-03-01 23:15:13 +00007452 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00007453}
7454
John McCalldadc5752010-08-24 06:29:42 +00007455ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00007456 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007457 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00007458 TypeSourceInfo *TInfo;
7459 QualType T = GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00007460 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00007461}
7462
John McCalldadc5752010-08-24 06:29:42 +00007463ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallb268a282010-08-23 23:25:46 +00007464 Expr *E, TypeSourceInfo *TInfo,
Abramo Bagnara27db2392010-08-10 10:06:15 +00007465 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00007466 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00007467
Eli Friedman121ba0c2008-08-09 23:32:40 +00007468 // Get the va_list type
7469 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00007470 if (VaListType->isArrayType()) {
7471 // Deal with implicit array decay; for example, on x86-64,
7472 // va_list is an array, but it's supposed to decay to
7473 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00007474 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00007475 // Make sure the input expression also decays appropriately.
7476 UsualUnaryConversions(E);
7477 } else {
7478 // Otherwise, the va_list argument must be an l-value because
7479 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00007480 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00007481 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00007482 return ExprError();
7483 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00007484
Douglas Gregorad3150c2009-05-19 23:10:31 +00007485 if (!E->isTypeDependent() &&
7486 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007487 return ExprError(Diag(E->getLocStart(),
7488 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00007489 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00007490 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007491
Eli Friedmanba961a92009-03-23 00:24:07 +00007492 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00007493 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007494
Abramo Bagnara27db2392010-08-10 10:06:15 +00007495 QualType T = TInfo->getType().getNonLValueExprType(Context);
7496 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00007497}
7498
John McCalldadc5752010-08-24 06:29:42 +00007499ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00007500 // The type of __null will be int or long, depending on the size of
7501 // pointers on the target.
7502 QualType Ty;
7503 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
7504 Ty = Context.IntTy;
7505 else
7506 Ty = Context.LongTy;
7507
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007508 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00007509}
7510
Alexis Huntc46382e2010-04-28 23:02:27 +00007511static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00007512 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00007513 if (!SemaRef.getLangOptions().ObjC1)
7514 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007515
Anders Carlssonace5d072009-11-10 04:46:30 +00007516 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
7517 if (!PT)
7518 return;
7519
7520 // Check if the destination is of type 'id'.
7521 if (!PT->isObjCIdType()) {
7522 // Check if the destination is the 'NSString' interface.
7523 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
7524 if (!ID || !ID->getIdentifier()->isStr("NSString"))
7525 return;
7526 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007527
Anders Carlssonace5d072009-11-10 04:46:30 +00007528 // Strip off any parens and casts.
7529 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
7530 if (!SL || SL->isWide())
7531 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007532
Douglas Gregora771f462010-03-31 17:46:05 +00007533 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00007534}
7535
Chris Lattner9bad62c2008-01-04 18:04:52 +00007536bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
7537 SourceLocation Loc,
7538 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007539 Expr *SrcExpr, AssignmentAction Action,
7540 bool *Complained) {
7541 if (Complained)
7542 *Complained = false;
7543
Chris Lattner9bad62c2008-01-04 18:04:52 +00007544 // Decode the result (notice that AST's are still created for extensions).
7545 bool isInvalid = false;
7546 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00007547 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007548
Chris Lattner9bad62c2008-01-04 18:04:52 +00007549 switch (ConvTy) {
7550 default: assert(0 && "Unknown conversion type");
7551 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00007552 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00007553 DiagKind = diag::ext_typecheck_convert_pointer_int;
7554 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00007555 case IntToPointer:
7556 DiagKind = diag::ext_typecheck_convert_int_pointer;
7557 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007558 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00007559 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007560 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
7561 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00007562 case IncompatiblePointerSign:
7563 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
7564 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007565 case FunctionVoidPointer:
7566 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
7567 break;
7568 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00007569 // If the qualifiers lost were because we were applying the
7570 // (deprecated) C++ conversion from a string literal to a char*
7571 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
7572 // Ideally, this check would be performed in
7573 // CheckPointerTypesForAssignment. However, that would require a
7574 // bit of refactoring (so that the second argument is an
7575 // expression, rather than a type), which should be done as part
7576 // of a larger effort to fix CheckPointerTypesForAssignment for
7577 // C++ semantics.
7578 if (getLangOptions().CPlusPlus &&
7579 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
7580 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007581 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
7582 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00007583 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00007584 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00007585 break;
Steve Naroff081c7422008-09-04 15:10:53 +00007586 case IntToBlockPointer:
7587 DiagKind = diag::err_int_to_block_pointer;
7588 break;
7589 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00007590 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00007591 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00007592 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00007593 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00007594 // it can give a more specific diagnostic.
7595 DiagKind = diag::warn_incompatible_qualified_id;
7596 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007597 case IncompatibleVectors:
7598 DiagKind = diag::warn_incompatible_vectors;
7599 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007600 case Incompatible:
7601 DiagKind = diag::err_typecheck_convert_incompatible;
7602 isInvalid = true;
7603 break;
7604 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007605
Douglas Gregorc68e1402010-04-09 00:35:39 +00007606 QualType FirstType, SecondType;
7607 switch (Action) {
7608 case AA_Assigning:
7609 case AA_Initializing:
7610 // The destination type comes first.
7611 FirstType = DstType;
7612 SecondType = SrcType;
7613 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00007614
Douglas Gregorc68e1402010-04-09 00:35:39 +00007615 case AA_Returning:
7616 case AA_Passing:
7617 case AA_Converting:
7618 case AA_Sending:
7619 case AA_Casting:
7620 // The source type comes first.
7621 FirstType = SrcType;
7622 SecondType = DstType;
7623 break;
7624 }
Alexis Huntc46382e2010-04-28 23:02:27 +00007625
Douglas Gregorc68e1402010-04-09 00:35:39 +00007626 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00007627 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007628 if (Complained)
7629 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007630 return isInvalid;
7631}
Anders Carlssone54e8a12008-11-30 19:50:32 +00007632
Chris Lattnerc71d08b2009-04-25 21:59:05 +00007633bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007634 llvm::APSInt ICEResult;
7635 if (E->isIntegerConstantExpr(ICEResult, Context)) {
7636 if (Result)
7637 *Result = ICEResult;
7638 return false;
7639 }
7640
Anders Carlssone54e8a12008-11-30 19:50:32 +00007641 Expr::EvalResult EvalResult;
7642
Mike Stump4e1f26a2009-02-19 03:04:26 +00007643 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00007644 EvalResult.HasSideEffects) {
7645 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7646
7647 if (EvalResult.Diag) {
7648 // We only show the note if it's not the usual "invalid subexpression"
7649 // or if it's actually in a subexpression.
7650 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7651 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7652 Diag(EvalResult.DiagLoc, EvalResult.Diag);
7653 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007654
Anders Carlssone54e8a12008-11-30 19:50:32 +00007655 return true;
7656 }
7657
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007658 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7659 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00007660
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007661 if (EvalResult.Diag &&
7662 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7663 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007664
Anders Carlssone54e8a12008-11-30 19:50:32 +00007665 if (Result)
7666 *Result = EvalResult.Val.getInt();
7667 return false;
7668}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007669
Douglas Gregorff790f12009-11-26 00:44:06 +00007670void
Mike Stump11289f42009-09-09 15:08:12 +00007671Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00007672 ExprEvalContexts.push_back(
7673 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007674}
7675
Mike Stump11289f42009-09-09 15:08:12 +00007676void
Douglas Gregorff790f12009-11-26 00:44:06 +00007677Sema::PopExpressionEvaluationContext() {
7678 // Pop the current expression evaluation context off the stack.
7679 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7680 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007681
Douglas Gregorfab31f42009-12-12 07:57:52 +00007682 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7683 if (Rec.PotentiallyReferenced) {
7684 // Mark any remaining declarations in the current position of the stack
7685 // as "referenced". If they were not meant to be referenced, semantic
7686 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007687 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00007688 I = Rec.PotentiallyReferenced->begin(),
7689 IEnd = Rec.PotentiallyReferenced->end();
7690 I != IEnd; ++I)
7691 MarkDeclarationReferenced(I->first, I->second);
7692 }
7693
7694 if (Rec.PotentiallyDiagnosed) {
7695 // Emit any pending diagnostics.
7696 for (PotentiallyEmittedDiagnostics::iterator
7697 I = Rec.PotentiallyDiagnosed->begin(),
7698 IEnd = Rec.PotentiallyDiagnosed->end();
7699 I != IEnd; ++I)
7700 Diag(I->first, I->second);
7701 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007702 }
Douglas Gregorff790f12009-11-26 00:44:06 +00007703
7704 // When are coming out of an unevaluated context, clear out any
7705 // temporaries that we may have created as part of the evaluation of
7706 // the expression in that context: they aren't relevant because they
7707 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007708 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00007709 ExprTemporaries.size() > Rec.NumTemporaries)
7710 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7711 ExprTemporaries.end());
7712
7713 // Destroy the popped expression evaluation record.
7714 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007715}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007716
7717/// \brief Note that the given declaration was referenced in the source code.
7718///
7719/// This routine should be invoke whenever a given declaration is referenced
7720/// in the source code, and where that reference occurred. If this declaration
7721/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7722/// C99 6.9p3), then the declaration will be marked as used.
7723///
7724/// \param Loc the location where the declaration was referenced.
7725///
7726/// \param D the declaration that has been referenced by the source code.
7727void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7728 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00007729
Douglas Gregorebada0772010-06-17 23:14:26 +00007730 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00007731 return;
Mike Stump11289f42009-09-09 15:08:12 +00007732
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00007733 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7734 // template or not. The reason for this is that unevaluated expressions
7735 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7736 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007737 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00007738 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007739 D->setUsed(true);
Douglas Gregorfd27fed2010-04-07 20:29:57 +00007740 return;
7741 }
Alexis Huntc46382e2010-04-28 23:02:27 +00007742
Douglas Gregorfd27fed2010-04-07 20:29:57 +00007743 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
7744 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00007745
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007746 // Do not mark anything as "used" within a dependent context; wait for
7747 // an instantiation.
7748 if (CurContext->isDependentContext())
7749 return;
Mike Stump11289f42009-09-09 15:08:12 +00007750
Douglas Gregorff790f12009-11-26 00:44:06 +00007751 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007752 case Unevaluated:
7753 // We are in an expression that is not potentially evaluated; do nothing.
7754 return;
Mike Stump11289f42009-09-09 15:08:12 +00007755
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007756 case PotentiallyEvaluated:
7757 // We are in a potentially-evaluated expression, so this declaration is
7758 // "used"; handle this below.
7759 break;
Mike Stump11289f42009-09-09 15:08:12 +00007760
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007761 case PotentiallyPotentiallyEvaluated:
7762 // We are in an expression that may be potentially evaluated; queue this
7763 // declaration reference until we know whether the expression is
7764 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00007765 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007766 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00007767
7768 case PotentiallyEvaluatedIfUsed:
7769 // Referenced declarations will only be used if the construct in the
7770 // containing expression is used.
7771 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007772 }
Mike Stump11289f42009-09-09 15:08:12 +00007773
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007774 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00007775 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007776 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007777 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00007778 if (Constructor->getParent()->hasTrivialConstructor())
7779 return;
7780 if (!Constructor->isUsed(false))
7781 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00007782 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00007783 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00007784 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007785 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7786 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007787
Douglas Gregor88d292c2010-05-13 16:44:06 +00007788 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007789 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00007790 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007791 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00007792 if (Destructor->isVirtual())
7793 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007794 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7795 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7796 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00007797 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00007798 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00007799 } else if (MethodDecl->isVirtual())
7800 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007801 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00007802 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00007803 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00007804 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00007805 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00007806 bool AlreadyInstantiated = false;
7807 if (FunctionTemplateSpecializationInfo *SpecInfo
7808 = Function->getTemplateSpecializationInfo()) {
7809 if (SpecInfo->getPointOfInstantiation().isInvalid())
7810 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007811 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00007812 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007813 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007814 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00007815 = Function->getMemberSpecializationInfo()) {
7816 if (MSInfo->getPointOfInstantiation().isInvalid())
7817 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007818 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00007819 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007820 AlreadyInstantiated = true;
7821 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007822
Douglas Gregor7f792cf2010-01-16 22:29:39 +00007823 if (!AlreadyInstantiated) {
7824 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
7825 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
7826 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
7827 Loc));
7828 else
Chandler Carruth54080172010-08-25 08:44:16 +00007829 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00007830 }
Gabor Greifb6aba3e2010-08-28 00:16:06 +00007831 } else // Walk redefinitions, as some of them may be instantiable.
7832 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
7833 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00007834 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00007835 MarkDeclarationReferenced(Loc, *i);
7836 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007837
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007838 // FIXME: keep track of references to static functions
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00007839
7840 // Recursive functions should be marked when used from another function.
7841 if (CurContext != Function)
7842 Function->setUsed(true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007843
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007844 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00007845 }
Mike Stump11289f42009-09-09 15:08:12 +00007846
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007847 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007848 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00007849 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00007850 Var->getInstantiatedFromStaticDataMember()) {
7851 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7852 assert(MSInfo && "Missing member specialization information?");
7853 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7854 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7855 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +00007856 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00007857 }
7858 }
Mike Stump11289f42009-09-09 15:08:12 +00007859
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007860 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007861
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007862 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007863 return;
Sam Weinigbae69142009-09-11 03:29:30 +00007864 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007865}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007866
Douglas Gregor5597ab42010-05-07 23:12:07 +00007867namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00007868 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00007869 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00007870 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00007871 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
7872 Sema &S;
7873 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00007874
Douglas Gregor5597ab42010-05-07 23:12:07 +00007875 public:
7876 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00007877
Douglas Gregor5597ab42010-05-07 23:12:07 +00007878 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00007879
7880 bool TraverseTemplateArgument(const TemplateArgument &Arg);
7881 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00007882 };
7883}
7884
Chandler Carruthaf80f662010-06-09 08:17:30 +00007885bool MarkReferencedDecls::TraverseTemplateArgument(
7886 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00007887 if (Arg.getKind() == TemplateArgument::Declaration) {
7888 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
7889 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00007890
7891 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00007892}
7893
Chandler Carruthaf80f662010-06-09 08:17:30 +00007894bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00007895 if (ClassTemplateSpecializationDecl *Spec
7896 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
7897 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Chandler Carruthaf80f662010-06-09 08:17:30 +00007898 return TraverseTemplateArguments(Args.getFlatArgumentList(),
7899 Args.flat_size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00007900 }
7901
Chandler Carruthc65667c2010-06-10 10:31:57 +00007902 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00007903}
7904
7905void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
7906 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00007907 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00007908}
7909
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00007910namespace {
7911 /// \brief Helper class that marks all of the declarations referenced by
7912 /// potentially-evaluated subexpressions as "referenced".
7913 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
7914 Sema &S;
7915
7916 public:
7917 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
7918
7919 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
7920
7921 void VisitDeclRefExpr(DeclRefExpr *E) {
7922 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
7923 }
7924
7925 void VisitMemberExpr(MemberExpr *E) {
7926 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00007927 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00007928 }
7929
7930 void VisitCXXNewExpr(CXXNewExpr *E) {
7931 if (E->getConstructor())
7932 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
7933 if (E->getOperatorNew())
7934 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
7935 if (E->getOperatorDelete())
7936 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00007937 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00007938 }
7939
7940 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
7941 if (E->getOperatorDelete())
7942 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00007943 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
7944 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
7945 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
7946 S.MarkDeclarationReferenced(E->getLocStart(),
7947 S.LookupDestructor(Record));
7948 }
7949
Douglas Gregor32b3de52010-09-11 23:32:50 +00007950 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00007951 }
7952
7953 void VisitCXXConstructExpr(CXXConstructExpr *E) {
7954 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00007955 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00007956 }
7957
7958 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
7959 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
7960 }
7961 };
7962}
7963
7964/// \brief Mark any declarations that appear within this expression or any
7965/// potentially-evaluated subexpressions as "referenced".
7966void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
7967 EvaluatedExprMarker(*this).Visit(E);
7968}
7969
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007970/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7971/// of the program being compiled.
7972///
7973/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007974/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007975/// possibility that the code will actually be executable. Code in sizeof()
7976/// expressions, code used only during overload resolution, etc., are not
7977/// potentially evaluated. This routine will suppress such diagnostics or,
7978/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007979/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007980/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007981///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007982/// This routine should be used for all diagnostics that describe the run-time
7983/// behavior of a program, such as passing a non-POD value through an ellipsis.
7984/// Failure to do so will likely result in spurious diagnostics or failures
7985/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007986bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007987 const PartialDiagnostic &PD) {
7988 switch (ExprEvalContexts.back().Context ) {
7989 case Unevaluated:
7990 // The argument will never be evaluated, so don't complain.
7991 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007992
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007993 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00007994 case PotentiallyEvaluatedIfUsed:
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007995 Diag(Loc, PD);
7996 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007997
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007998 case PotentiallyPotentiallyEvaluated:
7999 ExprEvalContexts.back().addDiagnostic(Loc, PD);
8000 break;
8001 }
8002
8003 return false;
8004}
8005
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008006bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
8007 CallExpr *CE, FunctionDecl *FD) {
8008 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
8009 return false;
8010
8011 PartialDiagnostic Note =
8012 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
8013 << FD->getDeclName() : PDiag();
8014 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008015
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008016 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008017 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008018 PDiag(diag::err_call_function_incomplete_return)
8019 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008020 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008021 << CE->getSourceRange(),
8022 std::make_pair(NoteLoc, Note)))
8023 return true;
8024
8025 return false;
8026}
8027
John McCalld5707ab2009-10-12 21:59:07 +00008028// Diagnose the common s/=/==/ typo. Note that adding parentheses
8029// will prevent this condition from triggering, which is what we want.
8030void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
8031 SourceLocation Loc;
8032
John McCall0506e4a2009-11-11 02:41:58 +00008033 unsigned diagnostic = diag::warn_condition_is_assignment;
8034
John McCalld5707ab2009-10-12 21:59:07 +00008035 if (isa<BinaryOperator>(E)) {
8036 BinaryOperator *Op = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00008037 if (Op->getOpcode() != BO_Assign)
John McCalld5707ab2009-10-12 21:59:07 +00008038 return;
8039
John McCallb0e419e2009-11-12 00:06:05 +00008040 // Greylist some idioms by putting them into a warning subcategory.
8041 if (ObjCMessageExpr *ME
8042 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
8043 Selector Sel = ME->getSelector();
8044
John McCallb0e419e2009-11-12 00:06:05 +00008045 // self = [<foo> init...]
8046 if (isSelfExpr(Op->getLHS())
8047 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
8048 diagnostic = diag::warn_condition_is_idiomatic_assignment;
8049
8050 // <foo> = [<bar> nextObject]
8051 else if (Sel.isUnarySelector() &&
8052 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
8053 diagnostic = diag::warn_condition_is_idiomatic_assignment;
8054 }
John McCall0506e4a2009-11-11 02:41:58 +00008055
John McCalld5707ab2009-10-12 21:59:07 +00008056 Loc = Op->getOperatorLoc();
8057 } else if (isa<CXXOperatorCallExpr>(E)) {
8058 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
8059 if (Op->getOperator() != OO_Equal)
8060 return;
8061
8062 Loc = Op->getOperatorLoc();
8063 } else {
8064 // Not an assignment.
8065 return;
8066 }
8067
John McCalld5707ab2009-10-12 21:59:07 +00008068 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00008069 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008070
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008071 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008072 Diag(Loc, diag::note_condition_assign_to_comparison)
Douglas Gregora771f462010-03-31 17:46:05 +00008073 << FixItHint::CreateReplacement(Loc, "==");
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008074 Diag(Loc, diag::note_condition_assign_silence)
8075 << FixItHint::CreateInsertion(Open, "(")
8076 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +00008077}
8078
8079bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
8080 DiagnoseAssignmentAsCondition(E);
8081
8082 if (!E->isTypeDependent()) {
Douglas Gregorb92a1562010-02-03 00:27:59 +00008083 DefaultFunctionArrayLvalueConversion(E);
John McCalld5707ab2009-10-12 21:59:07 +00008084
8085 QualType T = E->getType();
8086
8087 if (getLangOptions().CPlusPlus) {
8088 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
8089 return true;
8090 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
8091 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
8092 << T << E->getSourceRange();
8093 return true;
8094 }
8095 }
8096
8097 return false;
8098}
Douglas Gregore60e41a2010-05-06 17:25:47 +00008099
John McCalldadc5752010-08-24 06:29:42 +00008100ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
8101 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00008102 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00008103 return ExprError();
8104
Douglas Gregorb412e172010-07-25 18:17:45 +00008105 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00008106 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00008107
8108 return Owned(Sub);
8109}