blob: d8f3ccf8a4de5ae3332e53f93ba9f07db2b180c3 [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) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000059 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
60 // If there were any diagnostics suppressed by template argument deduction,
61 // emit them now.
62 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
63 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
64 if (Pos != SuppressedDiagnostics.end()) {
65 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
66 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
67 Diag(Suppressed[I].first, Suppressed[I].second);
68
69 // Clear out the list of suppressed diagnostics, so that we don't emit
70 // them again for this specialization. However, we don't remove this
71 // entry from the table, because we want to avoid ever emitting these
72 // diagnostics again.
73 Suppressed.clear();
74 }
75 }
76
Chris Lattner4bf74fd2009-02-15 22:43:40 +000077 // See if the decl is deprecated.
Benjamin Kramerbfac7dc2010-10-09 15:49:00 +000078 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>())
79 EmitDeprecationWarning(D, DA->getMessage(), Loc);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000080
Chris Lattnera27dd592009-10-25 17:21:40 +000081 // See if the decl is unavailable
Fariborz Jahanianc74073c2010-10-06 23:12:32 +000082 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) {
83 if (UA->getMessage().empty())
84 Diag(Loc, diag::err_unavailable) << D->getDeclName();
85 else
86 Diag(Loc, diag::err_unavailable_message)
Benjamin Kramerbfac7dc2010-10-09 15:49:00 +000087 << D->getDeclName() << UA->getMessage();
Chris Lattnera27dd592009-10-25 17:21:40 +000088 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
89 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000090
Douglas Gregor171c45a2009-02-18 21:56:37 +000091 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000092 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000093 if (FD->isDeleted()) {
94 Diag(Loc, diag::err_deleted_function_use);
95 Diag(D->getLocation(), diag::note_unavailable_here) << true;
96 return true;
97 }
Douglas Gregorde681d42009-02-24 04:26:15 +000098 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000099
Anders Carlsson73067a02010-10-22 23:37:08 +0000100 // Warn if this is used but marked unused.
101 if (D->hasAttr<UnusedAttr>())
102 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
103
Douglas Gregor171c45a2009-02-18 21:56:37 +0000104 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000105}
106
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000107/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000108/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000109/// attribute. It warns if call does not have the sentinel argument.
110///
111void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000112 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000113 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000114 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000115 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000116
117 // FIXME: In C++0x, if any of the arguments are parameter pack
118 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000119 int sentinelPos = attr->getSentinel();
120 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000121
Mike Stump87c57ac2009-05-16 07:39:55 +0000122 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
123 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000124 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000125 bool warnNotEnoughArgs = false;
126 int isMethod = 0;
127 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
128 // skip over named parameters.
129 ObjCMethodDecl::param_iterator P, E = MD->param_end();
130 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
131 if (nullPos)
132 --nullPos;
133 else
134 ++i;
135 }
136 warnNotEnoughArgs = (P != E || i >= NumArgs);
137 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000138 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000139 // skip over named parameters.
140 ObjCMethodDecl::param_iterator P, E = FD->param_end();
141 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
142 if (nullPos)
143 --nullPos;
144 else
145 ++i;
146 }
147 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000148 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000149 // block or function pointer call.
150 QualType Ty = V->getType();
151 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000152 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000153 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
154 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000155 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
156 unsigned NumArgsInProto = Proto->getNumArgs();
157 unsigned k;
158 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
159 if (nullPos)
160 --nullPos;
161 else
162 ++i;
163 }
164 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
165 }
166 if (Ty->isBlockPointerType())
167 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000168 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000169 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000170 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000171 return;
172
173 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000174 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000175 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000176 return;
177 }
178 int sentinel = i;
179 while (sentinelPos > 0 && i < NumArgs-1) {
180 --sentinelPos;
181 ++i;
182 }
183 if (sentinelPos > 0) {
184 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000185 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000186 return;
187 }
188 while (i < NumArgs-1) {
189 ++i;
190 ++sentinel;
191 }
192 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000193 if (!sentinelExpr) return;
194 if (sentinelExpr->isTypeDependent()) return;
195 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000196
197 // nullptr_t is always treated as null.
198 if (sentinelExpr->getType()->isNullPtrType()) return;
199
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000200 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000201 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
202 Expr::NPC_ValueDependentIsNull))
203 return;
204
205 // Unfortunately, __null has type 'int'.
206 if (isa<GNUNullExpr>(sentinelExpr)) return;
207
208 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
209 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000210}
211
Douglas Gregor87f95b02009-02-26 21:00:50 +0000212SourceRange Sema::getExprRange(ExprTy *E) const {
213 Expr *Ex = (Expr *)E;
214 return Ex? Ex->getSourceRange() : SourceRange();
215}
216
Chris Lattner513165e2008-07-25 21:10:04 +0000217//===----------------------------------------------------------------------===//
218// Standard Promotions and Conversions
219//===----------------------------------------------------------------------===//
220
Chris Lattner513165e2008-07-25 21:10:04 +0000221/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
222void Sema::DefaultFunctionArrayConversion(Expr *&E) {
223 QualType Ty = E->getType();
224 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
225
Chris Lattner513165e2008-07-25 21:10:04 +0000226 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000227 ImpCastExprToType(E, Context.getPointerType(Ty),
John McCalle3027922010-08-25 11:45:40 +0000228 CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000229 else if (Ty->isArrayType()) {
230 // In C90 mode, arrays only promote to pointers if the array expression is
231 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
232 // type 'array of type' is converted to an expression that has type 'pointer
233 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
234 // that has type 'array of type' ...". The relevant change is "an lvalue"
235 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000236 //
237 // C++ 4.2p1:
238 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
239 // T" can be converted to an rvalue of type "pointer to T".
240 //
241 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
242 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000243 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
John McCalle3027922010-08-25 11:45:40 +0000244 CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000245 }
Chris Lattner513165e2008-07-25 21:10:04 +0000246}
247
Douglas Gregorb92a1562010-02-03 00:27:59 +0000248void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
249 DefaultFunctionArrayConversion(E);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000250
Douglas Gregorb92a1562010-02-03 00:27:59 +0000251 QualType Ty = E->getType();
252 assert(!Ty.isNull() && "DefaultFunctionArrayLvalueConversion - missing type");
253 if (!Ty->isDependentType() && Ty.hasQualifiers() &&
254 (!getLangOptions().CPlusPlus || !Ty->isRecordType()) &&
255 E->isLvalue(Context) == Expr::LV_Valid) {
256 // C++ [conv.lval]p1:
257 // [...] If T is a non-class type, the type of the rvalue is the
258 // cv-unqualified version of T. Otherwise, the type of the
259 // rvalue is T
260 //
261 // C99 6.3.2.1p2:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000262 // If the lvalue has qualified type, the value has the unqualified
263 // version of the type of the lvalue; otherwise, the value has the
Douglas Gregorb92a1562010-02-03 00:27:59 +0000264 // type of the lvalue.
John McCalle3027922010-08-25 11:45:40 +0000265 ImpCastExprToType(E, Ty.getUnqualifiedType(), CK_NoOp);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000266 }
267}
268
269
Chris Lattner513165e2008-07-25 21:10:04 +0000270/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000271/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000272/// sometimes surpressed. For example, the array->pointer conversion doesn't
273/// apply if the array is an argument to the sizeof or address (&) operators.
274/// In these instances, this routine should *not* be called.
275Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
276 QualType Ty = Expr->getType();
277 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000278
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000279 // C99 6.3.1.1p2:
280 //
281 // The following may be used in an expression wherever an int or
282 // unsigned int may be used:
283 // - an object or expression with an integer type whose integer
284 // conversion rank is less than or equal to the rank of int
285 // and unsigned int.
286 // - A bit-field of type _Bool, int, signed int, or unsigned int.
287 //
288 // If an int can represent all values of the original type, the
289 // value is converted to an int; otherwise, it is converted to an
290 // unsigned int. These are called the integer promotions. All
291 // other types are unchanged by the integer promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000292 QualType PTy = Context.isPromotableBitField(Expr);
293 if (!PTy.isNull()) {
John McCalle3027922010-08-25 11:45:40 +0000294 ImpCastExprToType(Expr, PTy, CK_IntegralCast);
Eli Friedman629ffb92009-08-20 04:21:42 +0000295 return Expr;
296 }
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000297 if (Ty->isPromotableIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000298 QualType PT = Context.getPromotedIntegerType(Ty);
John McCalle3027922010-08-25 11:45:40 +0000299 ImpCastExprToType(Expr, PT, CK_IntegralCast);
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000300 return Expr;
Eli Friedman629ffb92009-08-20 04:21:42 +0000301 }
302
Douglas Gregorb92a1562010-02-03 00:27:59 +0000303 DefaultFunctionArrayLvalueConversion(Expr);
Chris Lattner513165e2008-07-25 21:10:04 +0000304 return Expr;
305}
306
Chris Lattner2ce500f2008-07-25 22:25:12 +0000307/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000308/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000309/// double. All other argument types are converted by UsualUnaryConversions().
310void Sema::DefaultArgumentPromotion(Expr *&Expr) {
311 QualType Ty = Expr->getType();
312 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000313
Chris Lattner2ce500f2008-07-25 22:25:12 +0000314 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000315 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
316 return ImpCastExprToType(Expr, Context.DoubleTy,
John McCalle3027922010-08-25 11:45:40 +0000317 CK_FloatingCast);
Mike Stump11289f42009-09-09 15:08:12 +0000318
Chris Lattner2ce500f2008-07-25 22:25:12 +0000319 UsualUnaryConversions(Expr);
320}
321
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000322/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
323/// will warn if the resulting type is not a POD type, and rejects ObjC
324/// interfaces passed by value. This returns true if the argument type is
325/// completely illegal.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000326bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
327 FunctionDecl *FDecl) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000328 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000329
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000330 // __builtin_va_start takes the second argument as a "varargs" argument, but
331 // it doesn't actually do anything with it. It doesn't need to be non-pod
332 // etc.
333 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
334 return false;
335
John McCall8b07ec22010-05-15 11:32:37 +0000336 if (Expr->getType()->isObjCObjectType() &&
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000337 DiagRuntimeBehavior(Expr->getLocStart(),
338 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
339 << Expr->getType() << CT))
340 return true;
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000341
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000342 if (!Expr->getType()->isPODType() &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000343 DiagRuntimeBehavior(Expr->getLocStart(),
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000344 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
345 << Expr->getType() << CT))
346 return true;
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000347
348 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000349}
350
Chris Lattner513165e2008-07-25 21:10:04 +0000351/// UsualArithmeticConversions - Performs various conversions that are common to
352/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000353/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000354/// responsible for emitting appropriate error diagnostics.
355/// FIXME: verify the conversion rules for "complex int" are consistent with
356/// GCC.
357QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
358 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000359 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000360 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000361
362 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000363
Mike Stump11289f42009-09-09 15:08:12 +0000364 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000365 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000366 QualType lhs =
367 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000368 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000369 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000370
371 // If both types are identical, no conversion is needed.
372 if (lhs == rhs)
373 return lhs;
374
375 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
376 // The caller can deal with this (e.g. pointer + int).
377 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
378 return lhs;
379
John McCalld005ac92010-11-13 08:17:45 +0000380 // Apply unary and bitfield promotions to the LHS's type.
381 QualType lhs_unpromoted = lhs;
382 if (lhs->isPromotableIntegerType())
383 lhs = Context.getPromotedIntegerType(lhs);
Eli Friedman629ffb92009-08-20 04:21:42 +0000384 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000385 if (!LHSBitfieldPromoteTy.isNull())
386 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000387 if (lhs != lhs_unpromoted && !isCompAssign)
388 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000389
John McCalld005ac92010-11-13 08:17:45 +0000390 // If both types are identical, no conversion is needed.
391 if (lhs == rhs)
392 return lhs;
393
394 // At this point, we have two different arithmetic types.
395
396 // Handle complex types first (C99 6.3.1.8p1).
397 bool LHSComplexFloat = lhs->isComplexType();
398 bool RHSComplexFloat = rhs->isComplexType();
399 if (LHSComplexFloat || RHSComplexFloat) {
400 // if we have an integer operand, the result is the complex type.
401
John McCallc5e62b42010-11-13 09:02:35 +0000402 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
403 if (rhs->isIntegerType()) {
404 QualType fp = cast<ComplexType>(lhs)->getElementType();
405 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
406 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
407 } else {
408 assert(rhs->isComplexIntegerType());
John McCalld7646252010-11-14 08:17:51 +0000409 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000410 }
John McCalld005ac92010-11-13 08:17:45 +0000411 return lhs;
412 }
413
John McCallc5e62b42010-11-13 09:02:35 +0000414 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
415 if (!isCompAssign) {
416 // int -> float -> _Complex float
417 if (lhs->isIntegerType()) {
418 QualType fp = cast<ComplexType>(rhs)->getElementType();
419 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
420 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
421 } else {
422 assert(lhs->isComplexIntegerType());
John McCalld7646252010-11-14 08:17:51 +0000423 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000424 }
425 }
John McCalld005ac92010-11-13 08:17:45 +0000426 return rhs;
427 }
428
429 // This handles complex/complex, complex/float, or float/complex.
430 // When both operands are complex, the shorter operand is converted to the
431 // type of the longer, and that is the type of the result. This corresponds
432 // to what is done when combining two real floating-point operands.
433 // The fun begins when size promotion occur across type domains.
434 // From H&S 6.3.4: When one operand is complex and the other is a real
435 // floating-point type, the less precise type is converted, within it's
436 // real or complex domain, to the precision of the other type. For example,
437 // when combining a "long double" with a "double _Complex", the
438 // "double _Complex" is promoted to "long double _Complex".
439 int order = Context.getFloatingTypeOrder(lhs, rhs);
440
441 // If both are complex, just cast to the more precise type.
442 if (LHSComplexFloat && RHSComplexFloat) {
443 if (order > 0) {
444 // _Complex float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000445 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000446 return lhs;
447
448 } else if (order < 0) {
449 // _Complex float -> _Complex double
450 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000451 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000452 return rhs;
453 }
454 return lhs;
455 }
456
457 // If just the LHS is complex, the RHS needs to be converted,
458 // and the LHS might need to be promoted.
459 if (LHSComplexFloat) {
460 if (order > 0) { // LHS is wider
461 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000462 QualType fp = cast<ComplexType>(lhs)->getElementType();
463 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
464 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000465 return lhs;
466 }
467
468 // RHS is at least as wide. Find its corresponding complex type.
469 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
470
471 // double -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000472 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000473
474 // _Complex float -> _Complex double
475 if (!isCompAssign && order < 0)
John McCallc5e62b42010-11-13 09:02:35 +0000476 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000477
478 return result;
479 }
480
481 // Just the RHS is complex, so the LHS needs to be converted
482 // and the RHS might need to be promoted.
483 assert(RHSComplexFloat);
484
485 if (order < 0) { // RHS is wider
486 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000487 if (!isCompAssign) {
488 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
489 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
490 }
John McCalld005ac92010-11-13 08:17:45 +0000491 return rhs;
492 }
493
494 // LHS is at least as wide. Find its corresponding complex type.
495 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
496
497 // double -> _Complex double
498 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000499 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000500
501 // _Complex float -> _Complex double
502 if (order > 0)
John McCallc5e62b42010-11-13 09:02:35 +0000503 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000504
505 return result;
506 }
507
508 // Now handle "real" floating types (i.e. float, double, long double).
509 bool LHSFloat = lhs->isRealFloatingType();
510 bool RHSFloat = rhs->isRealFloatingType();
511 if (LHSFloat || RHSFloat) {
512 // If we have two real floating types, convert the smaller operand
513 // to the bigger result.
514 if (LHSFloat && RHSFloat) {
515 int order = Context.getFloatingTypeOrder(lhs, rhs);
516 if (order > 0) {
517 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
518 return lhs;
519 }
520
521 assert(order < 0 && "illegal float comparison");
522 if (!isCompAssign)
523 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
524 return rhs;
525 }
526
527 // If we have an integer operand, the result is the real floating type.
528 if (LHSFloat) {
529 if (rhs->isIntegerType()) {
530 // Convert rhs to the lhs floating point type.
531 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
532 return lhs;
533 }
534
535 // Convert both sides to the appropriate complex float.
536 assert(rhs->isComplexIntegerType());
537 QualType result = Context.getComplexType(lhs);
538
539 // _Complex int -> _Complex float
John McCalld7646252010-11-14 08:17:51 +0000540 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000541
542 // float -> _Complex float
543 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000544 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000545
546 return result;
547 }
548
549 assert(RHSFloat);
550 if (lhs->isIntegerType()) {
551 // Convert lhs to the rhs floating point type.
552 if (!isCompAssign)
553 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
554 return rhs;
555 }
556
557 // Convert both sides to the appropriate complex float.
558 assert(lhs->isComplexIntegerType());
559 QualType result = Context.getComplexType(rhs);
560
561 // _Complex int -> _Complex float
562 if (!isCompAssign)
John McCalld7646252010-11-14 08:17:51 +0000563 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000564
565 // float -> _Complex float
John McCallc5e62b42010-11-13 09:02:35 +0000566 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000567
568 return result;
569 }
570
571 // Handle GCC complex int extension.
572 // FIXME: if the operands are (int, _Complex long), we currently
573 // don't promote the complex. Also, signedness?
574 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
575 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
576 if (lhsComplexInt && rhsComplexInt) {
577 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
578 rhsComplexInt->getElementType());
579 assert(order && "inequal types with equal element ordering");
580 if (order > 0) {
581 // _Complex int -> _Complex long
John McCallc5e62b42010-11-13 09:02:35 +0000582 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000583 return lhs;
584 }
585
586 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000587 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000588 return rhs;
589 } else if (lhsComplexInt) {
590 // int -> _Complex int
John McCallc5e62b42010-11-13 09:02:35 +0000591 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000592 return lhs;
593 } else if (rhsComplexInt) {
594 // int -> _Complex int
595 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000596 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000597 return rhs;
598 }
599
600 // Finally, we have two differing integer types.
601 // The rules for this case are in C99 6.3.1.8
602 int compare = Context.getIntegerTypeOrder(lhs, rhs);
603 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
604 rhsSigned = rhs->hasSignedIntegerRepresentation();
605 if (lhsSigned == rhsSigned) {
606 // Same signedness; use the higher-ranked type
607 if (compare >= 0) {
608 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
609 return lhs;
610 } else if (!isCompAssign)
611 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
612 return rhs;
613 } else if (compare != (lhsSigned ? 1 : -1)) {
614 // The unsigned type has greater than or equal rank to the
615 // signed type, so use the unsigned type
616 if (rhsSigned) {
617 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
618 return lhs;
619 } else if (!isCompAssign)
620 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
621 return rhs;
622 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
623 // The two types are different widths; if we are here, that
624 // means the signed type is larger than the unsigned type, so
625 // use the signed type.
626 if (lhsSigned) {
627 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
628 return lhs;
629 } else if (!isCompAssign)
630 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
631 return rhs;
632 } else {
633 // The signed type is higher-ranked than the unsigned type,
634 // but isn't actually any bigger (like unsigned int and long
635 // on most 32-bit systems). Use the unsigned type corresponding
636 // to the signed type.
637 QualType result =
638 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
639 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
640 if (!isCompAssign)
641 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
642 return result;
643 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000644}
645
Chris Lattner513165e2008-07-25 21:10:04 +0000646//===----------------------------------------------------------------------===//
647// Semantic Analysis for various Expression Types
648//===----------------------------------------------------------------------===//
649
650
Steve Naroff83895f72007-09-16 03:34:24 +0000651/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000652/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
653/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
654/// multiple tokens. However, the common case is that StringToks points to one
655/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000656///
John McCalldadc5752010-08-24 06:29:42 +0000657ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000658Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000659 assert(NumStringToks && "Must have at least one string!");
660
Chris Lattner8a24e582009-01-16 18:51:42 +0000661 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000662 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000663 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000664
Chris Lattner23b7eb62007-06-15 23:05:46 +0000665 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000666 for (unsigned i = 0; i != NumStringToks; ++i)
667 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000668
Chris Lattner36fc8792008-02-11 00:02:17 +0000669 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000670 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000671 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000672
673 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000674 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000675 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000676
Chris Lattner36fc8792008-02-11 00:02:17 +0000677 // Get an array type for the string, according to C99 6.4.5. This includes
678 // the nul terminator character as well as the string length for pascal
679 // strings.
680 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000681 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000682 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000683
Chris Lattner5b183d82006-11-10 05:03:26 +0000684 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000685 return Owned(StringLiteral::Create(Context, Literal.GetString(),
686 Literal.GetStringLength(),
687 Literal.AnyWide, StrTy,
688 &StringTokLocs[0],
689 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000690}
691
Chris Lattner2a9d9892008-10-20 05:16:36 +0000692/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
693/// CurBlock to VD should cause it to be snapshotted (as we do for auto
694/// variables defined outside the block) or false if this is not needed (e.g.
695/// for values inside the block or for globals).
696///
Douglas Gregor4f13beb2010-03-01 20:44:28 +0000697/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
Chris Lattner497d7b02009-04-21 22:26:47 +0000698/// up-to-date.
699///
Douglas Gregor9a28e842010-03-01 23:15:13 +0000700static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
Chris Lattner2a9d9892008-10-20 05:16:36 +0000701 ValueDecl *VD) {
702 // If the value is defined inside the block, we couldn't snapshot it even if
703 // we wanted to.
704 if (CurBlock->TheDecl == VD->getDeclContext())
705 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000706
Chris Lattner2a9d9892008-10-20 05:16:36 +0000707 // If this is an enum constant or function, it is constant, don't snapshot.
708 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
709 return false;
710
711 // If this is a reference to an extern, static, or global variable, no need to
712 // snapshot it.
713 // FIXME: What about 'const' variables in C++?
714 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000715 if (!Var->hasLocalStorage())
716 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000717
Chris Lattner497d7b02009-04-21 22:26:47 +0000718 // Blocks that have these can't be constant.
719 CurBlock->hasBlockDeclRefExprs = true;
720
721 // If we have nested blocks, the decl may be declared in an outer block (in
722 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
723 // be defined outside all of the current blocks (in which case the blocks do
724 // all get the bit). Walk the nesting chain.
Douglas Gregor9a28e842010-03-01 23:15:13 +0000725 for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
726 BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000727
Douglas Gregor9a28e842010-03-01 23:15:13 +0000728 if (!NextBlock)
729 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000730
Chris Lattner497d7b02009-04-21 22:26:47 +0000731 // If we found the defining block for the variable, don't mark the block as
732 // having a reference outside it.
733 if (NextBlock->TheDecl == VD->getDeclContext())
734 break;
Mike Stump11289f42009-09-09 15:08:12 +0000735
Chris Lattner497d7b02009-04-21 22:26:47 +0000736 // Otherwise, the DeclRef from the inner block causes the outer one to need
737 // a snapshot as well.
738 NextBlock->hasBlockDeclRefExprs = true;
739 }
Mike Stump11289f42009-09-09 15:08:12 +0000740
Chris Lattner2a9d9892008-10-20 05:16:36 +0000741 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000742}
743
Chris Lattner2a9d9892008-10-20 05:16:36 +0000744
John McCalldadc5752010-08-24 06:29:42 +0000745ExprResult
John McCall7decc9e2010-11-18 06:31:45 +0000746Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
747 SourceLocation Loc, const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000748 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +0000749 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000750}
751
752/// BuildDeclRefExpr - Build a DeclRefExpr.
John McCalldadc5752010-08-24 06:29:42 +0000753ExprResult
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000754Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +0000755 ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000756 const DeclarationNameInfo &NameInfo,
757 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000758 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000759 Diag(NameInfo.getLoc(),
Mike Stump11289f42009-09-09 15:08:12 +0000760 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000761 << D->getDeclName();
762 return ExprError();
763 }
Mike Stump11289f42009-09-09 15:08:12 +0000764
Anders Carlsson946b86d2009-06-24 00:10:43 +0000765 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Douglas Gregor15243332010-04-27 21:10:04 +0000766 if (isa<NonTypeTemplateParmDecl>(VD)) {
767 // Non-type template parameters can be referenced anywhere they are
768 // visible.
Douglas Gregora8a089b2010-07-13 18:40:04 +0000769 Ty = Ty.getNonLValueExprType(Context);
Douglas Gregor15243332010-04-27 21:10:04 +0000770 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
Anders Carlsson946b86d2009-06-24 00:10:43 +0000771 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
772 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000773 Diag(NameInfo.getLoc(),
774 diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000775 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000776 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000777 << D->getIdentifier();
778 return ExprError();
779 }
780 }
John McCall4bc41ae2010-11-18 19:01:18 +0000781
782 // This ridiculousness brought to you by 'extern void x;' and the
783 // GNU compiler collection.
784 } else if (!getLangOptions().CPlusPlus && !Ty.hasQualifiers() &&
785 Ty->isVoidType()) {
786 VK = VK_RValue;
Anders Carlsson946b86d2009-06-24 00:10:43 +0000787 }
788 }
Mike Stump11289f42009-09-09 15:08:12 +0000789
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000790 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +0000791
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000792 return Owned(DeclRefExpr::Create(Context,
793 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
794 SS? SS->getRange() : SourceRange(),
John McCall7decc9e2010-11-18 06:31:45 +0000795 D, NameInfo, Ty, VK));
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000796}
797
John McCalldadc5752010-08-24 06:29:42 +0000798ExprResult
Douglas Gregord5846a12009-04-15 06:41:24 +0000799Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
Francois Pichet783dd6e2010-11-21 06:08:52 +0000800 IndirectFieldDecl *IndirectField,
Douglas Gregord5846a12009-04-15 06:41:24 +0000801 Expr *BaseObjectExpr,
802 SourceLocation OpLoc) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000803 // Build the expression that refers to the base object, from
804 // which we will build a sequence of member references to each
805 // of the anonymous union objects and, eventually, the field we
806 // found via name lookup.
807 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000808 Qualifiers BaseQuals;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000809 VarDecl *BaseObject = IndirectField->getVarDecl();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000810 if (BaseObject) {
811 // BaseObject is an anonymous struct/union variable (and is,
812 // therefore, not part of another non-anonymous record).
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000813 MarkDeclarationReferenced(Loc, BaseObject);
John McCall7decc9e2010-11-18 06:31:45 +0000814 BaseObjectExpr =
815 new (Context) DeclRefExpr(BaseObject, BaseObject->getType(),
816 VK_LValue, Loc);
John McCall8ccfcb52009-09-24 19:53:00 +0000817 BaseQuals
818 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000819 } else if (BaseObjectExpr) {
820 // The caller provided the base object expression. Determine
821 // whether its a pointer and whether it adds any qualifiers to the
822 // anonymous struct/union fields we're looking into.
823 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000824 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000825 BaseObjectIsPointer = true;
826 ObjectType = ObjectPtr->getPointeeType();
827 }
John McCall8ccfcb52009-09-24 19:53:00 +0000828 BaseQuals
829 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000830 } else {
831 // We've found a member of an anonymous struct/union that is
832 // inside a non-anonymous struct/union, so in a well-formed
833 // program our base object expression is "this".
John McCall87fe5d52010-05-20 01:18:31 +0000834 DeclContext *DC = getFunctionLevelDeclContext();
835 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000836 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000837 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000838 = Context.getTagDeclType(
Francois Pichet783dd6e2010-11-21 06:08:52 +0000839 cast<RecordDecl>(
840 (*IndirectField->chain_begin())->getDeclContext()));
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000841 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000842 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000843 == Context.getCanonicalType(ThisType)) ||
844 IsDerivedFrom(ThisType, AnonFieldType)) {
845 // Our base object expression is "this".
Douglas Gregor4b654412009-12-24 20:23:34 +0000846 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000847 MD->getThisType(Context),
848 /*isImplicit=*/true);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000849 BaseObjectIsPointer = true;
850 }
851 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000852 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
Francois Pichet783dd6e2010-11-21 06:08:52 +0000853 << IndirectField->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000854 }
John McCall8ccfcb52009-09-24 19:53:00 +0000855 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000856 }
857
Mike Stump11289f42009-09-09 15:08:12 +0000858 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000859 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
Francois Pichet783dd6e2010-11-21 06:08:52 +0000860 << IndirectField->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000861 }
862
863 // Build the implicit member references to the field of the
864 // anonymous struct/union.
865 Expr *Result = BaseObjectExpr;
John McCall8ccfcb52009-09-24 19:53:00 +0000866 Qualifiers ResultQuals = BaseQuals;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000867
868 IndirectFieldDecl::chain_iterator FI = IndirectField->chain_begin(),
869 FEnd = IndirectField->chain_end();
870
871 // Skip the first VarDecl if present.
872 if (BaseObject)
873 FI++;
874 for (; FI != FEnd; FI++) {
875 FieldDecl *Field = cast<FieldDecl>(*FI);
John McCall7decc9e2010-11-18 06:31:45 +0000876 QualType MemberType = Field->getType();
John McCall8ccfcb52009-09-24 19:53:00 +0000877 Qualifiers MemberTypeQuals =
878 Context.getCanonicalType(MemberType).getQualifiers();
879
880 // CVR attributes from the base are picked up by members,
881 // except that 'mutable' members don't pick up 'const'.
John McCall7decc9e2010-11-18 06:31:45 +0000882 if (Field->isMutable())
John McCall8ccfcb52009-09-24 19:53:00 +0000883 ResultQuals.removeConst();
884
885 // GC attributes are never picked up by members.
886 ResultQuals.removeObjCGCAttr();
887
888 // TR 18037 does not allow fields to be declared with address spaces.
889 assert(!MemberTypeQuals.hasAddressSpace());
890
891 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
892 if (NewQuals != MemberTypeQuals)
893 MemberType = Context.getQualifiedType(MemberType, NewQuals);
894
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000895 MarkDeclarationReferenced(Loc, *FI);
John McCall16df1e52010-03-30 21:47:33 +0000896 PerformObjectMemberConversion(Result, /*FIXME:Qualifier=*/0, *FI, *FI);
Douglas Gregorc1905232009-08-26 22:36:53 +0000897 // FIXME: Might this end up being a qualified name?
Francois Pichet783dd6e2010-11-21 06:08:52 +0000898 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer,
899 cast<FieldDecl>(*FI), OpLoc,
900 MemberType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +0000901 Field->isBitField() ?
902 OK_BitField : OK_Ordinary);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000903 BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000904 ResultQuals = NewQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000905 }
906
Sebastian Redlffbcf962009-01-18 18:53:16 +0000907 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000908}
909
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000910/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +0000911/// possibly a list of template arguments.
912///
913/// If this produces template arguments, it is permitted to call
914/// DecomposeTemplateName.
915///
916/// This actually loses a lot of source location information for
917/// non-standard name kinds; we should consider preserving that in
918/// some way.
919static void DecomposeUnqualifiedId(Sema &SemaRef,
920 const UnqualifiedId &Id,
921 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000922 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +0000923 const TemplateArgumentListInfo *&TemplateArgs) {
924 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
925 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
926 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
927
928 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
929 Id.TemplateId->getTemplateArgs(),
930 Id.TemplateId->NumArgs);
931 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
932 TemplateArgsPtr.release();
933
John McCall3e56fd42010-08-23 07:28:44 +0000934 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000935 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
936 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +0000937 TemplateArgs = &Buffer;
938 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000939 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +0000940 TemplateArgs = 0;
941 }
942}
943
John McCall69f9dbc2010-02-08 19:26:07 +0000944/// Determines whether the given record is "fully-formed" at the given
945/// location, i.e. whether a qualified lookup into it is assured of
946/// getting consistent results already.
John McCall10eae182009-11-30 22:42:35 +0000947static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
John McCall69f9dbc2010-02-08 19:26:07 +0000948 if (!Record->hasDefinition())
949 return false;
950
John McCall10eae182009-11-30 22:42:35 +0000951 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
952 E = Record->bases_end(); I != E; ++I) {
953 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
954 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
955 if (!BaseRT) return false;
956
957 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall69f9dbc2010-02-08 19:26:07 +0000958 if (!BaseRecord->hasDefinition() ||
John McCall10eae182009-11-30 22:42:35 +0000959 !IsFullyFormedScope(SemaRef, BaseRecord))
960 return false;
961 }
962
963 return true;
964}
965
John McCall2d74de92009-12-01 22:10:20 +0000966/// Determines if the given class is provably not derived from all of
967/// the prospective base classes.
968static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
969 CXXRecordDecl *Record,
970 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +0000971 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +0000972 return false;
973
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000974 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +0000975 if (!RD) return false;
976 Record = cast<CXXRecordDecl>(RD);
977
John McCall2d74de92009-12-01 22:10:20 +0000978 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
979 E = Record->bases_end(); I != E; ++I) {
980 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
981 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
982 if (!BaseRT) return false;
983
984 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +0000985 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
986 return false;
987 }
988
989 return true;
990}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000991
John McCall2d74de92009-12-01 22:10:20 +0000992enum IMAKind {
993 /// The reference is definitely not an instance member access.
994 IMA_Static,
995
996 /// The reference may be an implicit instance member access.
997 IMA_Mixed,
998
999 /// The reference may be to an instance member, but it is invalid if
1000 /// so, because the context is not an instance method.
1001 IMA_Mixed_StaticContext,
1002
1003 /// The reference may be to an instance member, but it is invalid if
1004 /// so, because the context is from an unrelated class.
1005 IMA_Mixed_Unrelated,
1006
1007 /// The reference is definitely an implicit instance member access.
1008 IMA_Instance,
1009
1010 /// The reference may be to an unresolved using declaration.
1011 IMA_Unresolved,
1012
1013 /// The reference may be to an unresolved using declaration and the
1014 /// context is not an instance method.
1015 IMA_Unresolved_StaticContext,
1016
John McCall2d74de92009-12-01 22:10:20 +00001017 /// All possible referrents are instance members and the current
1018 /// context is not an instance method.
1019 IMA_Error_StaticContext,
1020
1021 /// All possible referrents are instance members of an unrelated
1022 /// class.
1023 IMA_Error_Unrelated
1024};
1025
1026/// The given lookup names class member(s) and is not being used for
1027/// an address-of-member expression. Classify the type of access
1028/// according to whether it's possible that this reference names an
1029/// instance member. This is best-effort; it is okay to
1030/// conservatively answer "yes", in which case some errors will simply
1031/// not be caught until template-instantiation.
1032static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1033 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001034 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001035
John McCall87fe5d52010-05-20 01:18:31 +00001036 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001037 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001038 (!isa<CXXMethodDecl>(DC) ||
1039 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001040
1041 if (R.isUnresolvableResult())
1042 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1043
1044 // Collect all the declaring classes of instance members we find.
1045 bool hasNonInstance = false;
1046 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1047 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001048 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001049
John McCalla8ae2222010-04-06 21:38:20 +00001050 if (D->isCXXInstanceMember()) {
John McCall2d74de92009-12-01 22:10:20 +00001051 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001052 Classes.insert(R->getCanonicalDecl());
1053 }
1054 else
1055 hasNonInstance = true;
1056 }
1057
1058 // If we didn't find any instance members, it can't be an implicit
1059 // member reference.
1060 if (Classes.empty())
1061 return IMA_Static;
1062
1063 // If the current context is not an instance method, it can't be
1064 // an implicit member reference.
1065 if (isStaticContext)
1066 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
1067
1068 // If we can prove that the current context is unrelated to all the
1069 // declaring classes, it can't be an implicit member reference (in
1070 // which case it's an error if any of those members are selected).
1071 if (IsProvablyNotDerivedFrom(SemaRef,
John McCall87fe5d52010-05-20 01:18:31 +00001072 cast<CXXMethodDecl>(DC)->getParent(),
John McCall2d74de92009-12-01 22:10:20 +00001073 Classes))
1074 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1075
1076 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1077}
1078
1079/// Diagnose a reference to a field with no object available.
1080static void DiagnoseInstanceReference(Sema &SemaRef,
1081 const CXXScopeSpec &SS,
1082 const LookupResult &R) {
1083 SourceLocation Loc = R.getNameLoc();
1084 SourceRange Range(Loc);
1085 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1086
1087 if (R.getAsSingle<FieldDecl>()) {
1088 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1089 if (MD->isStatic()) {
1090 // "invalid use of member 'x' in static member function"
1091 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
1092 << Range << R.getLookupName();
1093 return;
1094 }
1095 }
1096
1097 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
1098 << R.getLookupName() << Range;
1099 return;
1100 }
1101
1102 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001103}
1104
John McCalld681c392009-12-16 08:11:27 +00001105/// Diagnose an empty lookup.
1106///
1107/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001108bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1109 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001110 DeclarationName Name = R.getLookupName();
1111
John McCalld681c392009-12-16 08:11:27 +00001112 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001113 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001114 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1115 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001116 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001117 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001118 diagnostic_suggest = diag::err_undeclared_use_suggest;
1119 }
John McCalld681c392009-12-16 08:11:27 +00001120
Douglas Gregor598b08f2009-12-31 05:20:13 +00001121 // If the original lookup was an unqualified lookup, fake an
1122 // unqualified lookup. This is useful when (for example) the
1123 // original lookup would not have found something because it was a
1124 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001125 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001126 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001127 if (isa<CXXRecordDecl>(DC)) {
1128 LookupQualifiedName(R, DC);
1129
1130 if (!R.empty()) {
1131 // Don't give errors about ambiguities in this lookup.
1132 R.suppressDiagnostics();
1133
1134 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1135 bool isInstance = CurMethod &&
1136 CurMethod->isInstance() &&
1137 DC == CurMethod->getParent();
1138
1139 // Give a code modification hint to insert 'this->'.
1140 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1141 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001142 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001143 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1144 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001145 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001146 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001147 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001148 Diag(R.getNameLoc(), diagnostic) << Name
1149 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1150 QualType DepThisType = DepMethod->getThisType(Context);
1151 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1152 R.getNameLoc(), DepThisType, false);
1153 TemplateArgumentListInfo TList;
1154 if (ULE->hasExplicitTemplateArgs())
1155 ULE->copyTemplateArgumentsInto(TList);
1156 CXXDependentScopeMemberExpr *DepExpr =
1157 CXXDependentScopeMemberExpr::Create(
1158 Context, DepThis, DepThisType, true, SourceLocation(),
1159 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
1160 R.getLookupNameInfo(), &TList);
1161 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001162 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001163 // FIXME: we should be able to handle this case too. It is correct
1164 // to add this-> here. This is a workaround for PR7947.
1165 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001166 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001167 } else {
John McCalld681c392009-12-16 08:11:27 +00001168 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001169 }
John McCalld681c392009-12-16 08:11:27 +00001170
1171 // Do we really want to note all of these?
1172 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1173 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1174
1175 // Tell the callee to try to recover.
1176 return false;
1177 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001178
1179 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001180 }
1181 }
1182
Douglas Gregor598b08f2009-12-31 05:20:13 +00001183 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001184 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001185 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001186 if (!R.empty()) {
1187 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1188 if (SS.isEmpty())
1189 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1190 << FixItHint::CreateReplacement(R.getNameLoc(),
1191 R.getLookupName().getAsString());
1192 else
1193 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1194 << Name << computeDeclContext(SS, false) << R.getLookupName()
1195 << SS.getRange()
1196 << FixItHint::CreateReplacement(R.getNameLoc(),
1197 R.getLookupName().getAsString());
1198 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1199 Diag(ND->getLocation(), diag::note_previous_decl)
1200 << ND->getDeclName();
1201
1202 // Tell the callee to try to recover.
1203 return false;
1204 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001205
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001206 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1207 // FIXME: If we ended up with a typo for a type name or
1208 // Objective-C class name, we're in trouble because the parser
1209 // is in the wrong place to recover. Suggest the typo
1210 // correction, but don't make it a fix-it since we're not going
1211 // to recover well anyway.
1212 if (SS.isEmpty())
1213 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1214 else
1215 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1216 << Name << computeDeclContext(SS, false) << R.getLookupName()
1217 << SS.getRange();
1218
1219 // Don't try to recover; it won't work.
1220 return true;
1221 }
1222 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001223 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001224 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001225 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001226 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001227 else
Douglas Gregor25363982010-01-01 00:15:04 +00001228 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001229 << Name << computeDeclContext(SS, false) << Corrected
1230 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001231 return true;
1232 }
Douglas Gregor25363982010-01-01 00:15:04 +00001233 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001234 }
1235
1236 // Emit a special diagnostic for failed member lookups.
1237 // FIXME: computing the declaration context might fail here (?)
1238 if (!SS.isEmpty()) {
1239 Diag(R.getNameLoc(), diag::err_no_member)
1240 << Name << computeDeclContext(SS, false)
1241 << SS.getRange();
1242 return true;
1243 }
1244
John McCalld681c392009-12-16 08:11:27 +00001245 // Give up, we can't recover.
1246 Diag(R.getNameLoc(), diagnostic) << Name;
1247 return true;
1248}
1249
Douglas Gregor05fcf842010-11-02 20:36:02 +00001250ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1251 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001252 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1253 if (!IDecl)
1254 return 0;
1255 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1256 if (!ClassImpDecl)
1257 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001258 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001259 if (!property)
1260 return 0;
1261 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001262 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1263 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001264 return 0;
1265 return property;
1266}
1267
Douglas Gregor05fcf842010-11-02 20:36:02 +00001268bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1269 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1270 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1271 if (!IDecl)
1272 return false;
1273 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1274 if (!ClassImpDecl)
1275 return false;
1276 if (ObjCPropertyImplDecl *PIDecl
1277 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1278 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1279 PIDecl->getPropertyIvarDecl())
1280 return false;
1281
1282 return true;
1283}
1284
Fariborz Jahanian18722982010-07-17 00:59:30 +00001285static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001286 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001287 IdentifierInfo *II,
1288 SourceLocation NameLoc) {
1289 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001290 bool LookForIvars;
1291 if (Lookup.empty())
1292 LookForIvars = true;
1293 else if (CurMeth->isClassMethod())
1294 LookForIvars = false;
1295 else
1296 LookForIvars = (Lookup.isSingleResult() &&
1297 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1298 if (!LookForIvars)
1299 return 0;
1300
Fariborz Jahanian18722982010-07-17 00:59:30 +00001301 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1302 if (!IDecl)
1303 return 0;
1304 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001305 if (!ClassImpDecl)
1306 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001307 bool DynamicImplSeen = false;
1308 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1309 if (!property)
1310 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001311 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001312 DynamicImplSeen =
1313 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001314 // property implementation has a designated ivar. No need to assume a new
1315 // one.
1316 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1317 return 0;
1318 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001319 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001320 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1321 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001322 NameLoc,
1323 II, PropType, /*Dinfo=*/0,
1324 ObjCIvarDecl::Protected,
1325 (Expr *)0, true);
1326 ClassImpDecl->addDecl(Ivar);
1327 IDecl->makeDeclVisibleInContext(Ivar, false);
1328 property->setPropertyIvarDecl(Ivar);
1329 return Ivar;
1330 }
1331 return 0;
1332}
1333
John McCalldadc5752010-08-24 06:29:42 +00001334ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001335 CXXScopeSpec &SS,
1336 UnqualifiedId &Id,
1337 bool HasTrailingLParen,
1338 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001339 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1340 "cannot be direct & operand and have a trailing lparen");
1341
1342 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001343 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001344
John McCall10eae182009-11-30 22:42:35 +00001345 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001346
1347 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001348 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001349 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001350 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001351
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001352 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001353 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001354 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001355
John McCalle66edc12009-11-24 19:00:30 +00001356 // C++ [temp.dep.expr]p3:
1357 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001358 // -- an identifier that was declared with a dependent type,
1359 // (note: handled after lookup)
1360 // -- a template-id that is dependent,
1361 // (note: handled in BuildTemplateIdExpr)
1362 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001363 // -- a nested-name-specifier that contains a class-name that
1364 // names a dependent type.
1365 // Determine whether this is a member of an unknown specialization;
1366 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001367 bool DependentID = false;
1368 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1369 Name.getCXXNameType()->isDependentType()) {
1370 DependentID = true;
1371 } else if (SS.isSet()) {
1372 DeclContext *DC = computeDeclContext(SS, false);
1373 if (DC) {
1374 if (RequireCompleteDeclContext(SS, DC))
1375 return ExprError();
1376 // FIXME: We should be checking whether DC is the current instantiation.
1377 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
1378 DependentID = !IsFullyFormedScope(*this, RD);
1379 } else {
1380 DependentID = true;
1381 }
1382 }
1383
1384 if (DependentID) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001385 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001386 TemplateArgs);
1387 }
Fariborz Jahanian86151342010-07-22 23:33:21 +00001388 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001389 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001390 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001391 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001392 // Lookup the template name again to correctly establish the context in
1393 // which it was found. This is really unfortunate as we already did the
1394 // lookup to determine that it was a template name in the first place. If
1395 // this becomes a performance hit, we can work harder to preserve those
1396 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001397 bool MemberOfUnknownSpecialization;
1398 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1399 MemberOfUnknownSpecialization);
John McCalle66edc12009-11-24 19:00:30 +00001400 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001401 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001402 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001403
John McCalle66edc12009-11-24 19:00:30 +00001404 // If this reference is in an Objective-C method, then we need to do
1405 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001406 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001407 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001408 if (E.isInvalid())
1409 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001410
John McCalle66edc12009-11-24 19:00:30 +00001411 Expr *Ex = E.takeAs<Expr>();
1412 if (Ex) return Owned(Ex);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001413 // Synthesize ivars lazily
1414 if (getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001415 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1416 if (const ObjCPropertyDecl *Property =
1417 canSynthesizeProvisionalIvar(II)) {
1418 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1419 Diag(Property->getLocation(), diag::note_property_declare);
1420 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001421 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1422 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001423 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001424 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001425 // for further use, this must be set to false if in class method.
1426 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001427 }
Chris Lattner59a25942008-03-31 00:36:02 +00001428 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001429
John McCalle66edc12009-11-24 19:00:30 +00001430 if (R.isAmbiguous())
1431 return ExprError();
1432
Douglas Gregor171c45a2009-02-18 21:56:37 +00001433 // Determine whether this name might be a candidate for
1434 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001435 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001436
John McCalle66edc12009-11-24 19:00:30 +00001437 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001438 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001439 // in C90, extension in C99, forbidden in C++).
1440 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1441 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1442 if (D) R.addDecl(D);
1443 }
1444
1445 // If this name wasn't predeclared and if this is not a function
1446 // call, diagnose the problem.
1447 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001448 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001449 return ExprError();
1450
1451 assert(!R.empty() &&
1452 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001453
1454 // If we found an Objective-C instance variable, let
1455 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001456 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001457 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1458 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001459 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001460 assert(E.isInvalid() || E.get());
1461 return move(E);
1462 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001463 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001464 }
Mike Stump11289f42009-09-09 15:08:12 +00001465
John McCalle66edc12009-11-24 19:00:30 +00001466 // This is guaranteed from this point on.
1467 assert(!R.empty() || ADL);
1468
1469 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001470 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
Fariborz Jahanianc15dfd82010-07-29 16:53:53 +00001471 !getLangOptions().ObjCNonFragileABI2 &&
1472 Var->isFileVarDecl()) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001473 ObjCPropertyDecl *Property = canSynthesizeProvisionalIvar(II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001474 if (Property) {
1475 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1476 Diag(Property->getLocation(), diag::note_property_declare);
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001477 Diag(Var->getLocation(), diag::note_global_declared_at);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001478 }
1479 }
John McCalle66edc12009-11-24 19:00:30 +00001480 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001481 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1482 // C99 DR 316 says that, if a function type comes from a
1483 // function definition (without a prototype), that type is only
1484 // used for checking compatibility. Therefore, when referencing
1485 // the function, we pretend that we don't have the full function
1486 // type.
John McCalle66edc12009-11-24 19:00:30 +00001487 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001488 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001489
Douglas Gregor3256d042009-06-30 15:47:41 +00001490 QualType T = Func->getType();
1491 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001492 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Eli Friedmanb41ad0f2010-05-17 02:50:18 +00001493 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(),
1494 Proto->getExtInfo());
John McCall7decc9e2010-11-18 06:31:45 +00001495 // Note that functions are r-values in C.
1496 return BuildDeclRefExpr(Func, NoProtoType, VK_RValue, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001497 }
1498 }
Mike Stump11289f42009-09-09 15:08:12 +00001499
John McCall2d74de92009-12-01 22:10:20 +00001500 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001501 // C++ [class.mfct.non-static]p3:
1502 // When an id-expression that is not part of a class member access
1503 // syntax and not used to form a pointer to member is used in the
1504 // body of a non-static member function of class X, if name lookup
1505 // resolves the name in the id-expression to a non-static non-type
1506 // member of some class C, the id-expression is transformed into a
1507 // class member access expression using (*this) as the
1508 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001509 //
1510 // But we don't actually need to do this for '&' operands if R
1511 // resolved to a function or overloaded function set, because the
1512 // expression is ill-formed if it actually works out to be a
1513 // non-static member function:
1514 //
1515 // C++ [expr.ref]p4:
1516 // Otherwise, if E1.E2 refers to a non-static member function. . .
1517 // [t]he expression can be used only as the left-hand operand of a
1518 // member function call.
1519 //
1520 // There are other safeguards against such uses, but it's important
1521 // to get this right here so that we don't end up making a
1522 // spuriously dependent expression if we're inside a dependent
1523 // instance method.
John McCall57500772009-12-16 12:17:52 +00001524 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001525 bool MightBeImplicitMember;
1526 if (!isAddressOfOperand)
1527 MightBeImplicitMember = true;
1528 else if (!SS.isEmpty())
1529 MightBeImplicitMember = false;
1530 else if (R.isOverloadedResult())
1531 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001532 else if (R.isUnresolvableResult())
1533 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001534 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001535 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1536 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001537
1538 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001539 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001540 }
1541
John McCalle66edc12009-11-24 19:00:30 +00001542 if (TemplateArgs)
1543 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001544
John McCalle66edc12009-11-24 19:00:30 +00001545 return BuildDeclarationNameExpr(SS, R, ADL);
1546}
1547
John McCall57500772009-12-16 12:17:52 +00001548/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001549ExprResult
John McCall57500772009-12-16 12:17:52 +00001550Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1551 LookupResult &R,
1552 const TemplateArgumentListInfo *TemplateArgs) {
1553 switch (ClassifyImplicitMemberAccess(*this, R)) {
1554 case IMA_Instance:
1555 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1556
John McCall57500772009-12-16 12:17:52 +00001557 case IMA_Mixed:
1558 case IMA_Mixed_Unrelated:
1559 case IMA_Unresolved:
1560 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1561
1562 case IMA_Static:
1563 case IMA_Mixed_StaticContext:
1564 case IMA_Unresolved_StaticContext:
1565 if (TemplateArgs)
1566 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1567 return BuildDeclarationNameExpr(SS, R, false);
1568
1569 case IMA_Error_StaticContext:
1570 case IMA_Error_Unrelated:
1571 DiagnoseInstanceReference(*this, SS, R);
1572 return ExprError();
1573 }
1574
1575 llvm_unreachable("unexpected instance member access kind");
1576 return ExprError();
1577}
1578
John McCall10eae182009-11-30 22:42:35 +00001579/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1580/// declaration name, generally during template instantiation.
1581/// There's a large number of things which don't need to be done along
1582/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001583ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001584Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001585 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001586 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001587 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001588 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001589
John McCall0b66eb32010-05-01 00:40:08 +00001590 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001591 return ExprError();
1592
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001593 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001594 LookupQualifiedName(R, DC);
1595
1596 if (R.isAmbiguous())
1597 return ExprError();
1598
1599 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001600 Diag(NameInfo.getLoc(), diag::err_no_member)
1601 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001602 return ExprError();
1603 }
1604
1605 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1606}
1607
1608/// LookupInObjCMethod - The parser has read a name in, and Sema has
1609/// detected that we're currently inside an ObjC method. Perform some
1610/// additional lookup.
1611///
1612/// Ideally, most of this would be done by lookup, but there's
1613/// actually quite a lot of extra work involved.
1614///
1615/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001616ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001617Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001618 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001619 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001620 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001621
John McCalle66edc12009-11-24 19:00:30 +00001622 // There are two cases to handle here. 1) scoped lookup could have failed,
1623 // in which case we should look for an ivar. 2) scoped lookup could have
1624 // found a decl, but that decl is outside the current instance method (i.e.
1625 // a global variable). In these two cases, we do a lookup for an ivar with
1626 // this name, if the lookup sucedes, we replace it our current decl.
1627
1628 // If we're in a class method, we don't normally want to look for
1629 // ivars. But if we don't find anything else, and there's an
1630 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001631 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001632
1633 bool LookForIvars;
1634 if (Lookup.empty())
1635 LookForIvars = true;
1636 else if (IsClassMethod)
1637 LookForIvars = false;
1638 else
1639 LookForIvars = (Lookup.isSingleResult() &&
1640 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001641 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001642 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001643 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001644 ObjCInterfaceDecl *ClassDeclared;
1645 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1646 // Diagnose using an ivar in a class method.
1647 if (IsClassMethod)
1648 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1649 << IV->getDeclName());
1650
1651 // If we're referencing an invalid decl, just return this as a silent
1652 // error node. The error diagnostic was already emitted on the decl.
1653 if (IV->isInvalidDecl())
1654 return ExprError();
1655
1656 // Check if referencing a field with __attribute__((deprecated)).
1657 if (DiagnoseUseOfDecl(IV, Loc))
1658 return ExprError();
1659
1660 // Diagnose the use of an ivar outside of the declaring class.
1661 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1662 ClassDeclared != IFace)
1663 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1664
1665 // FIXME: This should use a new expr for a direct reference, don't
1666 // turn this into Self->ivar, just return a BareIVarExpr or something.
1667 IdentifierInfo &II = Context.Idents.get("self");
1668 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001669 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001670 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001671 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001672 SelfName, false, false);
1673 if (SelfExpr.isInvalid())
1674 return ExprError();
1675
John McCalle66edc12009-11-24 19:00:30 +00001676 MarkDeclarationReferenced(Loc, IV);
1677 return Owned(new (Context)
1678 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1679 SelfExpr.takeAs<Expr>(), true, true));
1680 }
Chris Lattner87313662010-04-12 05:10:17 +00001681 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001682 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001683 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001684 ObjCInterfaceDecl *ClassDeclared;
1685 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1686 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1687 IFace == ClassDeclared)
1688 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1689 }
1690 }
1691
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001692 if (Lookup.empty() && II && AllowBuiltinCreation) {
1693 // FIXME. Consolidate this with similar code in LookupName.
1694 if (unsigned BuiltinID = II->getBuiltinID()) {
1695 if (!(getLangOptions().CPlusPlus &&
1696 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1697 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1698 S, Lookup.isForRedeclaration(),
1699 Lookup.getNameLoc());
1700 if (D) Lookup.addDecl(D);
1701 }
1702 }
1703 }
John McCalle66edc12009-11-24 19:00:30 +00001704 // Sentinel value saying that we didn't do anything special.
1705 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001706}
John McCalld14a8642009-11-21 08:51:07 +00001707
John McCall16df1e52010-03-30 21:47:33 +00001708/// \brief Cast a base object to a member's actual type.
1709///
1710/// Logically this happens in three phases:
1711///
1712/// * First we cast from the base type to the naming class.
1713/// The naming class is the class into which we were looking
1714/// when we found the member; it's the qualifier type if a
1715/// qualifier was provided, and otherwise it's the base type.
1716///
1717/// * Next we cast from the naming class to the declaring class.
1718/// If the member we found was brought into a class's scope by
1719/// a using declaration, this is that class; otherwise it's
1720/// the class declaring the member.
1721///
1722/// * Finally we cast from the declaring class to the "true"
1723/// declaring class of the member. This conversion does not
1724/// obey access control.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001725bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001726Sema::PerformObjectMemberConversion(Expr *&From,
1727 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001728 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001729 NamedDecl *Member) {
1730 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1731 if (!RD)
1732 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001733
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001734 QualType DestRecordType;
1735 QualType DestType;
1736 QualType FromRecordType;
1737 QualType FromType = From->getType();
1738 bool PointerConversions = false;
1739 if (isa<FieldDecl>(Member)) {
1740 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001741
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001742 if (FromType->getAs<PointerType>()) {
1743 DestType = Context.getPointerType(DestRecordType);
1744 FromRecordType = FromType->getPointeeType();
1745 PointerConversions = true;
1746 } else {
1747 DestType = DestRecordType;
1748 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001749 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001750 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1751 if (Method->isStatic())
1752 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001753
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001754 DestType = Method->getThisType(Context);
1755 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001756
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001757 if (FromType->getAs<PointerType>()) {
1758 FromRecordType = FromType->getPointeeType();
1759 PointerConversions = true;
1760 } else {
1761 FromRecordType = FromType;
1762 DestType = DestRecordType;
1763 }
1764 } else {
1765 // No conversion necessary.
1766 return false;
1767 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001768
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001769 if (DestType->isDependentType() || FromType->isDependentType())
1770 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001771
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001772 // If the unqualified types are the same, no conversion is necessary.
1773 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1774 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001775
John McCall16df1e52010-03-30 21:47:33 +00001776 SourceRange FromRange = From->getSourceRange();
1777 SourceLocation FromLoc = FromRange.getBegin();
1778
John McCall2536c6d2010-08-25 10:28:54 +00001779 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001780
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001781 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001782 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001783 // class name.
1784 //
1785 // If the member was a qualified name and the qualified referred to a
1786 // specific base subobject type, we'll cast to that intermediate type
1787 // first and then to the object in which the member is declared. That allows
1788 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1789 //
1790 // class Base { public: int x; };
1791 // class Derived1 : public Base { };
1792 // class Derived2 : public Base { };
1793 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1794 //
1795 // void VeryDerived::f() {
1796 // x = 17; // error: ambiguous base subobjects
1797 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1798 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001799 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001800 QualType QType = QualType(Qualifier->getAsType(), 0);
1801 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1802 assert(QType->isRecordType() && "lookup done with non-record type");
1803
1804 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1805
1806 // In C++98, the qualifier type doesn't actually have to be a base
1807 // type of the object type, in which case we just ignore it.
1808 // Otherwise build the appropriate casts.
1809 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00001810 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001811 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001812 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001813 return true;
1814
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001815 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00001816 QType = Context.getPointerType(QType);
John McCall2536c6d2010-08-25 10:28:54 +00001817 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
1818 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00001819
1820 FromType = QType;
1821 FromRecordType = QRecordType;
1822
1823 // If the qualifier type was the same as the destination type,
1824 // we're done.
1825 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1826 return false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001827 }
1828 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001829
John McCall16df1e52010-03-30 21:47:33 +00001830 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001831
John McCall16df1e52010-03-30 21:47:33 +00001832 // If we actually found the member through a using declaration, cast
1833 // down to the using declaration's type.
1834 //
1835 // Pointer equality is fine here because only one declaration of a
1836 // class ever has member declarations.
1837 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1838 assert(isa<UsingShadowDecl>(FoundDecl));
1839 QualType URecordType = Context.getTypeDeclType(
1840 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1841
1842 // We only need to do this if the naming-class to declaring-class
1843 // conversion is non-trivial.
1844 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1845 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00001846 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001847 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001848 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001849 return true;
Alexis Huntc46382e2010-04-28 23:02:27 +00001850
John McCall16df1e52010-03-30 21:47:33 +00001851 QualType UType = URecordType;
1852 if (PointerConversions)
1853 UType = Context.getPointerType(UType);
John McCalle3027922010-08-25 11:45:40 +00001854 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001855 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00001856 FromType = UType;
1857 FromRecordType = URecordType;
1858 }
1859
1860 // We don't do access control for the conversion from the
1861 // declaring class to the true declaring class.
1862 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001863 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001864
John McCallcf142162010-08-07 06:22:56 +00001865 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00001866 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1867 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00001868 IgnoreAccess))
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001869 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001870
John McCalle3027922010-08-25 11:45:40 +00001871 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001872 VK, &BasePath);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001873 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001874}
Douglas Gregor3256d042009-06-30 15:47:41 +00001875
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001876/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001877static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001878 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00001879 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001880 const DeclarationNameInfo &MemberNameInfo,
1881 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00001882 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00001883 const TemplateArgumentListInfo *TemplateArgs = 0) {
1884 NestedNameSpecifier *Qualifier = 0;
1885 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001886 if (SS.isSet()) {
1887 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1888 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001889 }
Mike Stump11289f42009-09-09 15:08:12 +00001890
John McCalle66edc12009-11-24 19:00:30 +00001891 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001892 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00001893 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00001894}
1895
John McCall2d74de92009-12-01 22:10:20 +00001896/// Builds an implicit member access expression. The current context
1897/// is known to be an instance method, and the given unqualified lookup
1898/// set is known to contain only instance members, at least one of which
1899/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00001900ExprResult
John McCall2d74de92009-12-01 22:10:20 +00001901Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1902 LookupResult &R,
1903 const TemplateArgumentListInfo *TemplateArgs,
1904 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00001905 assert(!R.empty() && !R.isAmbiguous());
1906
John McCalld14a8642009-11-21 08:51:07 +00001907 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00001908
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001909 // We may have found a field within an anonymous union or struct
1910 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00001911 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00001912 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00001913 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1914 return BuildAnonymousStructUnionMemberReference(Loc, FD);
1915
Sebastian Redlffbcf962009-01-18 18:53:16 +00001916
John McCall2d74de92009-12-01 22:10:20 +00001917 // If this is known to be an instance access, go ahead and build a
1918 // 'this' expression now.
John McCall87fe5d52010-05-20 01:18:31 +00001919 DeclContext *DC = getFunctionLevelDeclContext();
1920 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2d74de92009-12-01 22:10:20 +00001921 Expr *This = 0; // null signifies implicit access
1922 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00001923 SourceLocation Loc = R.getNameLoc();
1924 if (SS.getRange().isValid())
1925 Loc = SS.getRange().getBegin();
1926 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001927 }
1928
John McCallb268a282010-08-23 23:25:46 +00001929 return BuildMemberReferenceExpr(This, ThisType,
John McCall2d74de92009-12-01 22:10:20 +00001930 /*OpLoc*/ SourceLocation(),
1931 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00001932 SS,
1933 /*FirstQualifierInScope*/ 0,
1934 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00001935}
1936
John McCalle66edc12009-11-24 19:00:30 +00001937bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001938 const LookupResult &R,
1939 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00001940 // Only when used directly as the postfix-expression of a call.
1941 if (!HasTrailingLParen)
1942 return false;
1943
1944 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00001945 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00001946 return false;
1947
1948 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00001949 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00001950 return false;
1951
1952 // Turn off ADL when we find certain kinds of declarations during
1953 // normal lookup:
1954 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1955 NamedDecl *D = *I;
1956
1957 // C++0x [basic.lookup.argdep]p3:
1958 // -- a declaration of a class member
1959 // Since using decls preserve this property, we check this on the
1960 // original decl.
John McCall57500772009-12-16 12:17:52 +00001961 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00001962 return false;
1963
1964 // C++0x [basic.lookup.argdep]p3:
1965 // -- a block-scope function declaration that is not a
1966 // using-declaration
1967 // NOTE: we also trigger this for function templates (in fact, we
1968 // don't check the decl type at all, since all other decl types
1969 // turn off ADL anyway).
1970 if (isa<UsingShadowDecl>(D))
1971 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1972 else if (D->getDeclContext()->isFunctionOrMethod())
1973 return false;
1974
1975 // C++0x [basic.lookup.argdep]p3:
1976 // -- a declaration that is neither a function or a function
1977 // template
1978 // And also for builtin functions.
1979 if (isa<FunctionDecl>(D)) {
1980 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1981
1982 // But also builtin functions.
1983 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1984 return false;
1985 } else if (!isa<FunctionTemplateDecl>(D))
1986 return false;
1987 }
1988
1989 return true;
1990}
1991
1992
John McCalld14a8642009-11-21 08:51:07 +00001993/// Diagnoses obvious problems with the use of the given declaration
1994/// as an expression. This is only actually called for lookups that
1995/// were not overloaded, and it doesn't promise that the declaration
1996/// will in fact be used.
1997static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1998 if (isa<TypedefDecl>(D)) {
1999 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2000 return true;
2001 }
2002
2003 if (isa<ObjCInterfaceDecl>(D)) {
2004 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2005 return true;
2006 }
2007
2008 if (isa<NamespaceDecl>(D)) {
2009 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2010 return true;
2011 }
2012
2013 return false;
2014}
2015
John McCalldadc5752010-08-24 06:29:42 +00002016ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002017Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002018 LookupResult &R,
2019 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002020 // If this is a single, fully-resolved result and we don't need ADL,
2021 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002022 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002023 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2024 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002025
2026 // We only need to check the declaration if there's exactly one
2027 // result, because in the overloaded case the results can only be
2028 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002029 if (R.isSingleResult() &&
2030 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002031 return ExprError();
2032
John McCall58cc69d2010-01-27 01:50:18 +00002033 // Otherwise, just build an unresolved lookup expression. Suppress
2034 // any lookup-related diagnostics; we'll hash these out later, when
2035 // we've picked a target.
2036 R.suppressDiagnostics();
2037
John McCalle66edc12009-11-24 19:00:30 +00002038 bool Dependent
2039 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCalld14a8642009-11-21 08:51:07 +00002040 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00002041 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00002042 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002043 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002044 NeedsADL, R.isOverloadedResult(),
2045 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002046
2047 return Owned(ULE);
2048}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002049
John McCall7decc9e2010-11-18 06:31:45 +00002050static ExprValueKind getValueKindForDecl(ASTContext &Context,
2051 const ValueDecl *D) {
John McCall4bc41ae2010-11-18 19:01:18 +00002052 // FIXME: It's not clear to me why NonTypeTemplateParmDecl is a VarDecl.
2053 if (isa<VarDecl>(D) && !isa<NonTypeTemplateParmDecl>(D)) return VK_LValue;
2054 if (isa<FieldDecl>(D)) return VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00002055 if (!Context.getLangOptions().CPlusPlus) return VK_RValue;
2056 if (isa<FunctionDecl>(D)) {
2057 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
2058 return VK_RValue;
2059 return VK_LValue;
2060 }
2061 return Expr::getValueKindForType(D->getType());
2062}
2063
John McCalld14a8642009-11-21 08:51:07 +00002064
2065/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002066ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002067Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002068 const DeclarationNameInfo &NameInfo,
2069 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002070 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002071 assert(!isa<FunctionTemplateDecl>(D) &&
2072 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002073
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002074 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002075 if (CheckDeclInExpr(*this, Loc, D))
2076 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002077
Douglas Gregore7488b92009-12-01 16:58:18 +00002078 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2079 // Specifically diagnose references to class templates that are missing
2080 // a template argument list.
2081 Diag(Loc, diag::err_template_decl_ref)
2082 << Template << SS.getRange();
2083 Diag(Template->getLocation(), diag::note_template_decl_here);
2084 return ExprError();
2085 }
2086
2087 // Make sure that we're referring to a value.
2088 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2089 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002090 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002091 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002092 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002093 return ExprError();
2094 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002095
Douglas Gregor171c45a2009-02-18 21:56:37 +00002096 // Check whether this declaration can be used. Note that we suppress
2097 // this check when we're going to perform argument-dependent lookup
2098 // on this function name, because this might not be the function
2099 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002100 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002101 return ExprError();
2102
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002103 // Only create DeclRefExpr's for valid Decl's.
2104 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002105 return ExprError();
2106
Francois Pichet783dd6e2010-11-21 06:08:52 +00002107 // Handle anonymous.
2108 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(VD))
2109 return BuildAnonymousStructUnionMemberReference(Loc, FD);
2110
John McCall7decc9e2010-11-18 06:31:45 +00002111 ExprValueKind VK = getValueKindForDecl(Context, VD);
2112
Chris Lattner2a9d9892008-10-20 05:16:36 +00002113 // If the identifier reference is inside a block, and it refers to a value
2114 // that is outside the block, create a BlockDeclRefExpr instead of a
2115 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2116 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002117 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002118 // We do not do this for things like enum constants, global variables, etc,
2119 // as they do not get snapshotted.
2120 //
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002121 if (getCurBlock() &&
Douglas Gregor9a28e842010-03-01 23:15:13 +00002122 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
Mike Stump7dafa0d2010-01-05 02:56:35 +00002123 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
2124 Diag(Loc, diag::err_ref_vm_type);
2125 Diag(D->getLocation(), diag::note_declared_at);
2126 return ExprError();
2127 }
2128
Fariborz Jahanianfa24e102010-03-16 23:39:51 +00002129 if (VD->getType()->isArrayType()) {
Mike Stump8971a862010-01-05 03:10:36 +00002130 Diag(Loc, diag::err_ref_array_type);
2131 Diag(D->getLocation(), diag::note_declared_at);
2132 return ExprError();
2133 }
2134
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00002135 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00002136 QualType ExprTy = VD->getType().getNonReferenceType();
John McCall7decc9e2010-11-18 06:31:45 +00002137
Steve Naroff1d95e5a2008-10-10 01:28:17 +00002138 // The BlocksAttr indicates the variable is bound by-reference.
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002139 bool byrefVar = (VD->getAttr<BlocksAttr>() != 0);
Fariborz Jahanian70c0b082010-07-12 17:26:57 +00002140 QualType T = VD->getType();
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002141 BlockDeclRefExpr *BDRE;
2142
2143 if (!byrefVar) {
2144 // This is to record that a 'const' was actually synthesize and added.
2145 bool constAdded = !ExprTy.isConstQualified();
2146 // Variable will be bound by-copy, make it const within the closure.
2147 ExprTy.addConst();
John McCall7decc9e2010-11-18 06:31:45 +00002148 BDRE = new (Context) BlockDeclRefExpr(VD, ExprTy, VK,
2149 Loc, false, constAdded);
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002150 }
2151 else
John McCall7decc9e2010-11-18 06:31:45 +00002152 BDRE = new (Context) BlockDeclRefExpr(VD, ExprTy, VK, Loc, true);
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002153
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002154 if (getLangOptions().CPlusPlus) {
2155 if (!T->isDependentType() && !T->isReferenceType()) {
2156 Expr *E = new (Context)
2157 DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T,
John McCall7decc9e2010-11-18 06:31:45 +00002158 VK, SourceLocation());
Fariborz Jahanian2a5deb52010-11-11 00:11:38 +00002159 if (T->getAs<RecordType>())
2160 if (!T->isUnionType()) {
2161 ExprResult Res = PerformCopyInitialization(
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002162 InitializedEntity::InitializeBlock(VD->getLocation(),
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002163 T, false),
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002164 SourceLocation(),
2165 Owned(E));
Fariborz Jahanian2a5deb52010-11-11 00:11:38 +00002166 if (!Res.isInvalid()) {
2167 Res = MaybeCreateCXXExprWithTemporaries(Res.get());
2168 Expr *Init = Res.takeAs<Expr>();
2169 BDRE->setCopyConstructorExpr(Init);
2170 }
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002171 }
Fariborz Jahanianea882cd2010-06-04 21:35:44 +00002172 }
2173 }
2174 return Owned(BDRE);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00002175 }
2176 // If this reference is not in a block or if the referenced variable is
2177 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00002178
John McCall7decc9e2010-11-18 06:31:45 +00002179 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002180 NameInfo, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00002181}
Chris Lattnere168f762006-11-10 05:29:30 +00002182
John McCalldadc5752010-08-24 06:29:42 +00002183ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlffbcf962009-01-18 18:53:16 +00002184 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002185 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002186
Chris Lattnere168f762006-11-10 05:29:30 +00002187 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002188 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002189 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2190 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2191 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002192 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002193
Chris Lattnera81a0272008-01-12 08:14:25 +00002194 // Pre-defined identifiers are of type char[x], where x is the length of the
2195 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002196
Anders Carlsson2fb08242009-09-08 18:24:21 +00002197 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002198 if (!currentDecl && getCurBlock())
2199 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002200 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002201 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002202 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002203 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002204
Anders Carlsson0b209a82009-09-11 01:22:35 +00002205 QualType ResTy;
2206 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2207 ResTy = Context.DependentTy;
2208 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002209 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002210
Anders Carlsson0b209a82009-09-11 01:22:35 +00002211 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002212 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002213 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2214 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002215 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002216}
2217
John McCalldadc5752010-08-24 06:29:42 +00002218ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002219 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002220 bool Invalid = false;
2221 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2222 if (Invalid)
2223 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002224
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002225 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2226 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002227 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002228 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002229
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002230 QualType Ty;
2231 if (!getLangOptions().CPlusPlus)
2232 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2233 else if (Literal.isWide())
2234 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002235 else if (Literal.isMultiChar())
2236 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002237 else
2238 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002239
Sebastian Redl20614a72009-01-20 22:23:13 +00002240 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2241 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002242 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002243}
2244
John McCalldadc5752010-08-24 06:29:42 +00002245ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002246 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002247 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2248 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002249 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002250 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002251 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002252 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002253 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002254
Chris Lattner23b7eb62007-06-15 23:05:46 +00002255 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002256 // Add padding so that NumericLiteralParser can overread by one character.
2257 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002258 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002259
Chris Lattner67ca9252007-05-21 01:08:44 +00002260 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002261 bool Invalid = false;
2262 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2263 if (Invalid)
2264 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002265
Mike Stump11289f42009-09-09 15:08:12 +00002266 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002267 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002268 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002269 return ExprError();
2270
Chris Lattner1c20a172007-08-26 03:42:43 +00002271 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002272
Chris Lattner1c20a172007-08-26 03:42:43 +00002273 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002274 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002275 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002276 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002277 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002278 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002279 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002280 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002281
2282 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2283
John McCall53b93a02009-12-24 09:08:04 +00002284 using llvm::APFloat;
2285 APFloat Val(Format);
2286
2287 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002288
2289 // Overflow is always an error, but underflow is only an error if
2290 // we underflowed to zero (APFloat reports denormals as underflow).
2291 if ((result & APFloat::opOverflow) ||
2292 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002293 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002294 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002295 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002296 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002297 APFloat::getLargest(Format).toString(buffer);
2298 } else {
John McCall62abc942010-02-26 23:35:57 +00002299 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002300 APFloat::getSmallest(Format).toString(buffer);
2301 }
2302
2303 Diag(Tok.getLocation(), diagnostic)
2304 << Ty
2305 << llvm::StringRef(buffer.data(), buffer.size());
2306 }
2307
2308 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002309 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002310
Chris Lattner1c20a172007-08-26 03:42:43 +00002311 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002312 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002313 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002314 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002315
Neil Boothac582c52007-08-29 22:00:19 +00002316 // long long is a C99 feature.
2317 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002318 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002319 Diag(Tok.getLocation(), diag::ext_longlong);
2320
Chris Lattner67ca9252007-05-21 01:08:44 +00002321 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002322 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002323
Chris Lattner67ca9252007-05-21 01:08:44 +00002324 if (Literal.GetIntegerValue(ResultVal)) {
2325 // If this value didn't fit into uintmax_t, warn and force to ull.
2326 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002327 Ty = Context.UnsignedLongLongTy;
2328 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002329 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002330 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002331 // If this value fits into a ULL, try to figure out what else it fits into
2332 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002333
Chris Lattner67ca9252007-05-21 01:08:44 +00002334 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2335 // be an unsigned int.
2336 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2337
2338 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002339 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002340 if (!Literal.isLong && !Literal.isLongLong) {
2341 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002342 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002343
Chris Lattner67ca9252007-05-21 01:08:44 +00002344 // Does it fit in a unsigned int?
2345 if (ResultVal.isIntN(IntSize)) {
2346 // Does it fit in a signed int?
2347 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002348 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002349 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002350 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002351 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002352 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002353 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002354
Chris Lattner67ca9252007-05-21 01:08:44 +00002355 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002356 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002357 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002358
Chris Lattner67ca9252007-05-21 01:08:44 +00002359 // Does it fit in a unsigned long?
2360 if (ResultVal.isIntN(LongSize)) {
2361 // Does it fit in a signed long?
2362 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002363 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002364 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002365 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002366 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002367 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002368 }
2369
Chris Lattner67ca9252007-05-21 01:08:44 +00002370 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002371 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002372 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002373
Chris Lattner67ca9252007-05-21 01:08:44 +00002374 // Does it fit in a unsigned long long?
2375 if (ResultVal.isIntN(LongLongSize)) {
2376 // Does it fit in a signed long long?
2377 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002378 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002379 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002380 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002381 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002382 }
2383 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002384
Chris Lattner67ca9252007-05-21 01:08:44 +00002385 // If we still couldn't decide a type, we probably have something that
2386 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002387 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002388 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002389 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002390 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002391 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002392
Chris Lattner55258cf2008-05-09 05:59:00 +00002393 if (ResultVal.getBitWidth() != Width)
2394 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002395 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002396 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002397 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002398
Chris Lattner1c20a172007-08-26 03:42:43 +00002399 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2400 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002401 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002402 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002403
2404 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002405}
2406
John McCalldadc5752010-08-24 06:29:42 +00002407ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002408 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002409 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002410 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002411}
2412
Steve Naroff71b59a92007-06-04 22:22:31 +00002413/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002414/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002415bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00002416 SourceLocation OpLoc,
John McCall36e7fe32010-10-12 00:20:44 +00002417 SourceRange ExprRange,
Sebastian Redl6f282892008-11-11 17:56:53 +00002418 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002419 if (exprType->isDependentType())
2420 return false;
2421
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002422 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2423 // the result is the size of the referenced type."
2424 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2425 // result shall be the alignment of the referenced type."
2426 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2427 exprType = Ref->getPointeeType();
2428
Steve Naroff043d45d2007-05-15 02:32:35 +00002429 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002430 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002431 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002432 if (isSizeof)
2433 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2434 return false;
2435 }
Mike Stump11289f42009-09-09 15:08:12 +00002436
Chris Lattner62975a72009-04-24 00:30:45 +00002437 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002438 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002439 Diag(OpLoc, diag::ext_sizeof_void_type)
2440 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002441 return false;
2442 }
Mike Stump11289f42009-09-09 15:08:12 +00002443
Chris Lattner62975a72009-04-24 00:30:45 +00002444 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002445 PDiag(diag::err_sizeof_alignof_incomplete_type)
2446 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002447 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002448
Chris Lattner62975a72009-04-24 00:30:45 +00002449 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002450 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002451 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002452 << exprType << isSizeof << ExprRange;
2453 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002454 }
Mike Stump11289f42009-09-09 15:08:12 +00002455
Chris Lattner62975a72009-04-24 00:30:45 +00002456 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002457}
2458
John McCall36e7fe32010-10-12 00:20:44 +00002459static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2460 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002461 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002462
Mike Stump11289f42009-09-09 15:08:12 +00002463 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002464 if (isa<DeclRefExpr>(E))
2465 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002466
2467 // Cannot know anything else if the expression is dependent.
2468 if (E->isTypeDependent())
2469 return false;
2470
Douglas Gregor71235ec2009-05-02 02:18:30 +00002471 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00002472 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00002473 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002474 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002475
2476 // Alignment of a field access is always okay, so long as it isn't a
2477 // bit-field.
2478 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002479 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002480 return false;
2481
John McCall36e7fe32010-10-12 00:20:44 +00002482 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
Chris Lattner8dff0172009-01-24 20:17:12 +00002483}
2484
Douglas Gregor0950e412009-03-13 21:01:28 +00002485/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002486ExprResult
John McCallbcd03502009-12-07 02:54:59 +00002487Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00002488 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002489 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002490 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002491 return ExprError();
2492
John McCallbcd03502009-12-07 02:54:59 +00002493 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002494
Douglas Gregor0950e412009-03-13 21:01:28 +00002495 if (!T->isDependentType() &&
2496 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2497 return ExprError();
2498
2499 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00002500 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00002501 Context.getSizeType(), OpLoc,
2502 R.getEnd()));
2503}
2504
2505/// \brief Build a sizeof or alignof expression given an expression
2506/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002507ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00002508Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002509 bool isSizeOf, SourceRange R) {
2510 // Verify that the operand is valid.
2511 bool isInvalid = false;
2512 if (E->isTypeDependent()) {
2513 // Delay type-checking for type-dependent expressions.
2514 } else if (!isSizeOf) {
John McCall36e7fe32010-10-12 00:20:44 +00002515 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002516 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002517 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2518 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00002519 } else if (E->getType()->isPlaceholderType()) {
2520 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2521 if (PE.isInvalid()) return ExprError();
2522 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00002523 } else {
2524 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2525 }
2526
2527 if (isInvalid)
2528 return ExprError();
2529
2530 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2531 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2532 Context.getSizeType(), OpLoc,
2533 R.getEnd()));
2534}
2535
Sebastian Redl6f282892008-11-11 17:56:53 +00002536/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2537/// the same for @c alignof and @c __alignof
2538/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002539ExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00002540Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2541 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002542 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002543 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002544
Sebastian Redl6f282892008-11-11 17:56:53 +00002545 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002546 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002547 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
John McCallbcd03502009-12-07 02:54:59 +00002548 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002549 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002550
Douglas Gregor0950e412009-03-13 21:01:28 +00002551 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00002552 ExprResult Result
Douglas Gregor0950e412009-03-13 21:01:28 +00002553 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2554
Douglas Gregor0950e412009-03-13 21:01:28 +00002555 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002556}
2557
John McCall4bc41ae2010-11-18 19:01:18 +00002558static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2559 bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002560 if (V->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002561 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002562
Chris Lattnere267f5d2007-08-26 05:39:26 +00002563 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00002564 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002565 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002566
Chris Lattnere267f5d2007-08-26 05:39:26 +00002567 // Otherwise they pass through real integer and floating point types here.
2568 if (V->getType()->isArithmeticType())
2569 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002570
John McCall36226622010-10-12 02:09:17 +00002571 // Test for placeholders.
John McCall4bc41ae2010-11-18 19:01:18 +00002572 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall36226622010-10-12 02:09:17 +00002573 if (PR.isInvalid()) return QualType();
2574 if (PR.take() != V) {
2575 V = PR.take();
John McCall4bc41ae2010-11-18 19:01:18 +00002576 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002577 }
2578
Chris Lattnere267f5d2007-08-26 05:39:26 +00002579 // Reject anything else.
John McCall4bc41ae2010-11-18 19:01:18 +00002580 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002581 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002582 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002583}
2584
2585
Chris Lattnere168f762006-11-10 05:29:30 +00002586
John McCalldadc5752010-08-24 06:29:42 +00002587ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002588Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002589 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002590 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002591 switch (Kind) {
2592 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002593 case tok::plusplus: Opc = UO_PostInc; break;
2594 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002595 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002596
John McCallb268a282010-08-23 23:25:46 +00002597 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002598}
2599
John McCall4bc41ae2010-11-18 19:01:18 +00002600/// Expressions of certain arbitrary types are forbidden by C from
2601/// having l-value type. These are:
2602/// - 'void', but not qualified void
2603/// - function types
2604///
2605/// The exact rule here is C99 6.3.2.1:
2606/// An lvalue is an expression with an object type or an incomplete
2607/// type other than void.
2608static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2609 return ((T->isVoidType() && !T.hasQualifiers()) ||
2610 T->isFunctionType());
2611}
2612
John McCalldadc5752010-08-24 06:29:42 +00002613ExprResult
John McCallb268a282010-08-23 23:25:46 +00002614Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2615 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002616 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002617 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002618 if (Result.isInvalid()) return ExprError();
2619 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002620
John McCallb268a282010-08-23 23:25:46 +00002621 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002622
Douglas Gregor40412ac2008-11-19 17:17:41 +00002623 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002624 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002625 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002626 Context.DependentTy,
2627 VK_LValue, OK_Ordinary,
2628 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002629 }
2630
Mike Stump11289f42009-09-09 15:08:12 +00002631 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002632 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002633 LHSExp->getType()->isEnumeralType() ||
2634 RHSExp->getType()->isRecordType() ||
2635 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002636 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002637 }
2638
John McCallb268a282010-08-23 23:25:46 +00002639 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002640}
2641
2642
John McCalldadc5752010-08-24 06:29:42 +00002643ExprResult
John McCallb268a282010-08-23 23:25:46 +00002644Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2645 Expr *Idx, SourceLocation RLoc) {
2646 Expr *LHSExp = Base;
2647 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002648
Chris Lattner36d572b2007-07-16 00:14:47 +00002649 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002650 if (!LHSExp->getType()->getAs<VectorType>())
2651 DefaultFunctionArrayLvalueConversion(LHSExp);
2652 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002653
Chris Lattner36d572b2007-07-16 00:14:47 +00002654 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00002655 ExprValueKind VK = VK_LValue;
2656 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00002657
Steve Naroffc1aadb12007-03-28 21:49:40 +00002658 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002659 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002660 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002661 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002662 Expr *BaseExpr, *IndexExpr;
2663 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002664 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2665 BaseExpr = LHSExp;
2666 IndexExpr = RHSExp;
2667 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002668 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002669 BaseExpr = LHSExp;
2670 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002671 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002672 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002673 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002674 BaseExpr = RHSExp;
2675 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002676 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002677 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002678 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002679 BaseExpr = LHSExp;
2680 IndexExpr = RHSExp;
2681 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002682 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002683 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002684 // Handle the uncommon case of "123[Ptr]".
2685 BaseExpr = RHSExp;
2686 IndexExpr = LHSExp;
2687 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00002688 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00002689 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00002690 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00002691 VK = LHSExp->getValueKind();
2692 if (VK != VK_RValue)
2693 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00002694
Chris Lattner36d572b2007-07-16 00:14:47 +00002695 // FIXME: need to deal with const...
2696 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002697 } else if (LHSTy->isArrayType()) {
2698 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00002699 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00002700 // wasn't promoted because of the C90 rule that doesn't
2701 // allow promoting non-lvalue arrays. Warn, then
2702 // force the promotion here.
2703 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2704 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002705 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCalle3027922010-08-25 11:45:40 +00002706 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002707 LHSTy = LHSExp->getType();
2708
2709 BaseExpr = LHSExp;
2710 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002711 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002712 } else if (RHSTy->isArrayType()) {
2713 // Same as previous, except for 123[f().a] case
2714 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2715 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002716 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCalle3027922010-08-25 11:45:40 +00002717 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002718 RHSTy = RHSExp->getType();
2719
2720 BaseExpr = RHSExp;
2721 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002722 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00002723 } else {
Chris Lattner003af242009-04-25 22:50:55 +00002724 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2725 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002726 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00002727 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002728 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00002729 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2730 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00002731
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002732 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00002733 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2734 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00002735 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2736
Douglas Gregorac1fb652009-03-24 19:52:54 +00002737 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00002738 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2739 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00002740 // incomplete types are not object types.
2741 if (ResultType->isFunctionType()) {
2742 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2743 << ResultType << BaseExpr->getSourceRange();
2744 return ExprError();
2745 }
Mike Stump11289f42009-09-09 15:08:12 +00002746
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00002747 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
2748 // GNU extension: subscripting on pointer to void
2749 Diag(LLoc, diag::ext_gnu_void_ptr)
2750 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00002751
2752 // C forbids expressions of unqualified void type from being l-values.
2753 // See IsCForbiddenLValueType.
2754 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00002755 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00002756 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00002757 PDiag(diag::err_subscript_incomplete_type)
2758 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00002759 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002760
Chris Lattner62975a72009-04-24 00:30:45 +00002761 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00002762 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00002763 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2764 << ResultType << BaseExpr->getSourceRange();
2765 return ExprError();
2766 }
Mike Stump11289f42009-09-09 15:08:12 +00002767
John McCall4bc41ae2010-11-18 19:01:18 +00002768 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
2769 !IsCForbiddenLValueType(Context, ResultType));
2770
Mike Stump4e1f26a2009-02-19 03:04:26 +00002771 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002772 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00002773}
2774
John McCall4bc41ae2010-11-18 19:01:18 +00002775/// Check an ext-vector component access expression.
2776///
2777/// VK should be set in advance to the value kind of the base
2778/// expression.
2779static QualType
2780CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
2781 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00002782 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00002783 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2784 // see FIXME there.
2785 //
2786 // FIXME: This logic can be greatly simplified by splitting it along
2787 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00002788 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00002789
Steve Narofff8fd09e2007-07-27 22:15:19 +00002790 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002791 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002792
Mike Stump4e1f26a2009-02-19 03:04:26 +00002793 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00002794 // special names that indicate a subset of exactly half the elements are
2795 // to be selected.
2796 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002797
Nate Begemanbb70bf62009-01-18 01:47:54 +00002798 // This flag determines whether or not CompName has an 's' char prefix,
2799 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00002800 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00002801
John McCall4bc41ae2010-11-18 19:01:18 +00002802 bool HasRepeated = false;
2803 bool HasIndex[16] = {};
2804
2805 int Idx;
2806
Nate Begemanf322eab2008-05-09 06:41:27 +00002807 // Check that we've found one of the special components, or that the component
2808 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002809 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00002810 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2811 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00002812 } else if (!HexSwizzle &&
2813 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
2814 do {
2815 if (HasIndex[Idx]) HasRepeated = true;
2816 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00002817 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00002818 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
2819 } else {
2820 if (HexSwizzle) compStr++;
2821 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
2822 if (HasIndex[Idx]) HasRepeated = true;
2823 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00002824 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00002825 }
Chris Lattner7e152db2007-08-02 22:33:49 +00002826 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002827
Mike Stump4e1f26a2009-02-19 03:04:26 +00002828 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002829 // We didn't get to the end of the string. This means the component names
2830 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00002831 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00002832 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002833 return QualType();
2834 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002835
Nate Begemanbb70bf62009-01-18 01:47:54 +00002836 // Ensure no component accessor exceeds the width of the vector type it
2837 // operates on.
2838 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002839 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002840
2841 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002842 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002843
2844 while (*compStr) {
2845 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00002846 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00002847 << baseType << SourceRange(CompLoc);
2848 return QualType();
2849 }
2850 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002851 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002852
Steve Narofff8fd09e2007-07-27 22:15:19 +00002853 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002854 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002855 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002856 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002857 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00002858 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002859 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002860 if (HexSwizzle)
2861 CompSize--;
2862
Steve Narofff8fd09e2007-07-27 22:15:19 +00002863 if (CompSize == 1)
2864 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002865
John McCall4bc41ae2010-11-18 19:01:18 +00002866 if (HasRepeated) VK = VK_RValue;
2867
2868 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002869 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00002870 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00002871 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
2872 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
2873 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00002874 }
2875 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00002876}
2877
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002878static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00002879 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002880 const Selector &Sel,
2881 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002882 if (Member)
2883 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
2884 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002885 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002886 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00002887
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002888 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2889 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002890 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
2891 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002892 return D;
2893 }
2894 return 0;
2895}
2896
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002897static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
2898 IdentifierInfo *Member,
2899 const Selector &Sel,
2900 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002901 // Check protocols on qualified interfaces.
2902 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00002903 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002904 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002905 if (Member)
2906 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
2907 GDecl = PD;
2908 break;
2909 }
2910 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002911 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002912 GDecl = OMD;
2913 break;
2914 }
2915 }
2916 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002917 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002918 E = QIdTy->qual_end(); I != E; ++I) {
2919 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002920 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
2921 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002922 if (GDecl)
2923 return GDecl;
2924 }
2925 }
2926 return GDecl;
2927}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00002928
John McCalldadc5752010-08-24 06:29:42 +00002929ExprResult
John McCallb268a282010-08-23 23:25:46 +00002930Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00002931 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002932 const CXXScopeSpec &SS,
2933 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002934 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00002935 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00002936 // Even in dependent contexts, try to diagnose base expressions with
2937 // obviously wrong types, e.g.:
2938 //
2939 // T* t;
2940 // t.f;
2941 //
2942 // In Obj-C++, however, the above expression is valid, since it could be
2943 // accessing the 'f' property if T is an Obj-C interface. The extra check
2944 // allows this, while still reporting an error if T is a struct pointer.
2945 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00002946 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00002947 if (PT && (!getLangOptions().ObjC1 ||
2948 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00002949 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002950 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00002951 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00002952 return ExprError();
2953 }
2954 }
2955
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002956 assert(BaseType->isDependentType() ||
2957 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00002958 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00002959
2960 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2961 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00002962 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00002963 IsArrow, OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002964 SS.getScopeRep(),
John McCall10eae182009-11-30 22:42:35 +00002965 SS.getRange(),
2966 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002967 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00002968}
2969
2970/// We know that the given qualified member reference points only to
2971/// declarations which do not belong to the static type of the base
2972/// expression. Diagnose the problem.
2973static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2974 Expr *BaseExpr,
2975 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002976 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002977 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00002978 // If this is an implicit member access, use a different set of
2979 // diagnostics.
2980 if (!BaseExpr)
2981 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00002982
John McCall1e67dd62010-04-27 01:43:38 +00002983 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
2984 << SS.getRange() << R.getRepresentativeDecl() << BaseType;
John McCall10eae182009-11-30 22:42:35 +00002985}
2986
2987// Check whether the declarations we found through a nested-name
2988// specifier in a member expression are actually members of the base
2989// type. The restriction here is:
2990//
2991// C++ [expr.ref]p2:
2992// ... In these cases, the id-expression shall name a
2993// member of the class or of one of its base classes.
2994//
2995// So it's perfectly legitimate for the nested-name specifier to name
2996// an unrelated class, and for us to find an overload set including
2997// decls from classes which are not superclasses, as long as the decl
2998// we actually pick through overload resolution is from a superclass.
2999bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3000 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003001 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003002 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003003 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3004 if (!BaseRT) {
3005 // We can't check this yet because the base type is still
3006 // dependent.
3007 assert(BaseType->isDependentType());
3008 return false;
3009 }
3010 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003011
3012 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003013 // If this is an implicit member reference and we find a
3014 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003015 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003016 return false;
John McCall10eae182009-11-30 22:42:35 +00003017
John McCall2d74de92009-12-01 22:10:20 +00003018 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003019 DeclContext *DC = (*I)->getDeclContext();
3020 while (DC->isTransparentContext())
3021 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003022
Douglas Gregora9c3e822010-07-28 22:27:52 +00003023 if (!DC->isRecord())
3024 continue;
3025
John McCall2d74de92009-12-01 22:10:20 +00003026 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003027 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003028
3029 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3030 return false;
3031 }
3032
John McCallcd4b4772009-12-02 03:53:29 +00003033 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00003034 return true;
3035}
3036
3037static bool
3038LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3039 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003040 SourceLocation OpLoc, CXXScopeSpec &SS,
3041 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003042 RecordDecl *RDecl = RTy->getDecl();
3043 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003044 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003045 << BaseRange))
3046 return true;
3047
John McCalle9cccd82010-06-16 08:42:20 +00003048 if (HasTemplateArgs) {
3049 // LookupTemplateName doesn't expect these both to exist simultaneously.
3050 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3051
3052 bool MOUS;
3053 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3054 return false;
3055 }
3056
John McCall2d74de92009-12-01 22:10:20 +00003057 DeclContext *DC = RDecl;
3058 if (SS.isSet()) {
3059 // If the member name was a qualified-id, look into the
3060 // nested-name-specifier.
3061 DC = SemaRef.computeDeclContext(SS, false);
3062
John McCall0b66eb32010-05-01 00:40:08 +00003063 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003064 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3065 << SS.getRange() << DC;
3066 return true;
3067 }
3068
John McCall2d74de92009-12-01 22:10:20 +00003069 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003070
John McCall2d74de92009-12-01 22:10:20 +00003071 if (!isa<TypeDecl>(DC)) {
3072 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3073 << DC << SS.getRange();
3074 return true;
John McCall10eae182009-11-30 22:42:35 +00003075 }
3076 }
3077
John McCall2d74de92009-12-01 22:10:20 +00003078 // The record definition is complete, now look up the member.
3079 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003080
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003081 if (!R.empty())
3082 return false;
3083
3084 // We didn't find anything with the given name, so try to correct
3085 // for typos.
3086 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003087 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003088 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003089 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3090 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3091 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003092 << FixItHint::CreateReplacement(R.getNameLoc(),
3093 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003094 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3095 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3096 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003097 return false;
3098 } else {
3099 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003100 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003101 }
3102
John McCall10eae182009-11-30 22:42:35 +00003103 return false;
3104}
3105
John McCalldadc5752010-08-24 06:29:42 +00003106ExprResult
John McCallb268a282010-08-23 23:25:46 +00003107Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003108 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003109 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003110 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003111 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003112 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003113 if (BaseType->isDependentType() ||
3114 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003115 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003116 IsArrow, OpLoc,
3117 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003118 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003119
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003120 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003121
John McCall2d74de92009-12-01 22:10:20 +00003122 // Implicit member accesses.
3123 if (!Base) {
3124 QualType RecordTy = BaseType;
3125 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3126 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3127 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003128 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003129 return ExprError();
3130
3131 // Explicit member accesses.
3132 } else {
John McCalldadc5752010-08-24 06:29:42 +00003133 ExprResult Result =
John McCall2d74de92009-12-01 22:10:20 +00003134 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003135 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003136
3137 if (Result.isInvalid()) {
3138 Owned(Base);
3139 return ExprError();
3140 }
3141
3142 if (Result.get())
3143 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003144
3145 // LookupMemberExpr can modify Base, and thus change BaseType
3146 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003147 }
3148
John McCallb268a282010-08-23 23:25:46 +00003149 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003150 OpLoc, IsArrow, SS, FirstQualifierInScope,
3151 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003152}
3153
John McCalldadc5752010-08-24 06:29:42 +00003154ExprResult
John McCallb268a282010-08-23 23:25:46 +00003155Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003156 SourceLocation OpLoc, bool IsArrow,
3157 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003158 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003159 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003160 const TemplateArgumentListInfo *TemplateArgs,
3161 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003162 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003163 if (IsArrow) {
3164 assert(BaseType->isPointerType());
3165 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3166 }
John McCalla8ae2222010-04-06 21:38:20 +00003167 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003168
John McCallb268a282010-08-23 23:25:46 +00003169 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003170 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3171 DeclarationName MemberName = MemberNameInfo.getName();
3172 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003173
3174 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003175 return ExprError();
3176
John McCall10eae182009-11-30 22:42:35 +00003177 if (R.empty()) {
3178 // Rederive where we looked up.
3179 DeclContext *DC = (SS.isSet()
3180 ? computeDeclContext(SS, false)
3181 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003182
John McCall10eae182009-11-30 22:42:35 +00003183 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003184 << MemberName << DC
3185 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003186 return ExprError();
3187 }
3188
John McCall38836f02010-01-15 08:34:02 +00003189 // Diagnose lookups that find only declarations from a non-base
3190 // type. This is possible for either qualified lookups (which may
3191 // have been qualified with an unrelated type) or implicit member
3192 // expressions (which were found with unqualified lookup and thus
3193 // may have come from an enclosing scope). Note that it's okay for
3194 // lookup to find declarations from a non-base type as long as those
3195 // aren't the ones picked by overload resolution.
3196 if ((SS.isSet() || !BaseExpr ||
3197 (isa<CXXThisExpr>(BaseExpr) &&
3198 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003199 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003200 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003201 return ExprError();
3202
3203 // Construct an unresolved result if we in fact got an unresolved
3204 // result.
3205 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall2d74de92009-12-01 22:10:20 +00003206 bool Dependent =
John McCall71739032009-12-19 02:05:44 +00003207 BaseExprType->isDependentType() ||
John McCall2d74de92009-12-01 22:10:20 +00003208 R.isUnresolvableResult() ||
John McCall1acbbb52010-02-02 06:20:04 +00003209 OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003210
John McCall58cc69d2010-01-27 01:50:18 +00003211 // Suppress any lookup-related diagnostics; we'll do these when we
3212 // pick a member.
3213 R.suppressDiagnostics();
3214
John McCall10eae182009-11-30 22:42:35 +00003215 UnresolvedMemberExpr *MemExpr
3216 = UnresolvedMemberExpr::Create(Context, Dependent,
3217 R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003218 BaseExpr, BaseExprType,
3219 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003220 Qualifier, SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003221 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003222 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003223
3224 return Owned(MemExpr);
3225 }
3226
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003227 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003228 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003229 NamedDecl *MemberDecl = R.getFoundDecl();
3230
3231 // FIXME: diagnose the presence of template arguments now.
3232
3233 // If the decl being referenced had an error, return an error for this
3234 // sub-expr without emitting another error, in order to avoid cascading
3235 // error cases.
3236 if (MemberDecl->isInvalidDecl())
3237 return ExprError();
3238
John McCall2d74de92009-12-01 22:10:20 +00003239 // Handle the implicit-member-access case.
3240 if (!BaseExpr) {
3241 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003242 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003243 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003244
Douglas Gregorb15af892010-01-07 23:12:05 +00003245 SourceLocation Loc = R.getNameLoc();
3246 if (SS.getRange().isValid())
3247 Loc = SS.getRange().getBegin();
3248 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003249 }
3250
John McCall10eae182009-11-30 22:42:35 +00003251 bool ShouldCheckUse = true;
3252 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3253 // Don't diagnose the use of a virtual member function unless it's
3254 // explicitly qualified.
3255 if (MD->isVirtual() && !SS.isSet())
3256 ShouldCheckUse = false;
3257 }
3258
3259 // Check the use of this member.
3260 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3261 Owned(BaseExpr);
3262 return ExprError();
3263 }
3264
3265 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
John McCall10eae182009-11-30 22:42:35 +00003266
John McCall7decc9e2010-11-18 06:31:45 +00003267 // x.a is an l-value if 'a' has a reference type. Otherwise:
3268 // x.a is an l-value/x-value/pr-value if the base is (and note
John McCall4bc41ae2010-11-18 19:01:18 +00003269 // that *x is always an l-value), except that if the base isn't
3270 // an ordinary object then we must have an rvalue.
3271 ExprValueKind VK = VK_LValue;
3272 ExprObjectKind OK = OK_Ordinary;
3273 if (!IsArrow) {
3274 if (BaseExpr->getObjectKind() == OK_Ordinary)
3275 VK = BaseExpr->getValueKind();
3276 else
3277 VK = VK_RValue;
3278 }
3279 if (VK != VK_RValue && FD->isBitField())
3280 OK = OK_BitField;
John McCall7decc9e2010-11-18 06:31:45 +00003281
John McCall10eae182009-11-30 22:42:35 +00003282 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
3283 QualType MemberType = FD->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003284 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
John McCall10eae182009-11-30 22:42:35 +00003285 MemberType = Ref->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +00003286 VK = VK_LValue;
3287 } else {
John McCall10eae182009-11-30 22:42:35 +00003288 Qualifiers BaseQuals = BaseType.getQualifiers();
3289 BaseQuals.removeObjCGCAttr();
3290 if (FD->isMutable()) BaseQuals.removeConst();
3291
3292 Qualifiers MemberQuals
3293 = Context.getCanonicalType(MemberType).getQualifiers();
3294
3295 Qualifiers Combined = BaseQuals + MemberQuals;
3296 if (Combined != MemberQuals)
3297 MemberType = Context.getQualifiedType(MemberType, Combined);
3298 }
3299
3300 MarkDeclarationReferenced(MemberLoc, FD);
John McCall16df1e52010-03-30 21:47:33 +00003301 if (PerformObjectMemberConversion(BaseExpr, Qualifier, FoundDecl, FD))
John McCall10eae182009-11-30 22:42:35 +00003302 return ExprError();
3303 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003304 FD, FoundDecl, MemberNameInfo,
John McCall4bc41ae2010-11-18 19:01:18 +00003305 MemberType, VK, OK));
John McCall10eae182009-11-30 22:42:35 +00003306 }
3307
Francois Pichet783dd6e2010-11-21 06:08:52 +00003308 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3309 // We may have found a field within an anonymous union or struct
3310 // (C++ [class.union]).
3311 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
3312 BaseExpr, OpLoc);
3313
John McCall10eae182009-11-30 22:42:35 +00003314 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3315 MarkDeclarationReferenced(MemberLoc, Var);
3316 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003317 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003318 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003319 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003320 }
3321
John McCall7decc9e2010-11-18 06:31:45 +00003322 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall10eae182009-11-30 22:42:35 +00003323 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3324 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003325 MemberFn, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003326 MemberFn->getType(),
3327 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3328 OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003329 }
John McCall7decc9e2010-11-18 06:31:45 +00003330 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003331
3332 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3333 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3334 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003335 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003336 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003337 }
3338
3339 Owned(BaseExpr);
3340
Douglas Gregor861eb802010-04-25 20:55:08 +00003341 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003342 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003343 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003344 << MemberName << BaseType << int(IsArrow);
3345 else
3346 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3347 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003348
Douglas Gregor861eb802010-04-25 20:55:08 +00003349 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3350 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003351 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003352 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003353}
3354
3355/// Look up the given member of the given non-type-dependent
3356/// expression. This can return in one of two ways:
3357/// * If it returns a sentinel null-but-valid result, the caller will
3358/// assume that lookup was performed and the results written into
3359/// the provided structure. It will take over from there.
3360/// * Otherwise, the returned expression will be produced in place of
3361/// an ordinary member expression.
3362///
3363/// The ObjCImpDecl bit is a gross hack that will need to be properly
3364/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00003365ExprResult
John McCall10eae182009-11-30 22:42:35 +00003366Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00003367 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003368 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00003369 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003370 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00003371
Steve Naroffeaaae462007-12-16 21:42:28 +00003372 // Perform default conversions.
3373 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003374
Steve Naroff185616f2007-07-26 03:11:44 +00003375 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00003376 assert(!BaseType->isDependentType());
3377
3378 DeclarationName MemberName = R.getLookupName();
3379 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00003380
3381 // If the user is trying to apply -> or . to a function pointer
John McCall10eae182009-11-30 22:42:35 +00003382 // type, it's probably because they forgot parentheses to call that
Douglas Gregord82ae382009-11-06 06:30:47 +00003383 // function. Suggest the addition of those parentheses, build the
3384 // call, and continue on.
3385 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
3386 if (const FunctionProtoType *Fun
3387 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
3388 QualType ResultTy = Fun->getResultType();
3389 if (Fun->getNumArgs() == 0 &&
John McCall10eae182009-11-30 22:42:35 +00003390 ((!IsArrow && ResultTy->isRecordType()) ||
3391 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregord82ae382009-11-06 06:30:47 +00003392 ResultTy->getAs<PointerType>()->getPointeeType()
3393 ->isRecordType()))) {
3394 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
Nick Lewyckyc60d6e72010-10-15 21:43:24 +00003395 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
Douglas Gregord82ae382009-11-06 06:30:47 +00003396 << QualType(Fun, 0)
Douglas Gregora771f462010-03-31 17:46:05 +00003397 << FixItHint::CreateInsertion(Loc, "()");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003398
John McCalldadc5752010-08-24 06:29:42 +00003399 ExprResult NewBase
Douglas Gregorce5aa332010-09-09 16:33:13 +00003400 = ActOnCallExpr(0, BaseExpr, Loc, MultiExprArg(*this, 0, 0), Loc);
Douglas Gregor143d3672010-06-21 22:46:46 +00003401 BaseExpr = 0;
Douglas Gregord82ae382009-11-06 06:30:47 +00003402 if (NewBase.isInvalid())
John McCall10eae182009-11-30 22:42:35 +00003403 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003404
Douglas Gregord82ae382009-11-06 06:30:47 +00003405 BaseExpr = NewBase.takeAs<Expr>();
3406 DefaultFunctionArrayConversion(BaseExpr);
3407 BaseType = BaseExpr->getType();
3408 }
3409 }
3410 }
3411
David Chisnall9f57c292009-08-17 16:35:33 +00003412 // If this is an Objective-C pseudo-builtin and a definition is provided then
3413 // use that.
3414 if (BaseType->isObjCIdType()) {
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00003415 if (IsArrow) {
3416 // Handle the following exceptional case PObj->isa.
3417 if (const ObjCObjectPointerType *OPT =
3418 BaseType->getAs<ObjCObjectPointerType>()) {
John McCall8b07ec22010-05-15 11:32:37 +00003419 if (OPT->getObjectType()->isObjCId() &&
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00003420 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00003421 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
3422 Context.getObjCClassType()));
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00003423 }
3424 }
David Chisnall9f57c292009-08-17 16:35:33 +00003425 // We have an 'id' type. Rather than fall through, we check if this
3426 // is a reference to 'isa'.
3427 if (BaseType != Context.ObjCIdRedefinitionType) {
3428 BaseType = Context.ObjCIdRedefinitionType;
John McCalle3027922010-08-25 11:45:40 +00003429 ImpCastExprToType(BaseExpr, BaseType, CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003430 }
David Chisnall9f57c292009-08-17 16:35:33 +00003431 }
John McCall10eae182009-11-30 22:42:35 +00003432
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00003433 // If this is an Objective-C pseudo-builtin and a definition is provided then
3434 // use that.
3435 if (Context.isObjCSelType(BaseType)) {
3436 // We have an 'SEL' type. Rather than fall through, we check if this
3437 // is a reference to 'sel_id'.
3438 if (BaseType != Context.ObjCSelRedefinitionType) {
3439 BaseType = Context.ObjCSelRedefinitionType;
John McCalle3027922010-08-25 11:45:40 +00003440 ImpCastExprToType(BaseExpr, BaseType, CK_BitCast);
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00003441 }
3442 }
John McCall10eae182009-11-30 22:42:35 +00003443
Steve Naroff185616f2007-07-26 03:11:44 +00003444 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003445
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003446 // Handle properties on ObjC 'Class' types.
John McCall10eae182009-11-30 22:42:35 +00003447 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003448 // Also must look for a getter name which uses property syntax.
3449 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3450 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3451 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3452 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3453 ObjCMethodDecl *Getter;
3454 // FIXME: need to also look locally in the implementation.
3455 if ((Getter = IFace->lookupClassMethod(Sel))) {
3456 // Check the use of this method.
3457 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3458 return ExprError();
3459 }
3460 // If we found a getter then this may be a valid dot-reference, we
3461 // will look for the matching setter, in case it is needed.
3462 Selector SetterSel =
3463 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3464 PP.getSelectorTable(), Member);
3465 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3466 if (!Setter) {
3467 // If this reference is in an @implementation, also check for 'private'
3468 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00003469 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003470 }
3471 // Look through local category implementations associated with the class.
3472 if (!Setter)
3473 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003474
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003475 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3476 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003477
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003478 if (Getter || Setter) {
3479 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003480
John McCall4bc41ae2010-11-18 19:01:18 +00003481 ExprValueKind VK = VK_LValue;
3482 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00003483 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00003484 if (!getLangOptions().CPlusPlus &&
3485 IsCForbiddenLValueType(Context, PType))
3486 VK = VK_RValue;
3487 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003488 // Get the expression type from Setter's incoming parameter.
3489 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00003490 }
3491 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3492
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003493 // FIXME: we must check that the setter has property type.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003494 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
John McCall4bc41ae2010-11-18 19:01:18 +00003495 PType, VK, OK,
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003496 Setter, MemberLoc, BaseExpr));
3497 }
3498 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3499 << MemberName << BaseType);
3500 }
3501 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003502
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003503 if (BaseType->isObjCClassType() &&
3504 BaseType != Context.ObjCClassRedefinitionType) {
3505 BaseType = Context.ObjCClassRedefinitionType;
John McCalle3027922010-08-25 11:45:40 +00003506 ImpCastExprToType(BaseExpr, BaseType, CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003507 }
Mike Stump11289f42009-09-09 15:08:12 +00003508
John McCall10eae182009-11-30 22:42:35 +00003509 if (IsArrow) {
3510 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00003511 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00003512 else if (BaseType->isObjCObjectPointerType())
3513 ;
John McCalla928c652009-12-07 22:46:59 +00003514 else if (BaseType->isRecordType()) {
3515 // Recover from arrow accesses to records, e.g.:
3516 // struct MyRecord foo;
3517 // foo->bar
3518 // This is actually well-formed in C++ if MyRecord has an
3519 // overloaded operator->, but that should have been dealt with
3520 // by now.
3521 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3522 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003523 << FixItHint::CreateReplacement(OpLoc, ".");
John McCalla928c652009-12-07 22:46:59 +00003524 IsArrow = false;
3525 } else {
John McCall10eae182009-11-30 22:42:35 +00003526 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3527 << BaseType << BaseExpr->getSourceRange();
3528 return ExprError();
Anders Carlsson524d5a42009-05-16 20:31:20 +00003529 }
John McCalla928c652009-12-07 22:46:59 +00003530 } else {
3531 // Recover from dot accesses to pointers, e.g.:
3532 // type *foo;
3533 // foo.bar
3534 // This is actually well-formed in two cases:
3535 // - 'type' is an Objective C type
3536 // - 'bar' is a pseudo-destructor name which happens to refer to
3537 // the appropriate pointer type
3538 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3539 const PointerType *PT = BaseType->getAs<PointerType>();
3540 if (PT && PT->getPointeeType()->isRecordType()) {
3541 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3542 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003543 << FixItHint::CreateReplacement(OpLoc, "->");
John McCalla928c652009-12-07 22:46:59 +00003544 BaseType = PT->getPointeeType();
3545 IsArrow = true;
3546 }
3547 }
John McCall10eae182009-11-30 22:42:35 +00003548 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003549
John McCall8b07ec22010-05-15 11:32:37 +00003550 // Handle field access to simple records.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003551 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCall2d74de92009-12-01 22:10:20 +00003552 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
John McCalle9cccd82010-06-16 08:42:20 +00003553 RTy, OpLoc, SS, HasTemplateArgs))
Douglas Gregordd430f72009-01-19 19:26:10 +00003554 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003555 return Owned((Expr*) 0);
Chris Lattnerb63a7452008-07-21 04:28:12 +00003556 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003557
Chris Lattnerdc420f42008-07-21 04:59:05 +00003558 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
3559 // (*Obj).ivar.
John McCall10eae182009-11-30 22:42:35 +00003560 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00003561 (!IsArrow && BaseType->isObjCObjectType())) {
John McCall9dd450b2009-09-21 23:43:11 +00003562 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
John McCall8b07ec22010-05-15 11:32:37 +00003563 ObjCInterfaceDecl *IDecl =
3564 OPT ? OPT->getInterfaceDecl()
3565 : BaseType->getAs<ObjCObjectType>()->getInterface();
3566 if (IDecl) {
Anders Carlssonf571c112009-08-26 18:25:21 +00003567 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3568
Steve Naroffa057ba92009-07-16 00:25:06 +00003569 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00003570 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00003571
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003572 if (!IV) {
3573 // Attempt to correct for typos in ivar names.
3574 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3575 LookupMemberName);
Douglas Gregord507d772010-10-20 03:06:34 +00003576 if (CorrectTypo(Res, 0, 0, IDecl, false,
3577 IsArrow? CTC_ObjCIvarLookup
3578 : CTC_ObjCPropertyLookup) &&
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003579 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003580 Diag(R.getNameLoc(),
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003581 diag::err_typecheck_member_reference_ivar_suggest)
3582 << IDecl->getDeclName() << MemberName << IV->getDeclName()
Douglas Gregora771f462010-03-31 17:46:05 +00003583 << FixItHint::CreateReplacement(R.getNameLoc(),
3584 IV->getNameAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003585 Diag(IV->getLocation(), diag::note_previous_decl)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003586 << IV->getDeclName();
Douglas Gregorc048c522010-06-29 19:27:42 +00003587 } else {
3588 Res.clear();
3589 Res.setLookupName(Member);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003590 }
3591 }
3592
Steve Naroffa057ba92009-07-16 00:25:06 +00003593 if (IV) {
3594 // If the decl being referenced had an error, return an error for this
3595 // sub-expr without emitting another error, in order to avoid cascading
3596 // error cases.
3597 if (IV->isInvalidDecl())
3598 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003599
Steve Naroffa057ba92009-07-16 00:25:06 +00003600 // Check whether we can reference this field.
3601 if (DiagnoseUseOfDecl(IV, MemberLoc))
3602 return ExprError();
3603 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3604 IV->getAccessControl() != ObjCIvarDecl::Package) {
3605 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3606 if (ObjCMethodDecl *MD = getCurMethodDecl())
3607 ClassOfMethodDecl = MD->getClassInterface();
3608 else if (ObjCImpDecl && getCurFunctionDecl()) {
3609 // Case of a c-function declared inside an objc implementation.
3610 // FIXME: For a c-style function nested inside an objc implementation
3611 // class, there is no implementation context available, so we pass
3612 // down the context as argument to this routine. Ideally, this context
3613 // need be passed down in the AST node and somehow calculated from the
3614 // AST for a function decl.
Mike Stump11289f42009-09-09 15:08:12 +00003615 if (ObjCImplementationDecl *IMPD =
John McCall48871652010-08-21 09:40:31 +00003616 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
Steve Naroffa057ba92009-07-16 00:25:06 +00003617 ClassOfMethodDecl = IMPD->getClassInterface();
3618 else if (ObjCCategoryImplDecl* CatImplClass =
John McCall48871652010-08-21 09:40:31 +00003619 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
Steve Naroffa057ba92009-07-16 00:25:06 +00003620 ClassOfMethodDecl = CatImplClass->getClassInterface();
3621 }
Mike Stump11289f42009-09-09 15:08:12 +00003622
3623 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3624 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00003625 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00003626 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00003627 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00003628 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3629 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00003630 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00003631 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00003632 }
Steve Naroffa057ba92009-07-16 00:25:06 +00003633
3634 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3635 MemberLoc, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00003636 IsArrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00003637 }
Steve Naroffa057ba92009-07-16 00:25:06 +00003638 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00003639 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00003640 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00003641 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00003642 }
Steve Naroff1329fa02009-07-15 18:40:39 +00003643 // Handle properties on 'id' and qualified "id".
John McCall10eae182009-11-30 22:42:35 +00003644 if (!IsArrow && (BaseType->isObjCIdType() ||
3645 BaseType->isObjCQualifiedIdType())) {
John McCall9dd450b2009-09-21 23:43:11 +00003646 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00003647 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003648
Steve Naroff7cae42b2009-07-10 23:34:53 +00003649 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00003650 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003651 if (Decl *PMDecl = FindGetterSetterNameDecl(QIdTy, Member, Sel,
3652 Context)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003653 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3654 // Check the use of this declaration
3655 if (DiagnoseUseOfDecl(PD, MemberLoc))
3656 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003657
Steve Naroff7cae42b2009-07-10 23:34:53 +00003658 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00003659 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00003660 MemberLoc,
3661 BaseExpr));
Steve Naroff7cae42b2009-07-10 23:34:53 +00003662 }
3663 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3664 // Check the use of this method.
3665 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3666 return ExprError();
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003667 Selector SetterSel =
3668 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3669 PP.getSelectorTable(), Member);
3670 ObjCMethodDecl *SMD = 0;
3671 if (Decl *SDecl = FindGetterSetterNameDecl(QIdTy, /*Property id*/0,
3672 SetterSel, Context))
3673 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3674 QualType PType = OMD->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00003675
3676 ExprValueKind VK = VK_LValue;
3677 if (!getLangOptions().CPlusPlus &&
3678 IsCForbiddenLValueType(Context, PType))
3679 VK = VK_RValue;
3680 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3681
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003682 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(OMD, PType,
John McCall4bc41ae2010-11-18 19:01:18 +00003683 VK, OK, SMD,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003684 MemberLoc,
3685 BaseExpr));
Steve Naroff7cae42b2009-07-10 23:34:53 +00003686 }
3687 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003688
Steve Naroff7cae42b2009-07-10 23:34:53 +00003689 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00003690 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003691 }
Alexis Huntc46382e2010-04-28 23:02:27 +00003692
Chris Lattnerdc420f42008-07-21 04:59:05 +00003693 // Handle Objective-C property access, which is "Obj.property" where Obj is a
3694 // pointer to a (potentially qualified) interface type.
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00003695 if (!IsArrow)
3696 if (const ObjCObjectPointerType *OPT =
3697 BaseType->getAsObjCInterfacePointerType())
Fariborz Jahanian681c0752010-10-14 16:04:05 +00003698 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3699 SourceLocation(), QualType(), false);
Mike Stump11289f42009-09-09 15:08:12 +00003700
Steve Naroffe87026a2009-07-24 17:54:45 +00003701 // Handle the following exceptional case (*Obj).isa.
John McCall10eae182009-11-30 22:42:35 +00003702 if (!IsArrow &&
John McCall8b07ec22010-05-15 11:32:37 +00003703 BaseType->isObjCObjectType() &&
3704 BaseType->getAs<ObjCObjectType>()->isObjCId() &&
Anders Carlssonf571c112009-08-26 18:25:21 +00003705 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00003706 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00003707 Context.getObjCClassType()));
Steve Naroffe87026a2009-07-24 17:54:45 +00003708
Chris Lattnerb63a7452008-07-21 04:28:12 +00003709 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003710 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00003711 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall4bc41ae2010-11-18 19:01:18 +00003712 ExprValueKind VK = BaseExpr->getValueKind();
3713 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3714 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00003715 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003716 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00003717
3718 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3719 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003720 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003721
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003722 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3723 << BaseType << BaseExpr->getSourceRange();
3724
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003725 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00003726}
3727
John McCall10eae182009-11-30 22:42:35 +00003728/// The main callback when the parser finds something like
3729/// expression . [nested-name-specifier] identifier
3730/// expression -> [nested-name-specifier] identifier
3731/// where 'identifier' encompasses a fairly broad spectrum of
3732/// possibilities, including destructor and operator references.
3733///
3734/// \param OpKind either tok::arrow or tok::period
3735/// \param HasTrailingLParen whether the next token is '(', which
3736/// is used to diagnose mis-uses of special members that can
3737/// only be called
3738/// \param ObjCImpDecl the current ObjC @implementation decl;
3739/// this is an ugly hack around the fact that ObjC @implementations
3740/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00003741ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall10eae182009-11-30 22:42:35 +00003742 SourceLocation OpLoc,
3743 tok::TokenKind OpKind,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003744 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003745 UnqualifiedId &Id,
John McCall48871652010-08-21 09:40:31 +00003746 Decl *ObjCImpDecl,
John McCall10eae182009-11-30 22:42:35 +00003747 bool HasTrailingLParen) {
3748 if (SS.isSet() && SS.isInvalid())
3749 return ExprError();
3750
3751 TemplateArgumentListInfo TemplateArgsBuffer;
3752
3753 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003754 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00003755 const TemplateArgumentListInfo *TemplateArgs;
3756 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003757 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003758
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003759 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00003760 bool IsArrow = (OpKind == tok::arrow);
3761
3762 NamedDecl *FirstQualifierInScope
3763 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3764 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3765
3766 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003767 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003768 if (Result.isInvalid()) return ExprError();
3769 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00003770
Douglas Gregor41f90302010-04-12 20:54:26 +00003771 if (Base->getType()->isDependentType() || Name.isDependentName() ||
3772 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00003773 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00003774 IsArrow, OpLoc,
3775 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003776 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003777 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003778 LookupResult R(*this, NameInfo, LookupMemberName);
John McCalle9cccd82010-06-16 08:42:20 +00003779 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3780 SS, ObjCImpDecl, TemplateArgs != 0);
Alexis Huntc46382e2010-04-28 23:02:27 +00003781
John McCalle9cccd82010-06-16 08:42:20 +00003782 if (Result.isInvalid()) {
3783 Owned(Base);
3784 return ExprError();
3785 }
John McCall10eae182009-11-30 22:42:35 +00003786
John McCalle9cccd82010-06-16 08:42:20 +00003787 if (Result.get()) {
3788 // The only way a reference to a destructor can be used is to
3789 // immediately call it, which falls into this case. If the
3790 // next token is not a '(', produce a diagnostic and build the
3791 // call now.
3792 if (!HasTrailingLParen &&
3793 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00003794 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00003795
John McCalle9cccd82010-06-16 08:42:20 +00003796 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00003797 }
3798
John McCallb268a282010-08-23 23:25:46 +00003799 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00003800 OpLoc, IsArrow, SS, FirstQualifierInScope,
3801 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003802 }
3803
3804 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003805}
3806
John McCalldadc5752010-08-24 06:29:42 +00003807ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Anders Carlsson355933d2009-08-25 03:49:14 +00003808 FunctionDecl *FD,
3809 ParmVarDecl *Param) {
3810 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003811 Diag(CallLoc,
Anders Carlsson355933d2009-08-25 03:49:14 +00003812 diag::err_use_of_default_argument_to_function_declared_later) <<
3813 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003814 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-08-25 03:49:14 +00003815 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003816 return ExprError();
3817 }
3818
3819 if (Param->hasUninstantiatedDefaultArg()) {
3820 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003821
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003822 // Instantiate the expression.
3823 MultiLevelTemplateArgumentList ArgList
3824 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003825
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003826 std::pair<const TemplateArgument *, unsigned> Innermost
3827 = ArgList.getInnermost();
3828 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3829 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003830
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003831 ExprResult Result = SubstExpr(UninstExpr, ArgList);
3832 if (Result.isInvalid())
3833 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003834
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003835 // Check the expression as an initializer for the parameter.
3836 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003837 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003838 InitializationKind Kind
3839 = InitializationKind::CreateCopy(Param->getLocation(),
3840 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3841 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003842
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003843 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3844 Result = InitSeq.Perform(*this, Entity, Kind,
3845 MultiExprArg(*this, &ResultE, 1));
3846 if (Result.isInvalid())
3847 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003848
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003849 // Build the default argument expression.
3850 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3851 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003852 }
3853
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003854 // If the default expression creates temporaries, we need to
3855 // push them to the current stack of expression temporaries so they'll
3856 // be properly destroyed.
3857 // FIXME: We should really be rebuilding the default argument with new
3858 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003859 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3860 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3861 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3862 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3863 ExprTemporaries.push_back(Temporary);
3864 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003865
3866 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003867 // Just mark all of the declarations in this potentially-evaluated expression
3868 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003869 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003870 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003871}
3872
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003873/// ConvertArgumentsForCall - Converts the arguments specified in
3874/// Args/NumArgs to the parameter types of the function FDecl with
3875/// function prototype Proto. Call is the call expression itself, and
3876/// Fn is the function expression. For a C++ member function, this
3877/// routine does not attempt to convert the object argument. Returns
3878/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003879bool
3880Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003881 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003882 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003883 Expr **Args, unsigned NumArgs,
3884 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003885 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003886 // assignment, to the types of the corresponding parameter, ...
3887 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003888 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003889
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003890 // If too few arguments are available (and we don't have default
3891 // arguments for the remaining parameters), don't make the call.
3892 if (NumArgs < NumArgsInProto) {
3893 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3894 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003895 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003896 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003897 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003898 }
3899
3900 // If too many are passed and not variadic, error on the extras and drop
3901 // them.
3902 if (NumArgs > NumArgsInProto) {
3903 if (!Proto->isVariadic()) {
3904 Diag(Args[NumArgsInProto]->getLocStart(),
3905 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003906 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003907 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003908 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3909 Args[NumArgs-1]->getLocEnd());
3910 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003911 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003912 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003913 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003914 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003915 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003916 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003917 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3918 if (Fn->getType()->isBlockPointerType())
3919 CallType = VariadicBlock; // Block
3920 else if (isa<MemberExpr>(Fn))
3921 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003922 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003923 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003924 if (Invalid)
3925 return true;
3926 unsigned TotalNumArgs = AllArgs.size();
3927 for (unsigned i = 0; i < TotalNumArgs; ++i)
3928 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003929
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003930 return false;
3931}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003932
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003933bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3934 FunctionDecl *FDecl,
3935 const FunctionProtoType *Proto,
3936 unsigned FirstProtoArg,
3937 Expr **Args, unsigned NumArgs,
3938 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003939 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003940 unsigned NumArgsInProto = Proto->getNumArgs();
3941 unsigned NumArgsToCheck = NumArgs;
3942 bool Invalid = false;
3943 if (NumArgs != NumArgsInProto)
3944 // Use default arguments for missing arguments
3945 NumArgsToCheck = NumArgsInProto;
3946 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003947 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003948 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003949 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003950
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003951 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003952 if (ArgIx < NumArgs) {
3953 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003954
Eli Friedman3164fb12009-03-22 22:00:50 +00003955 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3956 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003957 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003958 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003959 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003960
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003961 // Pass the argument
3962 ParmVarDecl *Param = 0;
3963 if (FDecl && i < FDecl->getNumParams())
3964 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003965
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003966 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003967 Param? InitializedEntity::InitializeParameter(Context, Param)
3968 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00003969 ExprResult ArgE = PerformCopyInitialization(Entity,
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003970 SourceLocation(),
3971 Owned(Arg));
3972 if (ArgE.isInvalid())
3973 return true;
3974
3975 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003976 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003977 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003978
John McCalldadc5752010-08-24 06:29:42 +00003979 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003980 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003981 if (ArgExpr.isInvalid())
3982 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003983
Anders Carlsson355933d2009-08-25 03:49:14 +00003984 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003985 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003986 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003987 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003988
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003989 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003990 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003991 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00003992 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003993 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00003994 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003995 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003996 }
3997 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003998 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003999}
4000
Steve Naroff83895f72007-09-16 03:34:24 +00004001/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004002/// This provides the location of the left/right parens and a list of comma
4003/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004004ExprResult
John McCallb268a282010-08-23 23:25:46 +00004005Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004006 MultiExprArg args, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004007 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004008
4009 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004010 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004011 if (Result.isInvalid()) return ExprError();
4012 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004013
John McCallb268a282010-08-23 23:25:46 +00004014 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004015
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004016 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004017 // If this is a pseudo-destructor expression, build the call immediately.
4018 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4019 if (NumArgs > 0) {
4020 // Pseudo-destructor calls should not have any arguments.
4021 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004022 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004023 SourceRange(Args[0]->getLocStart(),
4024 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004025
Douglas Gregorad8a3362009-09-04 17:36:40 +00004026 NumArgs = 0;
4027 }
Mike Stump11289f42009-09-09 15:08:12 +00004028
Douglas Gregorad8a3362009-09-04 17:36:40 +00004029 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004030 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004031 }
Mike Stump11289f42009-09-09 15:08:12 +00004032
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004033 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004034 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004035 // FIXME: Will need to cache the results of name lookup (including ADL) in
4036 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004037 bool Dependent = false;
4038 if (Fn->isTypeDependent())
4039 Dependent = true;
4040 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4041 Dependent = true;
4042
4043 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004044 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00004045 Context.DependentTy, VK_RValue,
4046 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004047
4048 // Determine whether this is a call to an object (C++ [over.call.object]).
4049 if (Fn->getType()->isRecordType())
4050 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004051 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004052
John McCall10eae182009-11-30 22:42:35 +00004053 Expr *NakedFn = Fn->IgnoreParens();
4054
4055 // Determine whether this is a call to an unresolved member function.
4056 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4057 // If lookup was unresolved but not dependent (i.e. didn't find
4058 // an unresolved using declaration), it has to be an overloaded
4059 // function set, which means it must contain either multiple
4060 // declarations (all methods or method templates) or a single
4061 // method template.
4062 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00004063 isa<FunctionTemplateDecl>(
4064 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00004065 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00004066
John McCall2d74de92009-12-01 22:10:20 +00004067 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004068 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004069 }
4070
Douglas Gregore254f902009-02-04 00:32:51 +00004071 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00004072 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004073 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00004074 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00004075 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004076 RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004077 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004078
Anders Carlsson61914b52009-10-03 17:40:22 +00004079 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00004080 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCalle3027922010-08-25 11:45:40 +00004081 if (BO->getOpcode() == BO_PtrMemD ||
4082 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00004083 if (const FunctionProtoType *FPT
4084 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004085 QualType ResultTy = FPT->getCallResultType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004086 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004087
John McCallb268a282010-08-23 23:25:46 +00004088 CXXMemberCallExpr *TheCall
4089 = new (Context) CXXMemberCallExpr(Context, BO, Args,
John McCall7decc9e2010-11-18 06:31:45 +00004090 NumArgs, ResultTy, VK,
John McCallb268a282010-08-23 23:25:46 +00004091 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004092
4093 if (CheckCallReturnType(FPT->getResultType(),
4094 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00004095 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004096 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00004097
John McCallb268a282010-08-23 23:25:46 +00004098 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004099 RParenLoc))
4100 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00004101
John McCallb268a282010-08-23 23:25:46 +00004102 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004103 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004104 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004105 diag::err_typecheck_call_not_function)
4106 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00004107 }
4108 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004109 }
4110
Douglas Gregore254f902009-02-04 00:32:51 +00004111 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004112 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00004113 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004114
Eli Friedmane14b1992009-12-26 03:35:45 +00004115 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004116 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4117 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4118 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4119 RParenLoc);
4120 }
4121
John McCall57500772009-12-16 12:17:52 +00004122 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004123 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4124 if (UnOp->getOpcode() == UO_AddrOf)
4125 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4126
John McCall57500772009-12-16 12:17:52 +00004127 if (isa<DeclRefExpr>(NakedFn))
4128 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4129
John McCall2d74de92009-12-01 22:10:20 +00004130 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
4131}
4132
John McCall57500772009-12-16 12:17:52 +00004133/// BuildResolvedCallExpr - Build a call to a resolved expression,
4134/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004135/// unary-convert to an expression of function-pointer or
4136/// block-pointer type.
4137///
4138/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004139ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004140Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4141 SourceLocation LParenLoc,
4142 Expr **Args, unsigned NumArgs,
4143 SourceLocation RParenLoc) {
4144 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4145
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004146 // Promote the function operand.
4147 UsualUnaryConversions(Fn);
4148
Chris Lattner08464942007-12-28 05:29:59 +00004149 // Make the call expr early, before semantic checks. This guarantees cleanup
4150 // of arguments and function on error.
John McCallb268a282010-08-23 23:25:46 +00004151 CallExpr *TheCall = new (Context) CallExpr(Context, Fn,
4152 Args, NumArgs,
4153 Context.BoolTy,
John McCall7decc9e2010-11-18 06:31:45 +00004154 VK_RValue,
John McCallb268a282010-08-23 23:25:46 +00004155 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004156
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004157 const FunctionType *FuncT;
4158 if (!Fn->getType()->isBlockPointerType()) {
4159 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4160 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004161 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004162 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004163 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4164 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00004165 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004166 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004167 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00004168 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004169 }
Chris Lattner08464942007-12-28 05:29:59 +00004170 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004171 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4172 << Fn->getType() << Fn->getSourceRange());
4173
Eli Friedman3164fb12009-03-22 22:00:50 +00004174 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004175 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00004176 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004177 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004178 return ExprError();
4179
Chris Lattner08464942007-12-28 05:29:59 +00004180 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004181 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004182 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004183
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004184 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00004185 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004186 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004187 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004188 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004189 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004190
Douglas Gregord8e97de2009-04-02 15:37:10 +00004191 if (FDecl) {
4192 // Check if we have too few/too many template arguments, based
4193 // on our knowledge of the function definition.
4194 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004195 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004196 const FunctionProtoType *Proto
4197 = Def->getType()->getAs<FunctionProtoType>();
4198 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004199 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4200 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004201 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004202
4203 // If the function we're calling isn't a function prototype, but we have
4204 // a function prototype from a prior declaratiom, use that prototype.
4205 if (!FDecl->hasPrototype())
4206 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004207 }
4208
Steve Naroff0b661582007-08-28 23:30:39 +00004209 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004210 for (unsigned i = 0; i != NumArgs; i++) {
4211 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004212
4213 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004214 InitializedEntity Entity
4215 = InitializedEntity::InitializeParameter(Context,
4216 Proto->getArgType(i));
4217 ExprResult ArgE = PerformCopyInitialization(Entity,
4218 SourceLocation(),
4219 Owned(Arg));
4220 if (ArgE.isInvalid())
4221 return true;
4222
4223 Arg = ArgE.takeAs<Expr>();
4224
4225 } else {
4226 DefaultArgumentPromotion(Arg);
Douglas Gregor8e09a722010-10-25 20:39:23 +00004227 }
4228
Douglas Gregor83025412010-10-26 05:45:40 +00004229 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4230 Arg->getType(),
4231 PDiag(diag::err_call_incomplete_argument)
4232 << Arg->getSourceRange()))
4233 return ExprError();
4234
Chris Lattner08464942007-12-28 05:29:59 +00004235 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004236 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004237 }
Chris Lattner08464942007-12-28 05:29:59 +00004238
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004239 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4240 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004241 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4242 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004243
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004244 // Check for sentinels
4245 if (NDecl)
4246 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004247
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004248 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004249 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00004250 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004251 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004252
Fariborz Jahaniane7d62022010-11-19 18:16:46 +00004253 if (unsigned BuiltinID = FDecl->getBuiltinID()) {
4254 // When not in Objective-C mode, there is no builtin 'id' type.
4255 // We won't have pre-defined library functions which use this type.
4256 if (getLangOptions().ObjC1 ||
4257 Context.BuiltinInfo.GetTypeString(BuiltinID)[0] != 'G')
4258 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4259 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004260 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00004261 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004262 return ExprError();
4263 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004264
John McCallb268a282010-08-23 23:25:46 +00004265 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004266}
4267
John McCalldadc5752010-08-24 06:29:42 +00004268ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004269Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004270 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004271 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004272 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004273 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004274
4275 TypeSourceInfo *TInfo;
4276 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4277 if (!TInfo)
4278 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4279
John McCallb268a282010-08-23 23:25:46 +00004280 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004281}
4282
John McCalldadc5752010-08-24 06:29:42 +00004283ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004284Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00004285 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004286 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004287
Eli Friedman37a186d2008-05-20 05:22:08 +00004288 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004289 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4290 PDiag(diag::err_illegal_decl_array_incomplete_type)
4291 << SourceRange(LParenLoc,
4292 literalExpr->getSourceRange().getEnd())))
4293 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004294 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004295 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4296 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004297 } else if (!literalType->isDependentType() &&
4298 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00004299 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00004300 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00004301 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004302 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004303
Douglas Gregor85dabae2009-12-16 01:38:02 +00004304 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004305 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004306 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004307 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004308 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004309 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004310 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004311 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004312 &literalType);
4313 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004314 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004315 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004316
Chris Lattner79413952008-12-04 23:50:19 +00004317 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004318 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00004319 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004320 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004321 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004322
John McCall7decc9e2010-11-18 06:31:45 +00004323 // In C, compound literals are l-values for some reason.
4324 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4325
John McCall5d7aa7f2010-01-19 22:33:45 +00004326 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00004327 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004328}
4329
John McCalldadc5752010-08-24 06:29:42 +00004330ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00004331Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004332 SourceLocation RBraceLoc) {
4333 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00004334 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004335
Steve Naroff30d242c2007-09-15 18:49:24 +00004336 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004337 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004338
Ted Kremenekac034612010-04-13 23:39:13 +00004339 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4340 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004341 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004342 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004343}
4344
John McCalld7646252010-11-14 08:17:51 +00004345/// Prepares for a scalar cast, performing all the necessary stages
4346/// except the final cast and returning the kind required.
4347static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4348 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4349 // Also, callers should have filtered out the invalid cases with
4350 // pointers. Everything else should be possible.
4351
John McCalle84af4e2010-11-13 01:35:44 +00004352 QualType SrcTy = Src->getType();
John McCalld7646252010-11-14 08:17:51 +00004353 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004354 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004355
John McCall8cb679e2010-11-15 09:13:47 +00004356 switch (SrcTy->getScalarTypeKind()) {
4357 case Type::STK_MemberPointer:
4358 llvm_unreachable("member pointer type in C");
4359
4360 case Type::STK_Pointer:
4361 switch (DestTy->getScalarTypeKind()) {
4362 case Type::STK_Pointer:
4363 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00004364 CK_AnyPointerToObjCPointerCast :
4365 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00004366 case Type::STK_Bool:
4367 return CK_PointerToBoolean;
4368 case Type::STK_Integral:
4369 return CK_PointerToIntegral;
4370 case Type::STK_Floating:
4371 case Type::STK_FloatingComplex:
4372 case Type::STK_IntegralComplex:
4373 case Type::STK_MemberPointer:
4374 llvm_unreachable("illegal cast from pointer");
4375 }
4376 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004377
John McCall8cb679e2010-11-15 09:13:47 +00004378 case Type::STK_Bool: // casting from bool is like casting from an integer
4379 case Type::STK_Integral:
4380 switch (DestTy->getScalarTypeKind()) {
4381 case Type::STK_Pointer:
John McCalld7646252010-11-14 08:17:51 +00004382 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004383 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004384 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004385 case Type::STK_Bool:
4386 return CK_IntegralToBoolean;
4387 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004388 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004389 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004390 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004391 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004392 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004393 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004394 S.ImpCastExprToType(Src, cast<ComplexType>(DestTy)->getElementType(),
4395 CK_IntegralToFloating);
4396 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004397 case Type::STK_MemberPointer:
4398 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004399 }
4400 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004401
John McCall8cb679e2010-11-15 09:13:47 +00004402 case Type::STK_Floating:
4403 switch (DestTy->getScalarTypeKind()) {
4404 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004405 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004406 case Type::STK_Bool:
4407 return CK_FloatingToBoolean;
4408 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004409 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004410 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004411 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004412 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004413 S.ImpCastExprToType(Src, cast<ComplexType>(DestTy)->getElementType(),
4414 CK_FloatingToIntegral);
4415 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004416 case Type::STK_Pointer:
4417 llvm_unreachable("valid float->pointer cast?");
4418 case Type::STK_MemberPointer:
4419 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004420 }
4421 break;
4422
John McCall8cb679e2010-11-15 09:13:47 +00004423 case Type::STK_FloatingComplex:
4424 switch (DestTy->getScalarTypeKind()) {
4425 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004426 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004427 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004428 return CK_FloatingComplexToIntegralComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004429 case Type::STK_Floating:
John McCalld7646252010-11-14 08:17:51 +00004430 return CK_FloatingComplexToReal;
John McCall8cb679e2010-11-15 09:13:47 +00004431 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004432 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004433 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004434 S.ImpCastExprToType(Src, cast<ComplexType>(SrcTy)->getElementType(),
4435 CK_FloatingComplexToReal);
4436 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004437 case Type::STK_Pointer:
4438 llvm_unreachable("valid complex float->pointer cast?");
4439 case Type::STK_MemberPointer:
4440 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004441 }
4442 break;
4443
John McCall8cb679e2010-11-15 09:13:47 +00004444 case Type::STK_IntegralComplex:
4445 switch (DestTy->getScalarTypeKind()) {
4446 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004447 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004448 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004449 return CK_IntegralComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004450 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004451 return CK_IntegralComplexToReal;
John McCall8cb679e2010-11-15 09:13:47 +00004452 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004453 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004454 case Type::STK_Floating:
John McCalld7646252010-11-14 08:17:51 +00004455 S.ImpCastExprToType(Src, cast<ComplexType>(SrcTy)->getElementType(),
4456 CK_IntegralComplexToReal);
4457 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004458 case Type::STK_Pointer:
4459 llvm_unreachable("valid complex int->pointer cast?");
4460 case Type::STK_MemberPointer:
4461 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004462 }
4463 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004464 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004465
John McCalld7646252010-11-14 08:17:51 +00004466 llvm_unreachable("Unhandled scalar cast");
4467 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00004468}
4469
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004470/// CheckCastTypes - Check type constraints for casting between types.
John McCall7decc9e2010-11-18 06:31:45 +00004471bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4472 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4473 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00004474 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00004475 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4476 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00004477 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00004478 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00004479
John McCall7decc9e2010-11-18 06:31:45 +00004480 // We only support r-value casts in C.
4481 VK = VK_RValue;
4482
Douglas Gregorb92a1562010-02-03 00:27:59 +00004483 DefaultFunctionArrayLvalueConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004484
4485 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4486 // type needs to be scalar.
4487 if (castType->isVoidType()) {
4488 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004489 Kind = CK_ToVoid;
Anders Carlssonef918ac2009-10-16 02:35:04 +00004490 return false;
4491 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004492
Eli Friedmane98194d2010-07-17 20:43:49 +00004493 if (RequireCompleteType(TyR.getBegin(), castType,
4494 diag::err_typecheck_cast_to_incomplete))
4495 return true;
4496
Anders Carlssonef918ac2009-10-16 02:35:04 +00004497 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004498 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004499 (castType->isStructureType() || castType->isUnionType())) {
4500 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004501 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004502 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4503 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004504 Kind = CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00004505 return false;
4506 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004507
Anders Carlsson525b76b2009-10-16 02:48:28 +00004508 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004509 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004510 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004511 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004512 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004513 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004514 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004515 castExpr->getType()) &&
4516 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004517 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4518 << castExpr->getSourceRange();
4519 break;
4520 }
4521 }
4522 if (Field == FieldEnd)
4523 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4524 << castExpr->getType() << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004525 Kind = CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00004526 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004527 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004528
Anders Carlsson525b76b2009-10-16 02:48:28 +00004529 // Reject any other conversions to non-scalar types.
4530 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
4531 << castType << castExpr->getSourceRange();
4532 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004533
John McCalld7646252010-11-14 08:17:51 +00004534 // The type we're casting to is known to be a scalar or vector.
4535
4536 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004537 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00004538 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004539 return Diag(castExpr->getLocStart(),
4540 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004541 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004542 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004543
4544 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00004545 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004546
Anders Carlsson525b76b2009-10-16 02:48:28 +00004547 if (castType->isVectorType())
4548 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
4549 if (castExpr->getType()->isVectorType())
4550 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
4551
John McCalld7646252010-11-14 08:17:51 +00004552 // The source and target types are both scalars, i.e.
4553 // - arithmetic types (fundamental, enum, and complex)
4554 // - all kinds of pointers
4555 // Note that member pointers were filtered out with C++, above.
4556
Anders Carlsson43d70f82009-10-16 05:23:41 +00004557 if (isa<ObjCSelectorExpr>(castExpr))
4558 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004559
John McCalld7646252010-11-14 08:17:51 +00004560 // If either type is a pointer, the other type has to be either an
4561 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00004562 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004563 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00004564 if (!castExprType->isIntegralType(Context) &&
Douglas Gregorb90df602010-06-16 00:17:44 +00004565 castExprType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004566 return Diag(castExpr->getLocStart(),
4567 diag::err_cast_pointer_from_non_pointer_int)
4568 << castExprType << castExpr->getSourceRange();
4569 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004570 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004571 return Diag(castExpr->getLocStart(),
4572 diag::err_cast_pointer_to_non_pointer_int)
4573 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004574 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004575
John McCalld7646252010-11-14 08:17:51 +00004576 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCall2b5c1b22010-08-12 21:44:57 +00004577
John McCalld7646252010-11-14 08:17:51 +00004578 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004579 CheckCastAlign(castExpr, castType, TyR);
4580
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004581 return false;
4582}
4583
Anders Carlsson525b76b2009-10-16 02:48:28 +00004584bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004585 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004586 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004587
Anders Carlssonde71adf2007-11-27 05:51:55 +00004588 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004589 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004590 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004591 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004592 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004593 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004594 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004595 } else
4596 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004597 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004598 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004599
John McCalle3027922010-08-25 11:45:40 +00004600 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004601 return false;
4602}
4603
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004604bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCalle3027922010-08-25 11:45:40 +00004605 CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004606 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004607
Anders Carlsson43d70f82009-10-16 05:23:41 +00004608 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004609
Nate Begemanc8961a42009-06-27 22:05:55 +00004610 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4611 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004612 if (SrcTy->isVectorType()) {
4613 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
4614 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4615 << DestTy << SrcTy << R;
John McCalle3027922010-08-25 11:45:40 +00004616 Kind = CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00004617 return false;
4618 }
4619
Nate Begemanbd956c42009-06-28 02:36:38 +00004620 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004621 // conversion will take place first from scalar to elt type, and then
4622 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004623 if (SrcTy->isPointerType())
4624 return Diag(R.getBegin(),
4625 diag::err_invalid_conversion_between_vector_and_scalar)
4626 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004627
4628 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4629 ImpCastExprToType(CastExpr, DestElemTy,
John McCalld7646252010-11-14 08:17:51 +00004630 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004631
John McCalle3027922010-08-25 11:45:40 +00004632 Kind = CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00004633 return false;
4634}
4635
John McCalldadc5752010-08-24 06:29:42 +00004636ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004637Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004638 SourceLocation RParenLoc, Expr *castExpr) {
4639 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004640 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004641
John McCall97513962010-01-15 18:39:57 +00004642 TypeSourceInfo *castTInfo;
4643 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4644 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00004645 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00004646
Nate Begeman5ec4b312009-08-10 23:49:36 +00004647 // If the Expr being casted is a ParenListExpr, handle it specially.
4648 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00004649 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00004650 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00004651
John McCallb268a282010-08-23 23:25:46 +00004652 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004653}
4654
John McCalldadc5752010-08-24 06:29:42 +00004655ExprResult
John McCallebe54742010-01-15 18:56:44 +00004656Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004657 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004658 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004659 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004660 CXXCastPath BasePath;
John McCallebe54742010-01-15 18:56:44 +00004661 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCall7decc9e2010-11-18 06:31:45 +00004662 Kind, VK, BasePath))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004663 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00004664
John McCallcf142162010-08-07 06:22:56 +00004665 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +00004666 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00004667 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00004668 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004669}
4670
Nate Begeman5ec4b312009-08-10 23:49:36 +00004671/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4672/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004673ExprResult
John McCallb268a282010-08-23 23:25:46 +00004674Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004675 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4676 if (!E)
4677 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004678
John McCalldadc5752010-08-24 06:29:42 +00004679 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004680
Nate Begeman5ec4b312009-08-10 23:49:36 +00004681 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004682 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4683 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004684
John McCallb268a282010-08-23 23:25:46 +00004685 if (Result.isInvalid()) return ExprError();
4686
4687 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004688}
4689
John McCalldadc5752010-08-24 06:29:42 +00004690ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00004691Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00004692 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00004693 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00004694 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00004695 QualType Ty = TInfo->getType();
John Thompson781ad172010-06-30 22:55:51 +00004696 bool isAltiVecLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00004697
John Thompson781ad172010-06-30 22:55:51 +00004698 // Check for an altivec literal,
4699 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004700 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4701 if (PE->getNumExprs() == 0) {
4702 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4703 return ExprError();
4704 }
John Thompson781ad172010-06-30 22:55:51 +00004705 if (PE->getNumExprs() == 1) {
4706 if (!PE->getExpr(0)->getType()->isVectorType())
4707 isAltiVecLiteral = true;
4708 }
4709 else
4710 isAltiVecLiteral = true;
4711 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004712
John Thompson781ad172010-06-30 22:55:51 +00004713 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
4714 // then handle it as such.
4715 if (isAltiVecLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004716 llvm::SmallVector<Expr *, 8> initExprs;
4717 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4718 initExprs.push_back(PE->getExpr(i));
4719
4720 // FIXME: This means that pretty-printing the final AST will produce curly
4721 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00004722 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4723 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00004724 initExprs.size(), RParenLoc);
4725 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00004726 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004727 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004728 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00004729 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00004730 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00004731 if (Result.isInvalid()) return ExprError();
4732 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004733 }
4734}
4735
John McCalldadc5752010-08-24 06:29:42 +00004736ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004737 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004738 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00004739 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004740 unsigned nexprs = Val.size();
4741 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004742 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4743 Expr *expr;
4744 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4745 expr = new (Context) ParenExpr(L, R, exprs[0]);
4746 else
4747 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004748 return Owned(expr);
4749}
4750
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004751/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4752/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004753/// C99 6.5.15
4754QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall7decc9e2010-11-18 06:31:45 +00004755 Expr *&SAVE, ExprValueKind &VK,
John McCall4bc41ae2010-11-18 19:01:18 +00004756 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004757 SourceLocation QuestionLoc) {
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004758 // If both LHS and RHS are overloaded functions, try to resolve them.
4759 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
4760 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
4761 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
4762 if (LHSResult.isInvalid())
4763 return QualType();
4764
4765 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
4766 if (RHSResult.isInvalid())
4767 return QualType();
4768
4769 LHS = LHSResult.take();
4770 RHS = RHSResult.take();
4771 }
4772
Sebastian Redl1a99f442009-04-16 17:51:27 +00004773 // C++ is sufficiently different to merit its own checker.
4774 if (getLangOptions().CPlusPlus)
John McCall4bc41ae2010-11-18 19:01:18 +00004775 return CXXCheckConditionalOperands(Cond, LHS, RHS, SAVE,
4776 VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004777
4778 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004779 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004780
Chris Lattner432cff52009-02-18 04:28:32 +00004781 UsualUnaryConversions(Cond);
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00004782 if (SAVE) {
4783 SAVE = LHS = Cond;
4784 }
4785 else
4786 UsualUnaryConversions(LHS);
Chris Lattner432cff52009-02-18 04:28:32 +00004787 UsualUnaryConversions(RHS);
4788 QualType CondTy = Cond->getType();
4789 QualType LHSTy = LHS->getType();
4790 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004791
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004792 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004793 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00004794 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4795 // Throw an error if its not either.
4796 if (getLangOptions().OpenCL) {
4797 if (!CondTy->isVectorType()) {
4798 Diag(Cond->getLocStart(),
4799 diag::err_typecheck_cond_expect_scalar_or_vector)
4800 << CondTy;
4801 return QualType();
4802 }
4803 }
4804 else {
4805 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4806 << CondTy;
4807 return QualType();
4808 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004809 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004810
Chris Lattnere2949f42008-01-06 22:42:25 +00004811 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004812 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4813 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00004814
Nate Begemanabb5a732010-09-20 22:41:17 +00004815 // OpenCL: If the condition is a vector, and both operands are scalar,
4816 // attempt to implicity convert them to the vector type to act like the
4817 // built in select.
4818 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4819 // Both operands should be of scalar type.
4820 if (!LHSTy->isScalarType()) {
4821 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4822 << CondTy;
4823 return QualType();
4824 }
4825 if (!RHSTy->isScalarType()) {
4826 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4827 << CondTy;
4828 return QualType();
4829 }
4830 // Implicity convert these scalars to the type of the condition.
4831 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
4832 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
4833 }
4834
Chris Lattnere2949f42008-01-06 22:42:25 +00004835 // If both operands have arithmetic type, do the usual arithmetic conversions
4836 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004837 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4838 UsualArithmeticConversions(LHS, RHS);
4839 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004840 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004841
Chris Lattnere2949f42008-01-06 22:42:25 +00004842 // If both operands are the same structure or union type, the result is that
4843 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004844 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4845 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004846 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004847 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004848 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004849 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004850 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004851 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004852
Chris Lattnere2949f42008-01-06 22:42:25 +00004853 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004854 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004855 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4856 if (!LHSTy->isVoidType())
4857 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4858 << RHS->getSourceRange();
4859 if (!RHSTy->isVoidType())
4860 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4861 << LHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004862 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
4863 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004864 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004865 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004866 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4867 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004868 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004869 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004870 // promote the null to a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00004871 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004872 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004873 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004874 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004875 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00004876 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004877 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004878 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004879
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004880 // All objective-c pointer type analysis is done here.
4881 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4882 QuestionLoc);
4883 if (!compositeType.isNull())
4884 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004885
4886
Steve Naroff05efa972009-07-01 14:36:47 +00004887 // Handle block pointer types.
4888 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4889 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4890 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4891 QualType destType = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00004892 ImpCastExprToType(LHS, destType, CK_BitCast);
4893 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004894 return destType;
4895 }
4896 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004897 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004898 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004899 }
Steve Naroff05efa972009-07-01 14:36:47 +00004900 // We have 2 block pointer types.
4901 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4902 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004903 return LHSTy;
4904 }
Steve Naroff05efa972009-07-01 14:36:47 +00004905 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004906 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4907 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004908
Steve Naroff05efa972009-07-01 14:36:47 +00004909 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4910 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004911 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004912 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004913 // In this situation, we assume void* type. No especially good
4914 // reason, but this is what gcc does, and we do have to pick
4915 // to get a consistent AST.
4916 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00004917 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
4918 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004919 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004920 }
Steve Naroff05efa972009-07-01 14:36:47 +00004921 // The block pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00004922 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
4923 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004924 return LHSTy;
4925 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004926
Steve Naroff05efa972009-07-01 14:36:47 +00004927 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4928 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4929 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004930 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4931 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004932
4933 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4934 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4935 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004936 QualType destPointee
4937 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004938 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004939 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00004940 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004941 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00004942 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004943 return destType;
4944 }
4945 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004946 QualType destPointee
4947 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004948 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004949 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00004950 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004951 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00004952 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004953 return destType;
4954 }
4955
4956 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4957 // Two identical pointer types are always compatible.
4958 return LHSTy;
4959 }
4960 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4961 rhptee.getUnqualifiedType())) {
4962 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4963 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4964 // In this situation, we assume void* type. No especially good
4965 // reason, but this is what gcc does, and we do have to pick
4966 // to get a consistent AST.
4967 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00004968 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
4969 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004970 return incompatTy;
4971 }
4972 // The pointer types are compatible.
4973 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4974 // differently qualified versions of compatible types, the result type is
4975 // a pointer to an appropriately qualified version of the *composite*
4976 // type.
4977 // FIXME: Need to calculate the composite type.
4978 // FIXME: Need to add qualifiers
John McCalle3027922010-08-25 11:45:40 +00004979 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
4980 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004981 return LHSTy;
4982 }
Mike Stump11289f42009-09-09 15:08:12 +00004983
John McCalle84af4e2010-11-13 01:35:44 +00004984 // GCC compatibility: soften pointer/integer mismatch. Note that
4985 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00004986 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4987 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4988 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004989 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004990 return RHSTy;
4991 }
4992 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4993 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4994 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004995 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004996 return LHSTy;
4997 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004998
Chris Lattnere2949f42008-01-06 22:42:25 +00004999 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005000 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5001 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005002 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005003}
5004
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005005/// FindCompositeObjCPointerType - Helper method to find composite type of
5006/// two objective-c pointer types of the two input expressions.
5007QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5008 SourceLocation QuestionLoc) {
5009 QualType LHSTy = LHS->getType();
5010 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005011
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005012 // Handle things like Class and struct objc_class*. Here we case the result
5013 // to the pseudo-builtin, because that will be implicitly cast back to the
5014 // redefinition type if an attempt is made to access its fields.
5015 if (LHSTy->isObjCClassType() &&
5016 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
John McCalle3027922010-08-25 11:45:40 +00005017 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005018 return LHSTy;
5019 }
5020 if (RHSTy->isObjCClassType() &&
5021 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
John McCalle3027922010-08-25 11:45:40 +00005022 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005023 return RHSTy;
5024 }
5025 // And the same for struct objc_object* / id
5026 if (LHSTy->isObjCIdType() &&
5027 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
John McCalle3027922010-08-25 11:45:40 +00005028 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005029 return LHSTy;
5030 }
5031 if (RHSTy->isObjCIdType() &&
5032 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
John McCalle3027922010-08-25 11:45:40 +00005033 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005034 return RHSTy;
5035 }
5036 // And the same for struct objc_selector* / SEL
5037 if (Context.isObjCSelType(LHSTy) &&
5038 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
John McCalle3027922010-08-25 11:45:40 +00005039 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005040 return LHSTy;
5041 }
5042 if (Context.isObjCSelType(RHSTy) &&
5043 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
John McCalle3027922010-08-25 11:45:40 +00005044 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005045 return RHSTy;
5046 }
5047 // Check constraints for Objective-C object pointers types.
5048 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005049
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005050 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5051 // Two identical object pointer types are always compatible.
5052 return LHSTy;
5053 }
5054 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5055 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5056 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005057
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005058 // If both operands are interfaces and either operand can be
5059 // assigned to the other, use that type as the composite
5060 // type. This allows
5061 // xxx ? (A*) a : (B*) b
5062 // where B is a subclass of A.
5063 //
5064 // Additionally, as for assignment, if either type is 'id'
5065 // allow silent coercion. Finally, if the types are
5066 // incompatible then make sure to use 'id' as the composite
5067 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005068
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005069 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5070 // It could return the composite type.
5071 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5072 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5073 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5074 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5075 } else if ((LHSTy->isObjCQualifiedIdType() ||
5076 RHSTy->isObjCQualifiedIdType()) &&
5077 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5078 // Need to handle "id<xx>" explicitly.
5079 // GCC allows qualified id and any Objective-C type to devolve to
5080 // id. Currently localizing to here until clear this should be
5081 // part of ObjCQualifiedIdTypesAreCompatible.
5082 compositeType = Context.getObjCIdType();
5083 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5084 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005085 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005086 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5087 ;
5088 else {
5089 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5090 << LHSTy << RHSTy
5091 << LHS->getSourceRange() << RHS->getSourceRange();
5092 QualType incompatTy = Context.getObjCIdType();
John McCalle3027922010-08-25 11:45:40 +00005093 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5094 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005095 return incompatTy;
5096 }
5097 // The object pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005098 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5099 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005100 return compositeType;
5101 }
5102 // Check Objective-C object pointer types and 'void *'
5103 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5104 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5105 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5106 QualType destPointee
5107 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5108 QualType destType = Context.getPointerType(destPointee);
5109 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005110 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005111 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005112 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005113 return destType;
5114 }
5115 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5116 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5117 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5118 QualType destPointee
5119 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5120 QualType destType = Context.getPointerType(destPointee);
5121 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005122 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005123 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005124 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005125 return destType;
5126 }
5127 return QualType();
5128}
5129
Steve Naroff83895f72007-09-16 03:34:24 +00005130/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005131/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005132ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005133 SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +00005134 Expr *CondExpr, Expr *LHSExpr,
5135 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005136 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5137 // was the condition.
5138 bool isLHSNull = LHSExpr == 0;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005139 Expr *SAVEExpr = 0;
5140 if (isLHSNull) {
5141 LHSExpr = SAVEExpr = CondExpr;
5142 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005143
John McCall7decc9e2010-11-18 06:31:45 +00005144 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005145 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00005146 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCall4bc41ae2010-11-18 19:01:18 +00005147 SAVEExpr, VK, OK, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00005148 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005149 return ExprError();
5150
Douglas Gregor7e112b02009-08-26 14:37:04 +00005151 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005152 LHSExpr, ColonLoc,
5153 RHSExpr, SAVEExpr,
John McCall4bc41ae2010-11-18 19:01:18 +00005154 result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005155}
5156
Steve Naroff3f597292007-05-11 22:18:03 +00005157// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005158// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005159// routine is it effectively iqnores the qualifiers on the top level pointee.
5160// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5161// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005162Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00005163Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00005164 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005165
David Chisnall9f57c292009-08-17 16:35:33 +00005166 if ((lhsType->isObjCClassType() &&
5167 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
5168 (rhsType->isObjCClassType() &&
5169 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
5170 return Compatible;
5171 }
5172
Steve Naroff1f4d7272007-05-11 04:00:31 +00005173 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005174 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
5175 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005176
Steve Naroff1f4d7272007-05-11 04:00:31 +00005177 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00005178 lhptee = Context.getCanonicalType(lhptee);
5179 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00005180
Chris Lattner9bad62c2008-01-04 18:04:52 +00005181 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005182
5183 // C99 6.5.16.1p1: This following citation is common to constraints
5184 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5185 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00005186 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00005187 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00005188 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00005189
Mike Stump4e1f26a2009-02-19 03:04:26 +00005190 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5191 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005192 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005193 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005194 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005195 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005196
Chris Lattner0a788432008-01-03 22:56:36 +00005197 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005198 assert(rhptee->isFunctionType());
5199 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005200 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005201
Chris Lattner0a788432008-01-03 22:56:36 +00005202 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005203 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005204 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005205
5206 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005207 assert(lhptee->isFunctionType());
5208 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005209 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005210 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005211 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00005212 lhptee = lhptee.getUnqualifiedType();
5213 rhptee = rhptee.getUnqualifiedType();
5214 if (!Context.typesAreCompatible(lhptee, rhptee)) {
5215 // Check if the pointee types are compatible ignoring the sign.
5216 // We explicitly check for char so that we catch "char" vs
5217 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005218 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00005219 lhptee = Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005220 else if (lhptee->hasSignedIntegerRepresentation())
Eli Friedman80160bd2009-03-22 23:59:44 +00005221 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005222
Chris Lattnerec3a1562009-10-17 20:33:28 +00005223 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00005224 rhptee = Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005225 else if (rhptee->hasSignedIntegerRepresentation())
Eli Friedman80160bd2009-03-22 23:59:44 +00005226 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005227
Eli Friedman80160bd2009-03-22 23:59:44 +00005228 if (lhptee == rhptee) {
5229 // Types are compatible ignoring the sign. Qualifier incompatibility
5230 // takes priority over sign incompatibility because the sign
5231 // warning can be disabled.
5232 if (ConvTy != Compatible)
5233 return ConvTy;
5234 return IncompatiblePointerSign;
5235 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005236
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005237 // If we are a multi-level pointer, it's possible that our issue is simply
5238 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5239 // the eventual target type is the same and the pointers have the same
5240 // level of indirection, this must be the issue.
5241 if (lhptee->isPointerType() && rhptee->isPointerType()) {
5242 do {
5243 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
5244 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005245
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005246 lhptee = Context.getCanonicalType(lhptee);
5247 rhptee = Context.getCanonicalType(rhptee);
5248 } while (lhptee->isPointerType() && rhptee->isPointerType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005249
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005250 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00005251 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005252 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005253
Eli Friedman80160bd2009-03-22 23:59:44 +00005254 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00005255 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005256 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005257 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005258}
5259
Steve Naroff081c7422008-09-04 15:10:53 +00005260/// CheckBlockPointerTypesForAssignment - This routine determines whether two
5261/// block pointer types are compatible or whether a block and normal pointer
5262/// are compatible. It is more restrict than comparing two function pointer
5263// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005264Sema::AssignConvertType
5265Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00005266 QualType rhsType) {
5267 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005268
Steve Naroff081c7422008-09-04 15:10:53 +00005269 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005270 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
5271 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005272
Steve Naroff081c7422008-09-04 15:10:53 +00005273 // make sure we operate on the canonical type
5274 lhptee = Context.getCanonicalType(lhptee);
5275 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005276
Steve Naroff081c7422008-09-04 15:10:53 +00005277 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005278
Steve Naroff081c7422008-09-04 15:10:53 +00005279 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005280 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00005281 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005282
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005283 if (!getLangOptions().CPlusPlus) {
5284 if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5285 return IncompatibleBlockPointer;
5286 }
5287 else if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00005288 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00005289 return ConvTy;
5290}
5291
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005292/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
5293/// for assignment compatibility.
5294Sema::AssignConvertType
5295Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005296 if (lhsType->isObjCBuiltinType()) {
5297 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005298 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5299 !rhsType->isObjCQualifiedClassType())
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005300 return IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005301 return Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005302 }
5303 if (rhsType->isObjCBuiltinType()) {
5304 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005305 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5306 !lhsType->isObjCQualifiedClassType())
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005307 return IncompatiblePointer;
5308 return Compatible;
5309 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005310 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005311 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005312 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005313 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
5314 // make sure we operate on the canonical type
5315 lhptee = Context.getCanonicalType(lhptee);
5316 rhptee = Context.getCanonicalType(rhptee);
5317 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5318 return CompatiblePointerDiscardsQualifiers;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005319
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005320 if (Context.typesAreCompatible(lhsType, rhsType))
5321 return Compatible;
5322 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
5323 return IncompatibleObjCQualifiedId;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005324 return IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005325}
5326
John McCall29600e12010-11-16 02:32:08 +00005327Sema::AssignConvertType
5328Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
5329 // Fake up an opaque expression. We don't actually care about what
5330 // cast operations are required, so if CheckAssignmentConstraints
5331 // adds casts to this they'll be wasted, but fortunately that doesn't
5332 // usually happen on valid code.
5333 OpaqueValueExpr rhs(rhsType, VK_RValue);
5334 Expr *rhsPtr = &rhs;
5335 CastKind K = CK_Invalid;
5336
5337 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5338}
5339
Mike Stump4e1f26a2009-02-19 03:04:26 +00005340/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5341/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005342/// pointers. Here are some objectionable examples that GCC considers warnings:
5343///
5344/// int a, *pint;
5345/// short *pshort;
5346/// struct foo *pfoo;
5347///
5348/// pint = pshort; // warning: assignment from incompatible pointer type
5349/// a = pint; // warning: assignment makes integer from pointer without a cast
5350/// pint = a; // warning: assignment makes pointer from integer without a cast
5351/// pint = pfoo; // warning: assignment from incompatible pointer type
5352///
5353/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005354/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005355///
John McCall8cb679e2010-11-15 09:13:47 +00005356/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005357Sema::AssignConvertType
John McCall29600e12010-11-16 02:32:08 +00005358Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005359 CastKind &Kind) {
John McCall29600e12010-11-16 02:32:08 +00005360 QualType rhsType = rhs->getType();
5361
Chris Lattnera52c2f22008-01-04 23:18:45 +00005362 // Get canonical types. We're not formatting these types, just comparing
5363 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005364 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5365 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005366
John McCall8cb679e2010-11-15 09:13:47 +00005367 if (lhsType == rhsType) {
5368 Kind = CK_NoOp;
Chris Lattnerf5c973d2008-01-07 17:51:46 +00005369 return Compatible; // Common case: fast path an exact match.
John McCall8cb679e2010-11-15 09:13:47 +00005370 }
Steve Naroff44fd8ff2007-07-24 21:46:40 +00005371
David Chisnall9f57c292009-08-17 16:35:33 +00005372 if ((lhsType->isObjCClassType() &&
5373 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
5374 (rhsType->isObjCClassType() &&
5375 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
John McCall8cb679e2010-11-15 09:13:47 +00005376 Kind = CK_BitCast;
5377 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005378 }
5379
Douglas Gregor6b754842008-10-28 00:22:11 +00005380 // If the left-hand side is a reference type, then we are in a
5381 // (rare!) case where we've allowed the use of references in C,
5382 // e.g., as a parameter type in a built-in function. In this case,
5383 // just make sure that the type referenced is compatible with the
5384 // right-hand side type. The caller is responsible for adjusting
5385 // lhsType so that the resulting expression does not have reference
5386 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005387 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005388 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5389 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005390 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005391 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005392 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005393 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005394 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5395 // to the same ExtVector type.
5396 if (lhsType->isExtVectorType()) {
5397 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005398 return Incompatible;
5399 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005400 // CK_VectorSplat does T -> vector T, so first cast to the
5401 // element type.
5402 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5403 if (elType != rhsType) {
5404 Kind = PrepareScalarCast(*this, rhs, elType);
5405 ImpCastExprToType(rhs, elType, Kind);
5406 }
5407 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005408 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005409 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005410 }
Mike Stump11289f42009-09-09 15:08:12 +00005411
Nate Begeman191a6b12008-07-14 18:02:46 +00005412 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005413 if (lhsType->isVectorType() && rhsType->isVectorType()) {
5414 // If we are allowing lax vector conversions, and LHS and RHS are both
5415 // vectors, the total size only needs to be the same. This is a bitcast;
5416 // no bits are changed but the result type is different.
5417 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005418 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005419 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005420 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005421 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005422
5423 // Allow assignments of an AltiVec vector type to an equivalent GCC
5424 // vector type and vice versa
John McCall8cb679e2010-11-15 09:13:47 +00005425 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCall3065d042010-11-15 10:08:00 +00005426 Kind = CK_BitCast;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005427 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005428 }
Chris Lattner881a2122008-01-04 23:32:24 +00005429 }
5430 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005431 }
Eli Friedman3360d892008-05-30 18:07:22 +00005432
Douglas Gregorbea453a2010-05-23 21:53:47 +00005433 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005434 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005435 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005436 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005437 }
Eli Friedman3360d892008-05-30 18:07:22 +00005438
Chris Lattnerec646832008-04-07 06:49:41 +00005439 if (isa<PointerType>(lhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005440 if (rhsType->isIntegerType()) {
5441 Kind = CK_IntegralToPointer; // FIXME: null?
Chris Lattner940cfeb2008-01-04 18:22:42 +00005442 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005443 }
Eli Friedman3360d892008-05-30 18:07:22 +00005444
John McCall8cb679e2010-11-15 09:13:47 +00005445 if (isa<PointerType>(rhsType)) {
5446 Kind = CK_BitCast;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005447 return CheckPointerTypesForAssignment(lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005448 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005449
Steve Naroffaccc4882009-07-20 17:56:53 +00005450 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005451 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005452 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005453 if (lhsType->isVoidPointerType()) // an exception to the rule.
5454 return Compatible;
5455 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005456 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005457 if (rhsType->getAs<BlockPointerType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005458 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5459 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005460 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005461 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005462
5463 // Treat block pointers as objects.
John McCall8cb679e2010-11-15 09:13:47 +00005464 if (getLangOptions().ObjC1 && lhsType->isObjCIdType()) {
5465 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005466 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005467 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005468 }
Steve Naroff081c7422008-09-04 15:10:53 +00005469 return Incompatible;
5470 }
5471
5472 if (isa<BlockPointerType>(lhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005473 if (rhsType->isIntegerType()) {
5474 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005475 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005476 }
5477
5478 Kind = CK_AnyPointerToObjCPointerCast;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005479
Steve Naroff32d072c2008-09-29 18:10:17 +00005480 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005481 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00005482 return Compatible;
5483
Steve Naroff081c7422008-09-04 15:10:53 +00005484 if (rhsType->isBlockPointerType())
5485 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005486
John McCall8cb679e2010-11-15 09:13:47 +00005487 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
Steve Naroff081c7422008-09-04 15:10:53 +00005488 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00005489 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005490
Chris Lattnera52c2f22008-01-04 23:18:45 +00005491 return Incompatible;
5492 }
5493
Steve Naroff7cae42b2009-07-10 23:34:53 +00005494 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005495 if (rhsType->isIntegerType()) {
5496 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005497 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005498 }
5499
5500 Kind = CK_BitCast;
Mike Stump11289f42009-09-09 15:08:12 +00005501
Steve Naroffaccc4882009-07-20 17:56:53 +00005502 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005503 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005504 if (rhsType->isVoidPointerType()) // an exception to the rule.
5505 return Compatible;
5506 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005507 }
5508 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005509 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005510 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005511 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005512 if (RHSPT->getPointeeType()->isVoidType())
5513 return Compatible;
5514 }
5515 // Treat block pointers as objects.
5516 if (rhsType->isBlockPointerType())
5517 return Compatible;
5518 return Incompatible;
5519 }
Chris Lattnerec646832008-04-07 06:49:41 +00005520 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00005521 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005522 if (lhsType == Context.BoolTy) {
5523 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005524 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005525 }
Eli Friedman3360d892008-05-30 18:07:22 +00005526
John McCall8cb679e2010-11-15 09:13:47 +00005527 if (lhsType->isIntegerType()) {
5528 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005529 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005530 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005531
5532 if (isa<BlockPointerType>(lhsType) &&
John McCall8cb679e2010-11-15 09:13:47 +00005533 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5534 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005535 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005536 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005537 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005538 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005539 if (isa<ObjCObjectPointerType>(rhsType)) {
5540 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005541 if (lhsType == Context.BoolTy) {
5542 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005543 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005544 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005545
John McCall8cb679e2010-11-15 09:13:47 +00005546 if (lhsType->isIntegerType()) {
5547 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005548 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005549 }
5550
5551 Kind = CK_BitCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005552
Steve Naroffaccc4882009-07-20 17:56:53 +00005553 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005554 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005555 if (lhsType->isVoidPointerType()) // an exception to the rule.
5556 return Compatible;
5557 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005558 }
5559 if (isa<BlockPointerType>(lhsType) &&
John McCall8cb679e2010-11-15 09:13:47 +00005560 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5561 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005562 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005563 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005564 return Incompatible;
5565 }
Eli Friedman3360d892008-05-30 18:07:22 +00005566
Chris Lattnera52c2f22008-01-04 23:18:45 +00005567 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005568 if (Context.typesAreCompatible(lhsType, rhsType)) {
5569 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005570 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005571 }
Bill Wendling216423b2007-05-30 06:30:29 +00005572 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00005573 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005574}
5575
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005576/// \brief Constructs a transparent union from an expression that is
5577/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00005578static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005579 QualType UnionType, FieldDecl *Field) {
5580 // Build an initializer list that designates the appropriate member
5581 // of the transparent union.
Ted Kremenekac034612010-04-13 23:39:13 +00005582 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005583 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005584 SourceLocation());
5585 Initializer->setType(UnionType);
5586 Initializer->setInitializedFieldInUnion(Field);
5587
5588 // Build a compound literal constructing a value of the transparent
5589 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005590 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00005591 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall7decc9e2010-11-18 06:31:45 +00005592 VK_RValue, Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005593}
5594
5595Sema::AssignConvertType
5596Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
5597 QualType FromType = rExpr->getType();
5598
Mike Stump11289f42009-09-09 15:08:12 +00005599 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005600 // transparent_union GCC extension.
5601 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005602 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005603 return Incompatible;
5604
5605 // The field to initialize within the transparent union.
5606 RecordDecl *UD = UT->getDecl();
5607 FieldDecl *InitField = 0;
5608 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005609 for (RecordDecl::field_iterator it = UD->field_begin(),
5610 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005611 it != itend; ++it) {
5612 if (it->getType()->isPointerType()) {
5613 // If the transparent union contains a pointer type, we allow:
5614 // 1) void pointer
5615 // 2) null pointer constant
5616 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005617 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +00005618 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005619 InitField = *it;
5620 break;
5621 }
Mike Stump11289f42009-09-09 15:08:12 +00005622
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005623 if (rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005624 Expr::NPC_ValueDependentIsNull)) {
John McCalle84af4e2010-11-13 01:35:44 +00005625 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005626 InitField = *it;
5627 break;
5628 }
5629 }
5630
John McCall29600e12010-11-16 02:32:08 +00005631 Expr *rhs = rExpr;
John McCall8cb679e2010-11-15 09:13:47 +00005632 CastKind Kind = CK_Invalid;
John McCall29600e12010-11-16 02:32:08 +00005633 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005634 == Compatible) {
John McCall29600e12010-11-16 02:32:08 +00005635 ImpCastExprToType(rhs, it->getType(), Kind);
5636 rExpr = rhs;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005637 InitField = *it;
5638 break;
5639 }
5640 }
5641
5642 if (!InitField)
5643 return Incompatible;
5644
5645 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
5646 return Compatible;
5647}
5648
Chris Lattner9bad62c2008-01-04 18:04:52 +00005649Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005650Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005651 if (getLangOptions().CPlusPlus) {
5652 if (!lhsType->isRecordType()) {
5653 // C++ 5.17p3: If the left operand is not of class type, the
5654 // expression is implicitly converted (C++ 4) to the
5655 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00005656 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005657 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00005658 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00005659 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00005660 }
5661
5662 // FIXME: Currently, we fall through and treat C++ classes like C
5663 // structures.
5664 }
5665
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005666 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5667 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00005668 if ((lhsType->isPointerType() ||
5669 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00005670 lhsType->isBlockPointerType())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005671 && rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005672 Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00005673 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005674 return Compatible;
5675 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005676
Chris Lattnere6dcd502007-10-16 02:55:40 +00005677 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005678 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005679 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005680 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005681 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005682 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00005683 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00005684 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005685
John McCall8cb679e2010-11-15 09:13:47 +00005686 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005687 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00005688 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005689
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005690 // C99 6.5.16.1p2: The value of the right operand is converted to the
5691 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005692 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5693 // so that we can use references in built-in functions even in C.
5694 // The getNonReferenceType() call makes sure that the resulting expression
5695 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005696 if (result != Incompatible && rExpr->getType() != lhsType)
John McCall8cb679e2010-11-15 09:13:47 +00005697 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005698 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005699}
5700
Chris Lattner326f7572008-11-18 01:30:42 +00005701QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005702 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005703 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00005704 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005705 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005706}
5707
Chris Lattnerfaa54172010-01-12 21:23:57 +00005708QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005709 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005710 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00005711 QualType lhsType =
5712 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
5713 QualType rhsType =
5714 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005715
Nate Begeman191a6b12008-07-14 18:02:46 +00005716 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005717 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00005718 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005719
Nate Begeman191a6b12008-07-14 18:02:46 +00005720 // Handle the case of a vector & extvector type of the same size and element
5721 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005722 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00005723 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00005724 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00005725 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005726 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005727 if (lhsType->isExtVectorType()) {
John McCalle3027922010-08-25 11:45:40 +00005728 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005729 return lhsType;
5730 }
5731
John McCalle3027922010-08-25 11:45:40 +00005732 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005733 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00005734 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
5735 // If we are allowing lax vector conversions, and LHS and RHS are both
5736 // vectors, the total size only needs to be the same. This is a
5737 // bitcast; no bits are changed but the result type is different.
5738 ImpCastExprToType(rex, lhsType, CK_BitCast);
5739 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005740 }
Eric Christophera613f562010-08-26 00:42:16 +00005741 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00005742 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005743 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005744
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005745 // Handle the case of equivalent AltiVec and GCC vector types
5746 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5747 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCalle3027922010-08-25 11:45:40 +00005748 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005749 return rhsType;
5750 }
5751
Nate Begemanbd956c42009-06-28 02:36:38 +00005752 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5753 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5754 bool swapped = false;
5755 if (rhsType->isExtVectorType()) {
5756 swapped = true;
5757 std::swap(rex, lex);
5758 std::swap(rhsType, lhsType);
5759 }
Mike Stump11289f42009-09-09 15:08:12 +00005760
Nate Begeman886448d2009-06-28 19:12:57 +00005761 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005762 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005763 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005764 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00005765 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5766 if (order > 0)
5767 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
5768 if (order >= 0) {
5769 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005770 if (swapped) std::swap(rex, lex);
5771 return lhsType;
5772 }
5773 }
5774 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5775 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005776 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5777 if (order > 0)
5778 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
5779 if (order >= 0) {
5780 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005781 if (swapped) std::swap(rex, lex);
5782 return lhsType;
5783 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005784 }
5785 }
Mike Stump11289f42009-09-09 15:08:12 +00005786
Nate Begeman886448d2009-06-28 19:12:57 +00005787 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00005788 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005789 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00005790 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005791 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005792}
5793
Chris Lattnerfaa54172010-01-12 21:23:57 +00005794QualType Sema::CheckMultiplyDivideOperands(
5795 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00005796 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005797 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005798
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005799 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005800
Chris Lattnerfaa54172010-01-12 21:23:57 +00005801 if (!lex->getType()->isArithmeticType() ||
5802 !rex->getType()->isArithmeticType())
5803 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005804
Chris Lattnerfaa54172010-01-12 21:23:57 +00005805 // Check for division by zero.
5806 if (isDiv &&
5807 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005808 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattner70117952010-01-12 21:30:55 +00005809 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005810
Chris Lattnerfaa54172010-01-12 21:23:57 +00005811 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005812}
5813
Chris Lattnerfaa54172010-01-12 21:23:57 +00005814QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005815 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005816 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005817 if (lex->getType()->hasIntegerRepresentation() &&
5818 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005819 return CheckVectorOperands(Loc, lex, rex);
5820 return InvalidOperands(Loc, lex, rex);
5821 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005822
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005823 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005824
Chris Lattnerfaa54172010-01-12 21:23:57 +00005825 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
5826 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005827
Chris Lattnerfaa54172010-01-12 21:23:57 +00005828 // Check for remainder by zero.
5829 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00005830 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
5831 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005832
Chris Lattnerfaa54172010-01-12 21:23:57 +00005833 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005834}
5835
Chris Lattnerfaa54172010-01-12 21:23:57 +00005836QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00005837 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005838 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5839 QualType compType = CheckVectorOperands(Loc, lex, rex);
5840 if (CompLHSTy) *CompLHSTy = compType;
5841 return compType;
5842 }
Steve Naroff7a5af782007-07-13 16:58:59 +00005843
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005844 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00005845
Steve Naroffe4718892007-04-27 18:30:00 +00005846 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005847 if (lex->getType()->isArithmeticType() &&
5848 rex->getType()->isArithmeticType()) {
5849 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005850 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005851 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00005852
Eli Friedman8e122982008-05-18 18:08:51 +00005853 // Put any potential pointer into PExp
5854 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00005855 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00005856 std::swap(PExp, IExp);
5857
Steve Naroff6b712a72009-07-14 18:25:06 +00005858 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005859
Eli Friedman8e122982008-05-18 18:08:51 +00005860 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005861 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005862
Chris Lattner12bdebb2009-04-24 23:50:08 +00005863 // Check for arithmetic on pointers to incomplete types.
5864 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00005865 if (getLangOptions().CPlusPlus) {
5866 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00005867 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00005868 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005869 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005870
5871 // GNU extension: arithmetic on pointer to void
5872 Diag(Loc, diag::ext_gnu_void_ptr)
5873 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00005874 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00005875 if (getLangOptions().CPlusPlus) {
5876 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5877 << lex->getType() << lex->getSourceRange();
5878 return QualType();
5879 }
5880
5881 // GNU extension: arithmetic on pointer to function
5882 Diag(Loc, diag::ext_gnu_ptr_func_arith)
5883 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00005884 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005885 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00005886 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00005887 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005888 PExp->getType()->isObjCObjectPointerType()) &&
5889 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00005890 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5891 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005892 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005893 return QualType();
5894 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00005895 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005896 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005897 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5898 << PointeeTy << PExp->getSourceRange();
5899 return QualType();
5900 }
Mike Stump11289f42009-09-09 15:08:12 +00005901
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005902 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00005903 QualType LHSTy = Context.isPromotableBitField(lex);
5904 if (LHSTy.isNull()) {
5905 LHSTy = lex->getType();
5906 if (LHSTy->isPromotableIntegerType())
5907 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005908 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005909 *CompLHSTy = LHSTy;
5910 }
Eli Friedman8e122982008-05-18 18:08:51 +00005911 return PExp->getType();
5912 }
5913 }
5914
Chris Lattner326f7572008-11-18 01:30:42 +00005915 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005916}
5917
Chris Lattner2a3569b2008-04-07 05:30:13 +00005918// C99 6.5.6
5919QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005920 SourceLocation Loc, QualType* CompLHSTy) {
5921 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5922 QualType compType = CheckVectorOperands(Loc, lex, rex);
5923 if (CompLHSTy) *CompLHSTy = compType;
5924 return compType;
5925 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005926
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005927 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005928
Chris Lattner4d62f422007-12-09 21:53:25 +00005929 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005930
Chris Lattner4d62f422007-12-09 21:53:25 +00005931 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00005932 if (lex->getType()->isArithmeticType()
5933 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005934 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005935 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005936 }
Mike Stump11289f42009-09-09 15:08:12 +00005937
Chris Lattner4d62f422007-12-09 21:53:25 +00005938 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00005939 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00005940 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005941
Douglas Gregorac1fb652009-03-24 19:52:54 +00005942 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005943
Douglas Gregorac1fb652009-03-24 19:52:54 +00005944 bool ComplainAboutVoid = false;
5945 Expr *ComplainAboutFunc = 0;
5946 if (lpointee->isVoidType()) {
5947 if (getLangOptions().CPlusPlus) {
5948 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5949 << lex->getSourceRange() << rex->getSourceRange();
5950 return QualType();
5951 }
5952
5953 // GNU C extension: arithmetic on pointer to void
5954 ComplainAboutVoid = true;
5955 } else if (lpointee->isFunctionType()) {
5956 if (getLangOptions().CPlusPlus) {
5957 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005958 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005959 return QualType();
5960 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005961
5962 // GNU C extension: arithmetic on pointer to function
5963 ComplainAboutFunc = lex;
5964 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00005965 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005966 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00005967 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005968 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005969 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005970
Chris Lattner12bdebb2009-04-24 23:50:08 +00005971 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005972 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005973 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5974 << lpointee << lex->getSourceRange();
5975 return QualType();
5976 }
Mike Stump11289f42009-09-09 15:08:12 +00005977
Chris Lattner4d62f422007-12-09 21:53:25 +00005978 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00005979 if (rex->getType()->isIntegerType()) {
5980 if (ComplainAboutVoid)
5981 Diag(Loc, diag::ext_gnu_void_ptr)
5982 << lex->getSourceRange() << rex->getSourceRange();
5983 if (ComplainAboutFunc)
5984 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005985 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005986 << ComplainAboutFunc->getSourceRange();
5987
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005988 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005989 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005990 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005991
Chris Lattner4d62f422007-12-09 21:53:25 +00005992 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005993 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00005994 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005995
Douglas Gregorac1fb652009-03-24 19:52:54 +00005996 // RHS must be a completely-type object type.
5997 // Handle the GNU void* extension.
5998 if (rpointee->isVoidType()) {
5999 if (getLangOptions().CPlusPlus) {
6000 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6001 << lex->getSourceRange() << rex->getSourceRange();
6002 return QualType();
6003 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006004
Douglas Gregorac1fb652009-03-24 19:52:54 +00006005 ComplainAboutVoid = true;
6006 } else if (rpointee->isFunctionType()) {
6007 if (getLangOptions().CPlusPlus) {
6008 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006009 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006010 return QualType();
6011 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006012
6013 // GNU extension: arithmetic on pointer to function
6014 if (!ComplainAboutFunc)
6015 ComplainAboutFunc = rex;
6016 } else if (!rpointee->isDependentType() &&
6017 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006018 PDiag(diag::err_typecheck_sub_ptr_object)
6019 << rex->getSourceRange()
6020 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006021 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006022
Eli Friedman168fe152009-05-16 13:54:38 +00006023 if (getLangOptions().CPlusPlus) {
6024 // Pointee types must be the same: C++ [expr.add]
6025 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6026 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6027 << lex->getType() << rex->getType()
6028 << lex->getSourceRange() << rex->getSourceRange();
6029 return QualType();
6030 }
6031 } else {
6032 // Pointee types must be compatible C99 6.5.6p3
6033 if (!Context.typesAreCompatible(
6034 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6035 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6036 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6037 << lex->getType() << rex->getType()
6038 << lex->getSourceRange() << rex->getSourceRange();
6039 return QualType();
6040 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006041 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006042
Douglas Gregorac1fb652009-03-24 19:52:54 +00006043 if (ComplainAboutVoid)
6044 Diag(Loc, diag::ext_gnu_void_ptr)
6045 << lex->getSourceRange() << rex->getSourceRange();
6046 if (ComplainAboutFunc)
6047 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006048 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006049 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006050
6051 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006052 return Context.getPointerDiffType();
6053 }
6054 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006055
Chris Lattner326f7572008-11-18 01:30:42 +00006056 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006057}
6058
Douglas Gregor0bf31402010-10-08 23:50:27 +00006059static bool isScopedEnumerationType(QualType T) {
6060 if (const EnumType *ET = dyn_cast<EnumType>(T))
6061 return ET->getDecl()->isScoped();
6062 return false;
6063}
6064
Chris Lattner2a3569b2008-04-07 05:30:13 +00006065// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00006066QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00006067 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006068 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006069 if (!lex->getType()->hasIntegerRepresentation() ||
6070 !rex->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006071 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006072
Douglas Gregor0bf31402010-10-08 23:50:27 +00006073 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6074 // hasIntegerRepresentation() above instead of this.
6075 if (isScopedEnumerationType(lex->getType()) ||
6076 isScopedEnumerationType(rex->getType())) {
6077 return InvalidOperands(Loc, lex, rex);
6078 }
6079
Nate Begemane46ee9a2009-10-25 02:26:48 +00006080 // Vector shifts promote their scalar inputs to vector type.
6081 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6082 return CheckVectorOperands(Loc, lex, rex);
6083
Chris Lattner5c11c412007-12-12 05:47:28 +00006084 // Shifts don't perform usual arithmetic conversions, they just do integer
6085 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00006086 QualType LHSTy = Context.isPromotableBitField(lex);
6087 if (LHSTy.isNull()) {
6088 LHSTy = lex->getType();
6089 if (LHSTy->isPromotableIntegerType())
6090 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006091 }
Chris Lattner3c133402007-12-13 07:28:16 +00006092 if (!isCompAssign)
John McCalle3027922010-08-25 11:45:40 +00006093 ImpCastExprToType(lex, LHSTy, CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006094
Chris Lattner5c11c412007-12-12 05:47:28 +00006095 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006096
Ryan Flynnf53fab82009-08-07 16:20:20 +00006097 // Sanity-check shift operands
6098 llvm::APSInt Right;
6099 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00006100 if (!rex->isValueDependent() &&
6101 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00006102 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00006103 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6104 else {
6105 llvm::APInt LeftBits(Right.getBitWidth(),
6106 Context.getTypeSize(lex->getType()));
6107 if (Right.uge(LeftBits))
6108 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6109 }
6110 }
6111
Chris Lattner5c11c412007-12-12 05:47:28 +00006112 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006113 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006114}
6115
Chandler Carruth17773fc2010-07-10 12:30:03 +00006116static bool IsWithinTemplateSpecialization(Decl *D) {
6117 if (DeclContext *DC = D->getDeclContext()) {
6118 if (isa<ClassTemplateSpecializationDecl>(DC))
6119 return true;
6120 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6121 return FD->isFunctionTemplateSpecialization();
6122 }
6123 return false;
6124}
6125
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006126// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00006127QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006128 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006129 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006130
Chris Lattner9a152e22009-12-05 05:40:13 +00006131 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00006132 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006133 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006134
Steve Naroff31090012007-07-16 21:54:35 +00006135 QualType lType = lex->getType();
6136 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006137
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006138 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006139 !(lType->isBlockPointerType() && isRelational) &&
6140 !lex->getLocStart().isMacroID() &&
6141 !rex->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006142 // For non-floating point types, check for self-comparisons of the form
6143 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6144 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006145 //
6146 // NOTE: Don't warn about comparison expressions resulting from macro
6147 // expansion. Also don't warn about comparisons which are only self
6148 // comparisons within a template specialization. The warnings should catch
6149 // obvious cases in the definition of the template anyways. The idea is to
6150 // warn when the typed comparison operator will always evaluate to the same
6151 // result.
Chris Lattner222b8bd2009-03-08 19:39:53 +00006152 Expr *LHSStripped = lex->IgnoreParens();
6153 Expr *RHSStripped = rex->IgnoreParens();
Chandler Carruth17773fc2010-07-10 12:30:03 +00006154 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006155 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006156 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006157 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006158 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6159 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006160 << (Opc == BO_EQ
6161 || Opc == BO_LE
6162 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006163 } else if (lType->isArrayType() && rType->isArrayType() &&
6164 !DRL->getDecl()->getType()->isReferenceType() &&
6165 !DRR->getDecl()->getType()->isReferenceType()) {
6166 // what is it always going to eval to?
6167 char always_evals_to;
6168 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006169 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006170 always_evals_to = 0; // false
6171 break;
John McCalle3027922010-08-25 11:45:40 +00006172 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006173 always_evals_to = 1; // true
6174 break;
6175 default:
6176 // best we can say is 'a constant'
6177 always_evals_to = 2; // e.g. array1 <= array2
6178 break;
6179 }
6180 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6181 << 1 // array
6182 << always_evals_to);
6183 }
6184 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006185 }
Mike Stump11289f42009-09-09 15:08:12 +00006186
Chris Lattner222b8bd2009-03-08 19:39:53 +00006187 if (isa<CastExpr>(LHSStripped))
6188 LHSStripped = LHSStripped->IgnoreParenCasts();
6189 if (isa<CastExpr>(RHSStripped))
6190 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006191
Chris Lattner222b8bd2009-03-08 19:39:53 +00006192 // Warn about comparisons against a string constant (unless the other
6193 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006194 Expr *literalString = 0;
6195 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006196 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006197 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006198 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006199 literalString = lex;
6200 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006201 } else if ((isa<StringLiteral>(RHSStripped) ||
6202 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006203 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006204 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006205 literalString = rex;
6206 literalStringStripped = RHSStripped;
6207 }
6208
6209 if (literalString) {
6210 std::string resultComparison;
6211 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006212 case BO_LT: resultComparison = ") < 0"; break;
6213 case BO_GT: resultComparison = ") > 0"; break;
6214 case BO_LE: resultComparison = ") <= 0"; break;
6215 case BO_GE: resultComparison = ") >= 0"; break;
6216 case BO_EQ: resultComparison = ") == 0"; break;
6217 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006218 default: assert(false && "Invalid comparison operator");
6219 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006220
Douglas Gregor49862b82010-01-12 23:18:54 +00006221 DiagRuntimeBehavior(Loc,
6222 PDiag(diag::warn_stringcompare)
6223 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006224 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006225 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006226 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006227
Douglas Gregorec170db2010-06-08 19:50:34 +00006228 // C99 6.5.8p3 / C99 6.5.9p4
6229 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6230 UsualArithmeticConversions(lex, rex);
6231 else {
6232 UsualUnaryConversions(lex);
6233 UsualUnaryConversions(rex);
6234 }
6235
6236 lType = lex->getType();
6237 rType = rex->getType();
6238
Douglas Gregorca63811b2008-11-19 03:25:36 +00006239 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00006240 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00006241
Chris Lattnerb620c342007-08-26 01:18:55 +00006242 if (isRelational) {
6243 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006244 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006245 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006246 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006247 if (lType->hasFloatingRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006248 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006249
Chris Lattnerb620c342007-08-26 01:18:55 +00006250 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006251 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006252 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006253
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006254 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006255 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006256 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006257 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006258
Douglas Gregorf267edd2010-06-15 21:38:40 +00006259 // All of the following pointer-related warnings are GCC extensions, except
6260 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006261 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006262 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006263 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006264 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006265 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006266
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006267 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006268 if (LCanPointeeTy == RCanPointeeTy)
6269 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006270 if (!isRelational &&
6271 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6272 // Valid unless comparison between non-null pointer and function pointer
6273 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006274 // In a SFINAE context, we treat this as a hard error to maintain
6275 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006276 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6277 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006278 Diag(Loc,
6279 isSFINAEContext()?
6280 diag::err_typecheck_comparison_of_fptr_to_void
6281 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006282 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006283
6284 if (isSFINAEContext())
6285 return QualType();
6286
John McCalle3027922010-08-25 11:45:40 +00006287 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006288 return ResultTy;
6289 }
6290 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006291
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006292 // C++ [expr.rel]p2:
6293 // [...] Pointer conversions (4.10) and qualification
6294 // conversions (4.4) are performed on pointer operands (or on
6295 // a pointer operand and a null pointer constant) to bring
6296 // them to their composite pointer type. [...]
6297 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006298 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006299 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006300 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006301 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006302 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006303 if (T.isNull()) {
6304 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6305 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6306 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006307 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006308 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006309 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006310 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006311 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006312 }
6313
John McCalle3027922010-08-25 11:45:40 +00006314 ImpCastExprToType(lex, T, CK_BitCast);
6315 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006316 return ResultTy;
6317 }
Eli Friedman16c209612009-08-23 00:27:47 +00006318 // C99 6.5.9p2 and C99 6.5.8p2
6319 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6320 RCanPointeeTy.getUnqualifiedType())) {
6321 // Valid unless a relational comparison of function pointers
6322 if (isRelational && LCanPointeeTy->isFunctionType()) {
6323 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6324 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6325 }
6326 } else if (!isRelational &&
6327 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6328 // Valid unless comparison between non-null pointer and function pointer
6329 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6330 && !LHSIsNull && !RHSIsNull) {
6331 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6332 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6333 }
6334 } else {
6335 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006336 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006337 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006338 }
Eli Friedman16c209612009-08-23 00:27:47 +00006339 if (LCanPointeeTy != RCanPointeeTy)
John McCalle3027922010-08-25 11:45:40 +00006340 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006341 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006342 }
Mike Stump11289f42009-09-09 15:08:12 +00006343
Sebastian Redl576fd422009-05-10 18:38:11 +00006344 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006345 // Comparison of nullptr_t with itself.
6346 if (lType->isNullPtrType() && rType->isNullPtrType())
6347 return ResultTy;
6348
Mike Stump11289f42009-09-09 15:08:12 +00006349 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006350 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006351 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006352 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006353 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006354 ImpCastExprToType(rex, lType,
6355 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006356 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006357 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006358 return ResultTy;
6359 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006360 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006361 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006362 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006363 ImpCastExprToType(lex, rType,
6364 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006365 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006366 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006367 return ResultTy;
6368 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006369
6370 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006371 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006372 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6373 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006374 // In addition, pointers to members can be compared, or a pointer to
6375 // member and a null pointer constant. Pointer to member conversions
6376 // (4.11) and qualification conversions (4.4) are performed to bring
6377 // them to a common type. If one operand is a null pointer constant,
6378 // the common type is the type of the other operand. Otherwise, the
6379 // common type is a pointer to member type similar (4.4) to the type
6380 // of one of the operands, with a cv-qualification signature (4.4)
6381 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006382 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006383 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006384 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006385 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006386 if (T.isNull()) {
6387 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006388 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006389 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006390 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006391 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006392 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006393 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006394 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006395 }
Mike Stump11289f42009-09-09 15:08:12 +00006396
John McCalle3027922010-08-25 11:45:40 +00006397 ImpCastExprToType(lex, T, CK_BitCast);
6398 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006399 return ResultTy;
6400 }
Sebastian Redl576fd422009-05-10 18:38:11 +00006401 }
Mike Stump11289f42009-09-09 15:08:12 +00006402
Steve Naroff081c7422008-09-04 15:10:53 +00006403 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00006404 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006405 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6406 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006407
Steve Naroff081c7422008-09-04 15:10:53 +00006408 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006409 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006410 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006411 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006412 }
John McCalle3027922010-08-25 11:45:40 +00006413 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006414 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006415 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00006416 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006417 if (!isRelational
6418 && ((lType->isBlockPointerType() && rType->isPointerType())
6419 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006420 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006421 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006422 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006423 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006424 ->getPointeeType()->isVoidType())))
6425 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6426 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006427 }
John McCalle3027922010-08-25 11:45:40 +00006428 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006429 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006430 }
Steve Naroff081c7422008-09-04 15:10:53 +00006431
Steve Naroff7cae42b2009-07-10 23:34:53 +00006432 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006433 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006434 const PointerType *LPT = lType->getAs<PointerType>();
6435 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006436 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00006437 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006438 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00006439 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006440
Steve Naroff753567f2008-11-17 19:49:16 +00006441 if (!LPtrToVoid && !RPtrToVoid &&
6442 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006443 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006444 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006445 }
John McCalle3027922010-08-25 11:45:40 +00006446 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006447 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006448 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006449 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006450 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006451 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6452 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006453 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006454 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006455 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006456 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006457 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6458 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006459 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006460 bool isError = false;
6461 if ((LHSIsNull && lType->isIntegerType()) ||
6462 (RHSIsNull && rType->isIntegerType())) {
6463 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006464 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006465 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006466 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006467 else if (getLangOptions().CPlusPlus) {
6468 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6469 isError = true;
6470 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006471 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006472
Chris Lattnerd99bd522009-08-23 00:03:44 +00006473 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006474 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00006475 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006476 if (isError)
6477 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006478 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006479
6480 if (lType->isIntegerType())
John McCalle84af4e2010-11-13 01:35:44 +00006481 ImpCastExprToType(lex, rType,
6482 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006483 else
John McCalle84af4e2010-11-13 01:35:44 +00006484 ImpCastExprToType(rex, lType,
6485 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006486 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006487 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006488
Steve Naroff4b191572008-09-04 16:56:14 +00006489 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006490 if (!isRelational && RHSIsNull
6491 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00006492 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006493 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006494 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006495 if (!isRelational && LHSIsNull
6496 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00006497 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006498 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006499 }
Chris Lattner326f7572008-11-18 01:30:42 +00006500 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006501}
6502
Nate Begeman191a6b12008-07-14 18:02:46 +00006503/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006504/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006505/// like a scalar comparison, a vector comparison produces a vector of integer
6506/// types.
6507QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00006508 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006509 bool isRelational) {
6510 // Check to make sure we're operating on vectors of the same type and width,
6511 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00006512 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00006513 if (vType.isNull())
6514 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006515
Anton Yartsev3f8f2882010-11-18 03:19:30 +00006516 // If AltiVec, the comparison results in a numeric type, i.e.
6517 // bool for C++, int for C
6518 if (getLangOptions().AltiVec)
6519 return (getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy);
6520
Nate Begeman191a6b12008-07-14 18:02:46 +00006521 QualType lType = lex->getType();
6522 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006523
Nate Begeman191a6b12008-07-14 18:02:46 +00006524 // For non-floating point types, check for self-comparisons of the form
6525 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6526 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006527 if (!lType->hasFloatingRepresentation()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006528 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
6529 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
6530 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregorec170db2010-06-08 19:50:34 +00006531 DiagRuntimeBehavior(Loc,
6532 PDiag(diag::warn_comparison_always)
6533 << 0 // self-
6534 << 2 // "a constant"
6535 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006536 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006537
Nate Begeman191a6b12008-07-14 18:02:46 +00006538 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006539 if (!isRelational && lType->hasFloatingRepresentation()) {
6540 assert (rType->hasFloatingRepresentation());
Chris Lattner326f7572008-11-18 01:30:42 +00006541 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00006542 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006543
Nate Begeman191a6b12008-07-14 18:02:46 +00006544 // Return the type for the comparison, which is the same as vector type for
6545 // integer vectors, or an integer type of identical size and number of
6546 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006547 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00006548 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006549
John McCall9dd450b2009-09-21 23:43:11 +00006550 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006551 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006552 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006553 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006554 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006555 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6556
Mike Stump4e1f26a2009-02-19 03:04:26 +00006557 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006558 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006559 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6560}
6561
Steve Naroff218bc2b2007-05-04 21:54:46 +00006562inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00006563 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006564 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6565 if (lex->getType()->hasIntegerRepresentation() &&
6566 rex->getType()->hasIntegerRepresentation())
6567 return CheckVectorOperands(Loc, lex, rex);
6568
6569 return InvalidOperands(Loc, lex, rex);
6570 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006571
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006572 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006573
Douglas Gregor0bf31402010-10-08 23:50:27 +00006574 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
6575 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006576 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00006577 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006578}
6579
Steve Naroff218bc2b2007-05-04 21:54:46 +00006580inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner8406c512010-07-13 19:41:32 +00006581 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
6582
6583 // Diagnose cases where the user write a logical and/or but probably meant a
6584 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6585 // is a constant.
6586 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman6b197e02010-07-27 19:14:53 +00006587 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00006588 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00006589 !Loc.isMacroID()) {
6590 // If the RHS can be constant folded, and if it constant folds to something
6591 // that isn't 0 or 1 (which indicate a potential logical operation that
6592 // happened to fold to true/false) then warn.
6593 Expr::EvalResult Result;
6594 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
6595 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
6596 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6597 << rex->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00006598 << (Opc == BO_LAnd ? "&&" : "||")
6599 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00006600 }
6601 }
Chris Lattner8406c512010-07-13 19:41:32 +00006602
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006603 if (!Context.getLangOptions().CPlusPlus) {
6604 UsualUnaryConversions(lex);
6605 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006606
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006607 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
6608 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006609
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006610 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006611 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006612
John McCall4a2429a2010-06-04 00:29:51 +00006613 // The following is safe because we only use this method for
6614 // non-overloadable operands.
6615
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006616 // C++ [expr.log.and]p1
6617 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006618 // The operands are both contextually converted to type bool.
6619 if (PerformContextuallyConvertToBool(lex) ||
6620 PerformContextuallyConvertToBool(rex))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006621 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006622
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006623 // C++ [expr.log.and]p2
6624 // C++ [expr.log.or]p2
6625 // The result is a bool.
6626 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006627}
6628
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006629/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6630/// is a read-only property; return true if so. A readonly property expression
6631/// depends on various declarations and thus must be treated specially.
6632///
Mike Stump11289f42009-09-09 15:08:12 +00006633static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006634 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6635 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6636 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006637 QualType BaseType = PropExpr->isSuperReceiver() ?
6638 PropExpr->getSuperType() :
6639 PropExpr->getBase()->getType();
6640
Mike Stump11289f42009-09-09 15:08:12 +00006641 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00006642 BaseType->getAsObjCInterfacePointerType())
6643 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6644 if (S.isPropertyReadonly(PDecl, IFace))
6645 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006646 }
6647 }
6648 return false;
6649}
6650
Chris Lattner30bd3272008-11-18 01:22:49 +00006651/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6652/// emit an error and return true. If so, return false.
6653static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006654 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006655 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006656 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006657 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6658 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00006659 if (IsLV == Expr::MLV_Valid)
6660 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006661
Chris Lattner30bd3272008-11-18 01:22:49 +00006662 unsigned Diag = 0;
6663 bool NeedType = false;
6664 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00006665 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006666 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006667 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6668 NeedType = true;
6669 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006670 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006671 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6672 NeedType = true;
6673 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006674 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006675 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6676 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006677 case Expr::MLV_Valid:
6678 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006679 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006680 case Expr::MLV_MemberFunction:
6681 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006682 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6683 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006684 case Expr::MLV_IncompleteType:
6685 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006686 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006687 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006688 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006689 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006690 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6691 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006692 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006693 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6694 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006695 case Expr::MLV_ReadonlyProperty:
6696 Diag = diag::error_readonly_property_assignment;
6697 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006698 case Expr::MLV_NoSetterProperty:
6699 Diag = diag::error_nosetter_property_assignment;
6700 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006701 case Expr::MLV_SubObjCPropertySetting:
6702 Diag = diag::error_no_subobject_property_setting;
6703 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006704 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006705
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006706 SourceRange Assign;
6707 if (Loc != OrigLoc)
6708 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006709 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006710 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006711 else
Mike Stump11289f42009-09-09 15:08:12 +00006712 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006713 return true;
6714}
6715
6716
6717
6718// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00006719QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
6720 SourceLocation Loc,
6721 QualType CompoundType) {
6722 // Verify that LHS is a modifiable lvalue, and emit error if not.
6723 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00006724 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00006725
6726 QualType LHSType = LHS->getType();
6727 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006728 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00006729 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006730 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006731 // Simple assignment "x = y".
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00006732 ConvertPropertyAssignment(LHS, RHS, LHSTy);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006733 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006734 // Special case of NSObject attributes on c-style pointer types.
6735 if (ConvTy == IncompatiblePointer &&
6736 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006737 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006738 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006739 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006740 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006741
John McCall7decc9e2010-11-18 06:31:45 +00006742 if (ConvTy == Compatible &&
6743 getLangOptions().ObjCNonFragileABI &&
6744 LHSType->isObjCObjectType())
6745 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6746 << LHSType;
6747
Chris Lattnerea714382008-08-21 18:04:13 +00006748 // If the RHS is a unary plus or minus, check to see if they = and + are
6749 // right next to each other. If so, the user may have typo'd "x =+ 4"
6750 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00006751 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00006752 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6753 RHSCheck = ICE->getSubExpr();
6754 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00006755 if ((UO->getOpcode() == UO_Plus ||
6756 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00006757 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00006758 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00006759 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6760 // And there is a space or other character before the subexpr of the
6761 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00006762 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6763 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006764 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00006765 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00006766 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00006767 }
Chris Lattnerea714382008-08-21 18:04:13 +00006768 }
6769 } else {
6770 // Compound assignment "x += y"
John McCall29600e12010-11-16 02:32:08 +00006771 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006772 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006773
Chris Lattner326f7572008-11-18 01:30:42 +00006774 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006775 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00006776 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006777
Chris Lattner39561062010-07-07 06:14:23 +00006778
6779 // Check to see if the destination operand is a dereferenced null pointer. If
6780 // so, and if not volatile-qualified, this is undefined behavior that the
6781 // optimizer will delete, so warn about it. People sometimes try to use this
6782 // to get a deterministic trap and are surprised by clang's behavior. This
6783 // only handles the pattern "*null = whatever", which is a very syntactic
6784 // check.
6785 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCalle3027922010-08-25 11:45:40 +00006786 if (UO->getOpcode() == UO_Deref &&
Chris Lattner39561062010-07-07 06:14:23 +00006787 UO->getSubExpr()->IgnoreParenCasts()->
6788 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
6789 !UO->getType().isVolatileQualified()) {
6790 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
6791 << UO->getSubExpr()->getSourceRange();
6792 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
6793 }
6794
Steve Naroff98cf3e92007-06-06 18:38:38 +00006795 // C99 6.5.16p3: The type of an assignment expression is the type of the
6796 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00006797 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00006798 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6799 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00006800 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00006801 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00006802 return (getLangOptions().CPlusPlus
6803 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00006804}
6805
Chris Lattner326f7572008-11-18 01:30:42 +00006806// C99 6.5.17
John McCall4bc41ae2010-11-18 19:01:18 +00006807static QualType CheckCommaOperands(Sema &S, Expr *LHS, Expr *&RHS,
6808 SourceLocation Loc) {
6809 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00006810
John McCall4bc41ae2010-11-18 19:01:18 +00006811 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006812 if (LHSResult.isInvalid())
6813 return QualType();
6814
John McCall4bc41ae2010-11-18 19:01:18 +00006815 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006816 if (RHSResult.isInvalid())
6817 return QualType();
6818 RHS = RHSResult.take();
6819
John McCall73d36182010-10-12 07:14:40 +00006820 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
6821 // operands, but not unary promotions.
6822 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
John McCall4bc41ae2010-11-18 19:01:18 +00006823 if (!S.getLangOptions().CPlusPlus) {
6824 S.DefaultFunctionArrayLvalueConversion(LHS);
John McCall73d36182010-10-12 07:14:40 +00006825 if (!LHS->getType()->isVoidType())
John McCall4bc41ae2010-11-18 19:01:18 +00006826 S.RequireCompleteType(Loc, LHS->getType(), diag::err_incomplete_type);
Eli Friedmanba961a92009-03-23 00:24:07 +00006827
John McCall4bc41ae2010-11-18 19:01:18 +00006828 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCall73d36182010-10-12 07:14:40 +00006829 if (!RHS->getType()->isVoidType())
John McCall4bc41ae2010-11-18 19:01:18 +00006830 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00006831 }
Eli Friedmanba961a92009-03-23 00:24:07 +00006832
Chris Lattner326f7572008-11-18 01:30:42 +00006833 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00006834}
6835
Steve Naroff7a5af782007-07-13 16:58:59 +00006836/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6837/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00006838static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
6839 ExprValueKind &VK,
6840 SourceLocation OpLoc,
6841 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006842 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00006843 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006844
Chris Lattner6b0cf142008-11-21 07:05:48 +00006845 QualType ResType = Op->getType();
6846 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00006847
John McCall4bc41ae2010-11-18 19:01:18 +00006848 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00006849 // Decrement of bool is not allowed.
6850 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00006851 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00006852 return QualType();
6853 }
6854 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00006855 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00006856 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006857 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00006858 } else if (ResType->isAnyPointerType()) {
6859 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006860
Chris Lattner6b0cf142008-11-21 07:05:48 +00006861 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00006862 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00006863 if (S.getLangOptions().CPlusPlus) {
6864 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006865 << Op->getSourceRange();
6866 return QualType();
6867 }
6868
6869 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00006870 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006871 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00006872 if (S.getLangOptions().CPlusPlus) {
6873 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006874 << Op->getType() << Op->getSourceRange();
6875 return QualType();
6876 }
6877
John McCall4bc41ae2010-11-18 19:01:18 +00006878 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006879 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00006880 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
6881 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00006882 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006883 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00006884 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006885 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00006886 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
6887 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006888 << PointeeTy << Op->getSourceRange();
6889 return QualType();
6890 }
Eli Friedman090addd2010-01-03 00:20:48 +00006891 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006892 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00006893 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006894 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00006895 } else if (ResType->isPlaceholderType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00006896 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00006897 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00006898 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
6899 isInc, isPrefix);
Chris Lattner6b0cf142008-11-21 07:05:48 +00006900 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00006901 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00006902 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00006903 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00006904 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006905 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00006906 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00006907 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00006908 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00006909 // In C++, a prefix increment is the same type as the operand. Otherwise
6910 // (in C or with postfix), the increment is the unqualified type of the
6911 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00006912 if (isPrefix && S.getLangOptions().CPlusPlus) {
6913 VK = VK_LValue;
6914 return ResType;
6915 } else {
6916 VK = VK_RValue;
6917 return ResType.getUnqualifiedType();
6918 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00006919}
6920
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00006921void Sema::ConvertPropertyAssignment(Expr *LHS, Expr *&RHS, QualType& LHSTy) {
6922 bool copyInit = false;
6923 if (const ObjCImplicitSetterGetterRefExpr *OISGE =
6924 dyn_cast<ObjCImplicitSetterGetterRefExpr>(LHS)) {
6925 // If using property-dot syntax notation for assignment, and there is a
6926 // setter, RHS expression is being passed to the setter argument. So,
6927 // type conversion (and comparison) is RHS to setter's argument type.
6928 if (const ObjCMethodDecl *SetterMD = OISGE->getSetterMethod()) {
6929 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
6930 LHSTy = (*P)->getType();
6931 }
6932 copyInit = (getLangOptions().CPlusPlus && LHSTy->isRecordType());
6933 }
6934 else
6935 copyInit = (getLangOptions().CPlusPlus && isa<ObjCPropertyRefExpr>(LHS) &&
6936 LHSTy->isRecordType());
6937 if (copyInit) {
6938 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00006939 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00006940 Expr *Arg = RHS;
6941 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
6942 Owned(Arg));
6943 if (!ArgE.isInvalid())
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00006944 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00006945 }
6946}
6947
6948
Anders Carlsson806700f2008-02-01 07:15:58 +00006949/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00006950/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00006951/// where the declaration is needed for type checking. We only need to
6952/// handle cases when the expression references a function designator
6953/// or is an lvalue. Here are some examples:
6954/// - &(x) => x
6955/// - &*****f => f for f a function designator.
6956/// - &s.xx => s
6957/// - &s.zz[1].yy -> s, if zz is an array
6958/// - *(x + 1) -> x, if x is an array
6959/// - &"123"[2] -> 0
6960/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006961static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006962 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00006963 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006964 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00006965 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00006966 // If this is an arrow operator, the address is an offset from
6967 // the base's value, so the object the base refers to is
6968 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006969 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00006970 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00006971 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006972 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00006973 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00006974 // FIXME: This code shouldn't be necessary! We should catch the implicit
6975 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00006976 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
6977 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
6978 if (ICE->getSubExpr()->getType()->isArrayType())
6979 return getPrimaryDecl(ICE->getSubExpr());
6980 }
6981 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00006982 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00006983 case Stmt::UnaryOperatorClass: {
6984 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006985
Daniel Dunbarb692ef42008-08-04 20:02:37 +00006986 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00006987 case UO_Real:
6988 case UO_Imag:
6989 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00006990 return getPrimaryDecl(UO->getSubExpr());
6991 default:
6992 return 0;
6993 }
6994 }
Steve Naroff47500512007-04-19 23:00:49 +00006995 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006996 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00006997 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00006998 // If the result of an implicit cast is an l-value, we care about
6999 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007000 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007001 default:
7002 return 0;
7003 }
7004}
7005
7006/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007007/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007008/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007009/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007010/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007011/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007012/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007013static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7014 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007015 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007016 return S.Context.DependentTy;
7017 if (OrigOp->getType() == S.Context.OverloadTy)
7018 return S.Context.OverloadTy;
John McCall8d08b9b2010-08-27 09:08:28 +00007019
John McCall4bc41ae2010-11-18 19:01:18 +00007020 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007021 if (PR.isInvalid()) return QualType();
7022 OrigOp = PR.take();
7023
John McCall8d08b9b2010-08-27 09:08:28 +00007024 // Make sure to ignore parentheses in subsequent checks
7025 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007026
John McCall4bc41ae2010-11-18 19:01:18 +00007027 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007028 // Implement C99-only parts of addressof rules.
7029 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007030 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007031 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7032 // (assuming the deref expression is valid).
7033 return uOp->getSubExpr()->getType();
7034 }
7035 // Technically, there should be a check for array subscript
7036 // expressions here, but the result of one is always an lvalue anyway.
7037 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007038 NamedDecl *dcl = getPrimaryDecl(op);
John McCall4bc41ae2010-11-18 19:01:18 +00007039 Expr::isLvalueResult lval = op->isLvalue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007040
Chris Lattner9156f1b2010-07-05 19:17:26 +00007041 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007042 bool sfinae = S.isSFINAEContext();
7043 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7044 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007045 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007046 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007047 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007048 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007049 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007050 } else if (lval == Expr::LV_MemberFunction) {
7051 // If it's an instance method, make a member pointer.
7052 // The expression must have exactly the form &A::foo.
7053
7054 // If the underlying expression isn't a decl ref, give up.
7055 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007056 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007057 << OrigOp->getSourceRange();
7058 return QualType();
7059 }
7060 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7061 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7062
7063 // The id-expression was parenthesized.
7064 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007065 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007066 << OrigOp->getSourceRange();
7067
7068 // The method was named without a qualifier.
7069 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007070 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007071 << op->getSourceRange();
7072 }
7073
John McCall4bc41ae2010-11-18 19:01:18 +00007074 return S.Context.getMemberPointerType(op->getType(),
7075 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007076 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007077 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007078 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007079 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007080 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007081 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007082 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007083 return QualType();
7084 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00007085 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007086 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007087 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007088 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007089 return QualType();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00007090 } else if (op->refersToVectorElement()) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007091 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007092 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007093 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007094 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00007095 } else if (isa<ObjCPropertyRefExpr>(op)) {
7096 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007097 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007098 << "property expression" << op->getSourceRange();
7099 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00007100 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
7101 // FIXME: Can LHS ever be null here?
John McCall4bc41ae2010-11-18 19:01:18 +00007102 if (!CheckAddressOfOperand(S, CO->getTrueExpr(), OpLoc).isNull())
7103 return CheckAddressOfOperand(S, CO->getFalseExpr(), OpLoc);
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007104 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007105 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007106 // with the register storage-class specifier.
7107 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007108 // in C++ it is not error to take address of a register
7109 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007110 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007111 !S.getLangOptions().CPlusPlus) {
7112 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007113 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007114 return QualType();
7115 }
John McCalld14a8642009-11-21 08:51:07 +00007116 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007117 return S.Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00007118 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007119 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007120 // Could be a pointer to member, though, if there is an explicit
7121 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007122 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007123 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007124 if (Ctx && Ctx->isRecord()) {
7125 if (FD->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007126 S.Diag(OpLoc,
7127 diag::err_cannot_form_pointer_to_member_of_reference_type)
Anders Carlsson0b675f52009-07-08 21:45:58 +00007128 << FD->getDeclName() << FD->getType();
7129 return QualType();
7130 }
Mike Stump11289f42009-09-09 15:08:12 +00007131
John McCall4bc41ae2010-11-18 19:01:18 +00007132 return S.Context.getMemberPointerType(op->getType(),
7133 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007134 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007135 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007136 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007137 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007138 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007139
Eli Friedmance7f9002009-05-16 23:27:50 +00007140 if (lval == Expr::LV_IncompleteVoidType) {
7141 // Taking the address of a void variable is technically illegal, but we
7142 // allow it in cases which are otherwise valid.
7143 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007144 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007145 }
7146
Steve Naroff47500512007-04-19 23:00:49 +00007147 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007148 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007149 return S.Context.getObjCObjectPointerType(op->getType());
7150 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007151}
7152
Chris Lattner9156f1b2010-07-05 19:17:26 +00007153/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007154static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7155 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007156 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007157 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007158
John McCall4bc41ae2010-11-18 19:01:18 +00007159 S.UsualUnaryConversions(Op);
Chris Lattner9156f1b2010-07-05 19:17:26 +00007160 QualType OpTy = Op->getType();
7161 QualType Result;
7162
7163 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7164 // is an incomplete type or void. It would be possible to warn about
7165 // dereferencing a void pointer, but it's completely well-defined, and such a
7166 // warning is unlikely to catch any mistakes.
7167 if (const PointerType *PT = OpTy->getAs<PointerType>())
7168 Result = PT->getPointeeType();
7169 else if (const ObjCObjectPointerType *OPT =
7170 OpTy->getAs<ObjCObjectPointerType>())
7171 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007172 else {
John McCall4bc41ae2010-11-18 19:01:18 +00007173 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007174 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007175 if (PR.take() != Op)
7176 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007177 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007178
Chris Lattner9156f1b2010-07-05 19:17:26 +00007179 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007180 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007181 << OpTy << Op->getSourceRange();
7182 return QualType();
7183 }
John McCall4bc41ae2010-11-18 19:01:18 +00007184
7185 // Dereferences are usually l-values...
7186 VK = VK_LValue;
7187
7188 // ...except that certain expressions are never l-values in C.
7189 if (!S.getLangOptions().CPlusPlus &&
7190 IsCForbiddenLValueType(S.Context, Result))
7191 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007192
7193 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007194}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007195
John McCalle3027922010-08-25 11:45:40 +00007196static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007197 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007198 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007199 switch (Kind) {
7200 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007201 case tok::periodstar: Opc = BO_PtrMemD; break;
7202 case tok::arrowstar: Opc = BO_PtrMemI; break;
7203 case tok::star: Opc = BO_Mul; break;
7204 case tok::slash: Opc = BO_Div; break;
7205 case tok::percent: Opc = BO_Rem; break;
7206 case tok::plus: Opc = BO_Add; break;
7207 case tok::minus: Opc = BO_Sub; break;
7208 case tok::lessless: Opc = BO_Shl; break;
7209 case tok::greatergreater: Opc = BO_Shr; break;
7210 case tok::lessequal: Opc = BO_LE; break;
7211 case tok::less: Opc = BO_LT; break;
7212 case tok::greaterequal: Opc = BO_GE; break;
7213 case tok::greater: Opc = BO_GT; break;
7214 case tok::exclaimequal: Opc = BO_NE; break;
7215 case tok::equalequal: Opc = BO_EQ; break;
7216 case tok::amp: Opc = BO_And; break;
7217 case tok::caret: Opc = BO_Xor; break;
7218 case tok::pipe: Opc = BO_Or; break;
7219 case tok::ampamp: Opc = BO_LAnd; break;
7220 case tok::pipepipe: Opc = BO_LOr; break;
7221 case tok::equal: Opc = BO_Assign; break;
7222 case tok::starequal: Opc = BO_MulAssign; break;
7223 case tok::slashequal: Opc = BO_DivAssign; break;
7224 case tok::percentequal: Opc = BO_RemAssign; break;
7225 case tok::plusequal: Opc = BO_AddAssign; break;
7226 case tok::minusequal: Opc = BO_SubAssign; break;
7227 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7228 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7229 case tok::ampequal: Opc = BO_AndAssign; break;
7230 case tok::caretequal: Opc = BO_XorAssign; break;
7231 case tok::pipeequal: Opc = BO_OrAssign; break;
7232 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007233 }
7234 return Opc;
7235}
7236
John McCalle3027922010-08-25 11:45:40 +00007237static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007238 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007239 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007240 switch (Kind) {
7241 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007242 case tok::plusplus: Opc = UO_PreInc; break;
7243 case tok::minusminus: Opc = UO_PreDec; break;
7244 case tok::amp: Opc = UO_AddrOf; break;
7245 case tok::star: Opc = UO_Deref; break;
7246 case tok::plus: Opc = UO_Plus; break;
7247 case tok::minus: Opc = UO_Minus; break;
7248 case tok::tilde: Opc = UO_Not; break;
7249 case tok::exclaim: Opc = UO_LNot; break;
7250 case tok::kw___real: Opc = UO_Real; break;
7251 case tok::kw___imag: Opc = UO_Imag; break;
7252 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007253 }
7254 return Opc;
7255}
7256
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007257/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7258/// operator @p Opc at location @c TokLoc. This routine only supports
7259/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007260ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007261 unsigned Op,
7262 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007263 QualType ResultTy; // Result type of the binary operator.
John McCalle3027922010-08-25 11:45:40 +00007264 BinaryOperatorKind Opc = (BinaryOperatorKind) Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007265 // The following two variables are used for compound assignment operators
7266 QualType CompLHSTy; // Type of LHS after promotions for computation
7267 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007268 ExprValueKind VK = VK_RValue;
7269 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007270
7271 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007272 case BO_Assign:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007273 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCall7decc9e2010-11-18 06:31:45 +00007274 if (getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007275 VK = lhs->getValueKind();
7276 OK = lhs->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007277 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007278 break;
John McCalle3027922010-08-25 11:45:40 +00007279 case BO_PtrMemD:
7280 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007281 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007282 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007283 break;
John McCalle3027922010-08-25 11:45:40 +00007284 case BO_Mul:
7285 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007286 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007287 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007288 break;
John McCalle3027922010-08-25 11:45:40 +00007289 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007290 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7291 break;
John McCalle3027922010-08-25 11:45:40 +00007292 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007293 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7294 break;
John McCalle3027922010-08-25 11:45:40 +00007295 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007296 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7297 break;
John McCalle3027922010-08-25 11:45:40 +00007298 case BO_Shl:
7299 case BO_Shr:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007300 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
7301 break;
John McCalle3027922010-08-25 11:45:40 +00007302 case BO_LE:
7303 case BO_LT:
7304 case BO_GE:
7305 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007306 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007307 break;
John McCalle3027922010-08-25 11:45:40 +00007308 case BO_EQ:
7309 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007310 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007311 break;
John McCalle3027922010-08-25 11:45:40 +00007312 case BO_And:
7313 case BO_Xor:
7314 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007315 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7316 break;
John McCalle3027922010-08-25 11:45:40 +00007317 case BO_LAnd:
7318 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007319 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007320 break;
John McCalle3027922010-08-25 11:45:40 +00007321 case BO_MulAssign:
7322 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007323 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007324 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007325 CompLHSTy = CompResultTy;
7326 if (!CompResultTy.isNull())
7327 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007328 break;
John McCalle3027922010-08-25 11:45:40 +00007329 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007330 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7331 CompLHSTy = CompResultTy;
7332 if (!CompResultTy.isNull())
7333 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007334 break;
John McCalle3027922010-08-25 11:45:40 +00007335 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007336 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7337 if (!CompResultTy.isNull())
7338 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007339 break;
John McCalle3027922010-08-25 11:45:40 +00007340 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007341 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7342 if (!CompResultTy.isNull())
7343 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007344 break;
John McCalle3027922010-08-25 11:45:40 +00007345 case BO_ShlAssign:
7346 case BO_ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007347 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
7348 CompLHSTy = CompResultTy;
7349 if (!CompResultTy.isNull())
7350 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007351 break;
John McCalle3027922010-08-25 11:45:40 +00007352 case BO_AndAssign:
7353 case BO_XorAssign:
7354 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007355 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7356 CompLHSTy = CompResultTy;
7357 if (!CompResultTy.isNull())
7358 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007359 break;
John McCalle3027922010-08-25 11:45:40 +00007360 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007361 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCall7decc9e2010-11-18 06:31:45 +00007362 if (getLangOptions().CPlusPlus) {
7363 VK = rhs->getValueKind();
7364 OK = rhs->getObjectKind();
7365 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007366 break;
7367 }
7368 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007369 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007370 if (CompResultTy.isNull())
John McCall7decc9e2010-11-18 06:31:45 +00007371 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
7372 VK, OK, OpLoc));
7373
7374 if (getLangOptions().CPlusPlus) {
7375 VK = VK_LValue;
7376 OK = lhs->getObjectKind();
7377 }
7378 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
7379 VK, OK, CompLHSTy,
7380 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007381}
7382
Sebastian Redl44615072009-10-27 12:10:02 +00007383/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
7384/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007385static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7386 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007387 const PartialDiagnostic &FirstNote,
7388 SourceRange FirstParenRange,
7389 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00007390 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007391 Self.Diag(Loc, PD);
7392
7393 if (!FirstNote.getDiagID())
7394 return;
7395
7396 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
7397 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7398 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007399 return;
7400 }
7401
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007402 Self.Diag(Loc, FirstNote)
7403 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00007404 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007405
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007406 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007407 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007408
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007409 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
7410 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7411 // We can't display the parentheses, so just dig the
7412 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007413 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007414 return;
7415 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007416
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007417 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00007418 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
7419 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007420}
7421
Sebastian Redl44615072009-10-27 12:10:02 +00007422/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7423/// operators are mixed in a way that suggests that the programmer forgot that
7424/// comparison operators have higher precedence. The most typical example of
7425/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007426static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007427 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007428 typedef BinaryOperator BinOp;
7429 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7430 rhsopc = static_cast<BinOp::Opcode>(-1);
7431 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007432 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007433 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007434 rhsopc = BO->getOpcode();
7435
7436 // Subs are not binary operators.
7437 if (lhsopc == -1 && rhsopc == -1)
7438 return;
7439
7440 // Bitwise operations are sometimes used as eager logical ops.
7441 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007442 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7443 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007444 return;
7445
Sebastian Redl44615072009-10-27 12:10:02 +00007446 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007447 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007448 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00007449 << SourceRange(lhs->getLocStart(), OpLoc)
7450 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00007451 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007452 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007453 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
7454 Self.PDiag(diag::note_precedence_bitwise_silence)
7455 << BinOp::getOpcodeStr(lhsopc),
7456 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00007457 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007458 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007459 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00007460 << SourceRange(OpLoc, rhs->getLocEnd())
7461 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00007462 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007463 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007464 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
7465 Self.PDiag(diag::note_precedence_bitwise_silence)
7466 << BinOp::getOpcodeStr(rhsopc),
7467 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00007468}
7469
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007470/// \brief It accepts a '&&' expr that is inside a '||' one.
7471/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7472/// in parentheses.
7473static void
7474EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
7475 Expr *E) {
7476 assert(isa<BinaryOperator>(E) &&
7477 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
7478 SuggestParentheses(Self, OpLoc,
7479 Self.PDiag(diag::warn_logical_and_in_logical_or)
7480 << E->getSourceRange(),
7481 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
7482 E->getSourceRange(),
7483 Self.PDiag(0), SourceRange());
7484}
7485
7486/// \brief Returns true if the given expression can be evaluated as a constant
7487/// 'true'.
7488static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7489 bool Res;
7490 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7491}
7492
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007493/// \brief Returns true if the given expression can be evaluated as a constant
7494/// 'false'.
7495static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7496 bool Res;
7497 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7498}
7499
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007500/// \brief Look for '&&' in the left hand of a '||' expr.
7501static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007502 Expr *OrLHS, Expr *OrRHS) {
7503 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007504 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007505 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7506 if (EvaluatesAsFalse(S, OrRHS))
7507 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007508 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7509 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7510 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7511 } else if (Bop->getOpcode() == BO_LOr) {
7512 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7513 // If it's "a || b && 1 || c" we didn't warn earlier for
7514 // "a || b && 1", but warn now.
7515 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7516 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7517 }
7518 }
7519 }
7520}
7521
7522/// \brief Look for '&&' in the right hand of a '||' expr.
7523static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007524 Expr *OrLHS, Expr *OrRHS) {
7525 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007526 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007527 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7528 if (EvaluatesAsFalse(S, OrLHS))
7529 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007530 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7531 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7532 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007533 }
7534 }
7535}
7536
Sebastian Redl43028242009-10-26 15:24:15 +00007537/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007538/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007539static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007540 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007541 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007542 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007543 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7544
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007545 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7546 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007547 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007548 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7549 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007550 }
Sebastian Redl43028242009-10-26 15:24:15 +00007551}
7552
Steve Naroff218bc2b2007-05-04 21:54:46 +00007553// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007554ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00007555 tok::TokenKind Kind,
7556 Expr *lhs, Expr *rhs) {
7557 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00007558 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7559 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00007560
Sebastian Redl43028242009-10-26 15:24:15 +00007561 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7562 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7563
Douglas Gregor5287f092009-11-05 00:51:44 +00007564 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7565}
7566
John McCalldadc5752010-08-24 06:29:42 +00007567ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007568 BinaryOperatorKind Opc,
7569 Expr *lhs, Expr *rhs) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007570 if (getLangOptions().CPlusPlus &&
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007571 ((!isa<ObjCImplicitSetterGetterRefExpr>(lhs) &&
7572 !isa<ObjCPropertyRefExpr>(lhs))
Fariborz Jahanianaaf44b22010-09-17 20:45:45 +00007573 || rhs->isTypeDependent() || Opc != BO_Assign) &&
Mike Stump11289f42009-09-09 15:08:12 +00007574 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007575 rhs->getType()->isOverloadableType())) {
7576 // Find all of the overloaded operators visible from this
7577 // point. We perform both an operator-name lookup from the local
7578 // scope and an argument-dependent lookup based on the types of
7579 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00007580 UnresolvedSet<16> Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007581 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00007582 if (S && OverOp != OO_None)
7583 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7584 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007585
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007586 // Build the (potentially-overloaded, potentially-dependent)
7587 // binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00007588 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00007589 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007590
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007591 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00007592 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007593}
7594
John McCalldadc5752010-08-24 06:29:42 +00007595ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
John McCall36226622010-10-12 02:09:17 +00007596 unsigned OpcIn,
7597 Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00007598 UnaryOperatorKind Opc = static_cast<UnaryOperatorKind>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00007599
John McCall7decc9e2010-11-18 06:31:45 +00007600 ExprValueKind VK = VK_RValue;
7601 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00007602 QualType resultType;
7603 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007604 case UO_PreInc:
7605 case UO_PreDec:
7606 case UO_PostInc:
7607 case UO_PostDec:
John McCall4bc41ae2010-11-18 19:01:18 +00007608 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007609 Opc == UO_PreInc ||
7610 Opc == UO_PostInc,
7611 Opc == UO_PreInc ||
7612 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00007613 break;
John McCalle3027922010-08-25 11:45:40 +00007614 case UO_AddrOf:
John McCall4bc41ae2010-11-18 19:01:18 +00007615 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007616 break;
John McCalle3027922010-08-25 11:45:40 +00007617 case UO_Deref:
Douglas Gregorb92a1562010-02-03 00:27:59 +00007618 DefaultFunctionArrayLvalueConversion(Input);
John McCall4bc41ae2010-11-18 19:01:18 +00007619 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007620 break;
John McCalle3027922010-08-25 11:45:40 +00007621 case UO_Plus:
7622 case UO_Minus:
Steve Naroff31090012007-07-16 21:54:35 +00007623 UsualUnaryConversions(Input);
7624 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007625 if (resultType->isDependentType())
7626 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00007627 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7628 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00007629 break;
7630 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7631 resultType->isEnumeralType())
7632 break;
7633 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00007634 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00007635 resultType->isPointerType())
7636 break;
John McCall36226622010-10-12 02:09:17 +00007637 else if (resultType->isPlaceholderType()) {
7638 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7639 if (PR.isInvalid()) return ExprError();
7640 return CreateBuiltinUnaryOp(OpLoc, OpcIn, PR.take());
7641 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007642
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007643 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7644 << resultType << Input->getSourceRange());
John McCalle3027922010-08-25 11:45:40 +00007645 case UO_Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00007646 UsualUnaryConversions(Input);
7647 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007648 if (resultType->isDependentType())
7649 break;
Chris Lattner0d707612008-07-25 23:52:49 +00007650 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
7651 if (resultType->isComplexType() || resultType->isComplexIntegerType())
7652 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00007653 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007654 << resultType << Input->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007655 else if (resultType->hasIntegerRepresentation())
7656 break;
7657 else if (resultType->isPlaceholderType()) {
7658 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7659 if (PR.isInvalid()) return ExprError();
7660 return CreateBuiltinUnaryOp(OpLoc, OpcIn, PR.take());
7661 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007662 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7663 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007664 }
Steve Naroff35d85152007-05-07 00:24:15 +00007665 break;
John McCalle3027922010-08-25 11:45:40 +00007666 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00007667 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00007668 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00007669 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007670 if (resultType->isDependentType())
7671 break;
John McCall36226622010-10-12 02:09:17 +00007672 if (resultType->isScalarType()) { // C99 6.5.3.3p1
7673 // ok, fallthrough
7674 } else if (resultType->isPlaceholderType()) {
7675 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7676 if (PR.isInvalid()) return ExprError();
7677 return CreateBuiltinUnaryOp(OpLoc, OpcIn, PR.take());
7678 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007679 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7680 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007681 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00007682
Chris Lattnerbe31ed82007-06-02 19:11:33 +00007683 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007684 // In C++, it's bool. C++ 5.3.1p8
7685 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00007686 break;
John McCalle3027922010-08-25 11:45:40 +00007687 case UO_Real:
7688 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00007689 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00007690 // _Real and _Imag map ordinary l-values into ordinary l-values.
7691 if (Input->getValueKind() != VK_RValue &&
7692 Input->getObjectKind() == OK_Ordinary)
7693 VK = Input->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00007694 break;
John McCalle3027922010-08-25 11:45:40 +00007695 case UO_Extension:
Chris Lattner86554282007-06-08 22:32:33 +00007696 resultType = Input->getType();
John McCall7decc9e2010-11-18 06:31:45 +00007697 VK = Input->getValueKind();
7698 OK = Input->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00007699 break;
Steve Naroff35d85152007-05-07 00:24:15 +00007700 }
7701 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007702 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00007703
John McCall7decc9e2010-11-18 06:31:45 +00007704 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
7705 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00007706}
Chris Lattnereefa10e2007-05-28 06:56:27 +00007707
John McCalldadc5752010-08-24 06:29:42 +00007708ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007709 UnaryOperatorKind Opc,
7710 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00007711 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00007712 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007713 // Find all of the overloaded operators visible from this
7714 // point. We perform both an operator-name lookup from the local
7715 // scope and an argument-dependent lookup based on the types of
7716 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00007717 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00007718 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00007719 if (S && OverOp != OO_None)
7720 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
7721 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007722
John McCallb268a282010-08-23 23:25:46 +00007723 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007724 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007725
John McCallb268a282010-08-23 23:25:46 +00007726 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007727}
7728
Douglas Gregor5287f092009-11-05 00:51:44 +00007729// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007730ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00007731 tok::TokenKind Op, Expr *Input) {
7732 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00007733}
7734
Steve Naroff66356bd2007-09-16 14:56:35 +00007735/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
John McCalldadc5752010-08-24 06:29:42 +00007736ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007737 SourceLocation LabLoc,
7738 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00007739 // Look up the record for this label identifier.
John McCallaab3e412010-08-25 08:40:02 +00007740 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00007741
Daniel Dunbar88402ce2008-08-04 16:51:22 +00007742 // If we haven't seen this label yet, create a forward reference. It
7743 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00007744 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00007745 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007746
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00007747 LabelDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00007748 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007749 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
7750 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00007751}
7752
John McCalldadc5752010-08-24 06:29:42 +00007753ExprResult
John McCallb268a282010-08-23 23:25:46 +00007754Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007755 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00007756 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
7757 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
7758
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00007759 bool isFileScope
7760 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00007761 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007762 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00007763
Chris Lattner366727f2007-07-24 16:58:17 +00007764 // FIXME: there are a variety of strange constraints to enforce here, for
7765 // example, it is not possible to goto into a stmt expression apparently.
7766 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007767
Chris Lattner366727f2007-07-24 16:58:17 +00007768 // If there are sub stmts in the compound stmt, take the type of the last one
7769 // as the type of the stmtexpr.
7770 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007771 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00007772 if (!Compound->body_empty()) {
7773 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007774 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00007775 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007776 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
7777 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00007778 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007779 }
7780 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
Fariborz Jahaniandd6907b2010-10-27 20:44:00 +00007781 DefaultFunctionArrayLvalueConversion(LastExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00007782 Ty = LastExpr->getType();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007783 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
7784 ExprResult Res = PerformCopyInitialization(
7785 InitializedEntity::InitializeResult(LPLoc,
7786 Ty,
7787 false),
7788 SourceLocation(),
7789 Owned(LastExpr));
7790 if (Res.isInvalid())
7791 return ExprError();
7792 if ((LastExpr = Res.takeAs<Expr>())) {
7793 if (!LastLabelStmt)
7794 Compound->setLastStmt(LastExpr);
7795 else
7796 LastLabelStmt->setSubStmt(LastExpr);
7797 StmtExprMayBindToTemp = true;
7798 }
7799 }
7800 }
Chris Lattner944d3062008-07-26 19:51:01 +00007801 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007802
Eli Friedmanba961a92009-03-23 00:24:07 +00007803 // FIXME: Check that expression type is complete/non-abstract; statement
7804 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007805 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
7806 if (StmtExprMayBindToTemp)
7807 return MaybeBindToTemporary(ResStmtExpr);
7808 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00007809}
Steve Naroff78864672007-08-01 22:05:33 +00007810
John McCalldadc5752010-08-24 06:29:42 +00007811ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00007812 TypeSourceInfo *TInfo,
7813 OffsetOfComponent *CompPtr,
7814 unsigned NumComponents,
7815 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007816 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007817 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00007818 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00007819
Chris Lattnerf17bd422007-08-30 17:45:32 +00007820 // We must have at least one component that refers to the type, and the first
7821 // one is known to be a field designator. Verify that the ArgTy represents
7822 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007823 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00007824 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
7825 << ArgTy << TypeRange);
7826
7827 // Type must be complete per C99 7.17p3 because a declaring a variable
7828 // with an incomplete type would be ill-formed.
7829 if (!Dependent
7830 && RequireCompleteType(BuiltinLoc, ArgTy,
7831 PDiag(diag::err_offsetof_incomplete_type)
7832 << TypeRange))
7833 return ExprError();
7834
Chris Lattner78502cf2007-08-31 21:49:13 +00007835 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
7836 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00007837 // FIXME: This diagnostic isn't actually visible because the location is in
7838 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00007839 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00007840 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
7841 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00007842
7843 bool DidWarnAboutNonPOD = false;
7844 QualType CurrentType = ArgTy;
7845 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
7846 llvm::SmallVector<OffsetOfNode, 4> Comps;
7847 llvm::SmallVector<Expr*, 4> Exprs;
7848 for (unsigned i = 0; i != NumComponents; ++i) {
7849 const OffsetOfComponent &OC = CompPtr[i];
7850 if (OC.isBrackets) {
7851 // Offset of an array sub-field. TODO: Should we allow vector elements?
7852 if (!CurrentType->isDependentType()) {
7853 const ArrayType *AT = Context.getAsArrayType(CurrentType);
7854 if(!AT)
7855 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
7856 << CurrentType);
7857 CurrentType = AT->getElementType();
7858 } else
7859 CurrentType = Context.DependentTy;
7860
7861 // The expression must be an integral expression.
7862 // FIXME: An integral constant expression?
7863 Expr *Idx = static_cast<Expr*>(OC.U.E);
7864 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
7865 !Idx->getType()->isIntegerType())
7866 return ExprError(Diag(Idx->getLocStart(),
7867 diag::err_typecheck_subscript_not_integer)
7868 << Idx->getSourceRange());
7869
7870 // Record this array index.
7871 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
7872 Exprs.push_back(Idx);
7873 continue;
7874 }
7875
7876 // Offset of a field.
7877 if (CurrentType->isDependentType()) {
7878 // We have the offset of a field, but we can't look into the dependent
7879 // type. Just record the identifier of the field.
7880 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
7881 CurrentType = Context.DependentTy;
7882 continue;
7883 }
7884
7885 // We need to have a complete type to look into.
7886 if (RequireCompleteType(OC.LocStart, CurrentType,
7887 diag::err_offsetof_incomplete_type))
7888 return ExprError();
7889
7890 // Look for the designated field.
7891 const RecordType *RC = CurrentType->getAs<RecordType>();
7892 if (!RC)
7893 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
7894 << CurrentType);
7895 RecordDecl *RD = RC->getDecl();
7896
7897 // C++ [lib.support.types]p5:
7898 // The macro offsetof accepts a restricted set of type arguments in this
7899 // International Standard. type shall be a POD structure or a POD union
7900 // (clause 9).
7901 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7902 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
7903 DiagRuntimeBehavior(BuiltinLoc,
7904 PDiag(diag::warn_offsetof_non_pod_type)
7905 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
7906 << CurrentType))
7907 DidWarnAboutNonPOD = true;
7908 }
7909
7910 // Look for the field.
7911 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
7912 LookupQualifiedName(R, RD);
7913 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00007914 IndirectFieldDecl *IndirectMemberDecl = 0;
7915 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00007916 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00007917 MemberDecl = IndirectMemberDecl->getAnonField();
7918 }
7919
Douglas Gregor882211c2010-04-28 22:16:22 +00007920 if (!MemberDecl)
7921 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
7922 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
7923 OC.LocEnd));
7924
Douglas Gregor10982ea2010-04-28 22:36:06 +00007925 // C99 7.17p3:
7926 // (If the specified member is a bit-field, the behavior is undefined.)
7927 //
7928 // We diagnose this as an error.
7929 if (MemberDecl->getBitWidth()) {
7930 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
7931 << MemberDecl->getDeclName()
7932 << SourceRange(BuiltinLoc, RParenLoc);
7933 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
7934 return ExprError();
7935 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00007936
7937 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00007938 if (IndirectMemberDecl)
7939 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00007940
Douglas Gregord1702062010-04-29 00:18:15 +00007941 // If the member was found in a base class, introduce OffsetOfNodes for
7942 // the base class indirections.
7943 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
7944 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00007945 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00007946 CXXBasePath &Path = Paths.front();
7947 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
7948 B != BEnd; ++B)
7949 Comps.push_back(OffsetOfNode(B->Base));
7950 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00007951
Francois Pichet783dd6e2010-11-21 06:08:52 +00007952 if (IndirectMemberDecl) {
7953 for (IndirectFieldDecl::chain_iterator FI =
7954 IndirectMemberDecl->chain_begin(),
7955 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
7956 assert(isa<FieldDecl>(*FI));
7957 Comps.push_back(OffsetOfNode(OC.LocStart,
7958 cast<FieldDecl>(*FI), OC.LocEnd));
7959 }
7960 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00007961 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00007962
Douglas Gregor882211c2010-04-28 22:16:22 +00007963 CurrentType = MemberDecl->getType().getNonReferenceType();
7964 }
7965
7966 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
7967 TInfo, Comps.data(), Comps.size(),
7968 Exprs.data(), Exprs.size(), RParenLoc));
7969}
Mike Stump4e1f26a2009-02-19 03:04:26 +00007970
John McCalldadc5752010-08-24 06:29:42 +00007971ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00007972 SourceLocation BuiltinLoc,
7973 SourceLocation TypeLoc,
7974 ParsedType argty,
7975 OffsetOfComponent *CompPtr,
7976 unsigned NumComponents,
7977 SourceLocation RPLoc) {
7978
Douglas Gregor882211c2010-04-28 22:16:22 +00007979 TypeSourceInfo *ArgTInfo;
7980 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
7981 if (ArgTy.isNull())
7982 return ExprError();
7983
Eli Friedman06dcfd92010-08-05 10:15:45 +00007984 if (!ArgTInfo)
7985 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
7986
7987 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
7988 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00007989}
7990
7991
John McCalldadc5752010-08-24 06:29:42 +00007992ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00007993 ParsedType arg1, ParsedType arg2,
7994 SourceLocation RPLoc) {
Abramo Bagnara092990a2010-08-10 08:50:03 +00007995 TypeSourceInfo *argTInfo1;
7996 QualType argT1 = GetTypeFromParser(arg1, &argTInfo1);
7997 TypeSourceInfo *argTInfo2;
7998 QualType argT2 = GetTypeFromParser(arg2, &argTInfo2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007999
Steve Naroff78864672007-08-01 22:05:33 +00008000 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00008001
Abramo Bagnara092990a2010-08-10 08:50:03 +00008002 return BuildTypesCompatibleExpr(BuiltinLoc, argTInfo1, argTInfo2, RPLoc);
8003}
8004
John McCalldadc5752010-08-24 06:29:42 +00008005ExprResult
Abramo Bagnara092990a2010-08-10 08:50:03 +00008006Sema::BuildTypesCompatibleExpr(SourceLocation BuiltinLoc,
8007 TypeSourceInfo *argTInfo1,
8008 TypeSourceInfo *argTInfo2,
8009 SourceLocation RPLoc) {
Douglas Gregorf907cbf2009-05-19 22:28:02 +00008010 if (getLangOptions().CPlusPlus) {
8011 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
8012 << SourceRange(BuiltinLoc, RPLoc);
8013 return ExprError();
8014 }
8015
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008016 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
Abramo Bagnara092990a2010-08-10 08:50:03 +00008017 argTInfo1, argTInfo2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00008018}
8019
Abramo Bagnara092990a2010-08-10 08:50:03 +00008020
John McCalldadc5752010-08-24 06:29:42 +00008021ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008022 Expr *CondExpr,
8023 Expr *LHSExpr, Expr *RHSExpr,
8024 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008025 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8026
John McCall7decc9e2010-11-18 06:31:45 +00008027 ExprValueKind VK = VK_RValue;
8028 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008029 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008030 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008031 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008032 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008033 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008034 } else {
8035 // The conditional expression is required to be a constant expression.
8036 llvm::APSInt condEval(32);
8037 SourceLocation ExpLoc;
8038 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008039 return ExprError(Diag(ExpLoc,
8040 diag::err_typecheck_choose_expr_requires_constant)
8041 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008042
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008043 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008044 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8045
8046 resType = ActiveExpr->getType();
8047 ValueDependent = ActiveExpr->isValueDependent();
8048 VK = ActiveExpr->getValueKind();
8049 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008050 }
8051
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008052 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008053 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008054 resType->isDependentType(),
8055 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008056}
8057
Steve Naroffc540d662008-09-03 18:15:37 +00008058//===----------------------------------------------------------------------===//
8059// Clang Extensions.
8060//===----------------------------------------------------------------------===//
8061
8062/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008063void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008064 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8065 PushBlockScope(BlockScope, Block);
8066 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008067 if (BlockScope)
8068 PushDeclContext(BlockScope, Block);
8069 else
8070 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008071}
8072
Mike Stump82f071f2009-02-04 22:31:32 +00008073void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008074 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Douglas Gregor9a28e842010-03-01 23:15:13 +00008075 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008076
John McCall8cb7bdf2010-06-04 23:28:52 +00008077 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCalla3ccba02010-06-04 11:21:44 +00008078 CurBlock->TheDecl->setSignatureAsWritten(Sig);
John McCall8cb7bdf2010-06-04 23:28:52 +00008079 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008080
John McCall8e346702010-06-04 19:02:56 +00008081 bool isVariadic;
John McCalla3ccba02010-06-04 11:21:44 +00008082 QualType RetTy;
8083 if (const FunctionType *Fn = T->getAs<FunctionType>()) {
John McCall8e346702010-06-04 19:02:56 +00008084 CurBlock->FunctionType = T;
John McCalla3ccba02010-06-04 11:21:44 +00008085 RetTy = Fn->getResultType();
John McCall8e346702010-06-04 19:02:56 +00008086 isVariadic =
John McCalla3ccba02010-06-04 11:21:44 +00008087 !isa<FunctionProtoType>(Fn) || cast<FunctionProtoType>(Fn)->isVariadic();
8088 } else {
8089 RetTy = T;
John McCall8e346702010-06-04 19:02:56 +00008090 isVariadic = false;
John McCalla3ccba02010-06-04 11:21:44 +00008091 }
Mike Stump11289f42009-09-09 15:08:12 +00008092
John McCall8e346702010-06-04 19:02:56 +00008093 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008094
John McCalla3ccba02010-06-04 11:21:44 +00008095 // Don't allow returning an array by value.
8096 if (RetTy->isArrayType()) {
8097 Diag(ParamInfo.getSourceRange().getBegin(), diag::err_block_returns_array);
Mike Stump82f071f2009-02-04 22:31:32 +00008098 return;
8099 }
8100
John McCalla3ccba02010-06-04 11:21:44 +00008101 // Don't allow returning a objc interface by value.
8102 if (RetTy->isObjCObjectType()) {
8103 Diag(ParamInfo.getSourceRange().getBegin(),
8104 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8105 return;
8106 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008107
John McCalla3ccba02010-06-04 11:21:44 +00008108 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008109 // return type. TODO: what should we do with declarators like:
8110 // ^ * { ... }
8111 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008112 if (RetTy != Context.DependentTy)
8113 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008114
John McCalla3ccba02010-06-04 11:21:44 +00008115 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00008116 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCalla3ccba02010-06-04 11:21:44 +00008117 if (isa<FunctionProtoType>(T)) {
8118 FunctionProtoTypeLoc TL = cast<FunctionProtoTypeLoc>(Sig->getTypeLoc());
8119 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
8120 ParmVarDecl *Param = TL.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008121 if (Param->getIdentifier() == 0 &&
8122 !Param->isImplicit() &&
8123 !Param->isInvalidDecl() &&
8124 !getLangOptions().CPlusPlus)
8125 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008126 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008127 }
John McCalla3ccba02010-06-04 11:21:44 +00008128
8129 // Fake up parameter variables if we have a typedef, like
8130 // ^ fntype { ... }
8131 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8132 for (FunctionProtoType::arg_type_iterator
8133 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8134 ParmVarDecl *Param =
8135 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8136 ParamInfo.getSourceRange().getBegin(),
8137 *I);
John McCall8e346702010-06-04 19:02:56 +00008138 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008139 }
Steve Naroffc540d662008-09-03 18:15:37 +00008140 }
John McCalla3ccba02010-06-04 11:21:44 +00008141
John McCall8e346702010-06-04 19:02:56 +00008142 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008143 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008144 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008145 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8146 CurBlock->TheDecl->param_end(),
8147 /*CheckParameterNames=*/false);
8148 }
8149
John McCalla3ccba02010-06-04 11:21:44 +00008150 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008151 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008152
John McCall8e346702010-06-04 19:02:56 +00008153 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008154 Diag(ParamInfo.getAttributes()->getLoc(),
8155 diag::warn_attribute_sentinel_not_variadic) << 1;
8156 // FIXME: remove the attribute.
8157 }
8158
8159 // Put the parameter variables in scope. We can bail out immediately
8160 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008161 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008162 return;
8163
John McCalldf8b37c2010-03-22 09:20:08 +00008164 bool ShouldCheckShadow =
8165 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
8166
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008167 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008168 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8169 (*AI)->setOwningFunction(CurBlock->TheDecl);
8170
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008171 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008172 if ((*AI)->getIdentifier()) {
8173 if (ShouldCheckShadow)
8174 CheckShadow(CurBlock->TheScope, *AI);
8175
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008176 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008177 }
John McCallf7b2fb52010-01-22 00:28:27 +00008178 }
Steve Naroffc540d662008-09-03 18:15:37 +00008179}
8180
8181/// ActOnBlockError - If there is an error parsing a block, this callback
8182/// is invoked to pop the information about the block from the action impl.
8183void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008184 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008185 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008186 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008187}
8188
8189/// ActOnBlockStmtExpr - This is called when the body of a block statement
8190/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008191ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
John McCallb268a282010-08-23 23:25:46 +00008192 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008193 // If blocks are disabled, emit an error.
8194 if (!LangOpts.Blocks)
8195 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008196
Douglas Gregor9a28e842010-03-01 23:15:13 +00008197 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008198
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008199 PopDeclContext();
8200
Steve Naroffc540d662008-09-03 18:15:37 +00008201 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008202 if (!BSI->ReturnType.isNull())
8203 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008204
Mike Stump3bf1ab42009-07-28 22:04:01 +00008205 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008206 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008207
8208 // If the user wrote a function type in some form, try to use that.
8209 if (!BSI->FunctionType.isNull()) {
8210 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8211
8212 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8213 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8214
8215 // Turn protoless block types into nullary block types.
8216 if (isa<FunctionNoProtoType>(FTy)) {
8217 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
8218 false, false, 0, 0, Ext);
8219
8220 // Otherwise, if we don't need to change anything about the function type,
8221 // preserve its sugar structure.
8222 } else if (FTy->getResultType() == RetTy &&
8223 (!NoReturn || FTy->getNoReturnAttr())) {
8224 BlockTy = BSI->FunctionType;
8225
8226 // Otherwise, make the minimal modifications to the function type.
8227 } else {
8228 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
8229 BlockTy = Context.getFunctionType(RetTy,
8230 FPT->arg_type_begin(),
8231 FPT->getNumArgs(),
8232 FPT->isVariadic(),
8233 /*quals*/ 0,
8234 FPT->hasExceptionSpec(),
8235 FPT->hasAnyExceptionSpec(),
8236 FPT->getNumExceptions(),
8237 FPT->exception_begin(),
8238 Ext);
8239 }
8240
8241 // If we don't have a function type, just build one from nothing.
8242 } else {
8243 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
8244 false, false, 0, 0,
8245 FunctionType::ExtInfo(NoReturn, 0, CC_Default));
8246 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008247
John McCall8e346702010-06-04 19:02:56 +00008248 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8249 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008250 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008251
Chris Lattner45542ea2009-04-19 05:28:12 +00008252 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00008253 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008254 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008255
John McCallb268a282010-08-23 23:25:46 +00008256 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Mike Stump314825b2010-01-19 23:08:01 +00008257
8258 bool Good = true;
8259 // Check goto/label use.
8260 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
8261 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
8262 LabelStmt *L = I->second;
8263
8264 // Verify that we have no forward references left. If so, there was a goto
8265 // or address of a label taken, but no definition of it.
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00008266 if (L->getSubStmt() != 0) {
8267 if (!L->isUsed())
8268 Diag(L->getIdentLoc(), diag::warn_unused_label) << L->getName();
Mike Stump314825b2010-01-19 23:08:01 +00008269 continue;
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00008270 }
Mike Stump314825b2010-01-19 23:08:01 +00008271
8272 // Emit error.
8273 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
8274 Good = false;
8275 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00008276 if (!Good) {
8277 PopFunctionOrBlockScope();
Mike Stump314825b2010-01-19 23:08:01 +00008278 return ExprError();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008279 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008280
John McCall1d570a72010-08-25 05:56:39 +00008281 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
8282 BSI->hasBlockDeclRefExprs);
8283
Ted Kremenek918fe842010-03-20 21:06:02 +00008284 // Issue any analysis-based warnings.
Ted Kremenek0b405322010-03-23 00:13:23 +00008285 const sema::AnalysisBasedWarnings::Policy &WP =
8286 AnalysisWarnings.getDefaultPolicy();
John McCall1d570a72010-08-25 05:56:39 +00008287 AnalysisWarnings.IssueWarnings(WP, Result);
Ted Kremenek918fe842010-03-20 21:06:02 +00008288
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008289 PopFunctionOrBlockScope();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008290 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008291}
8292
John McCalldadc5752010-08-24 06:29:42 +00008293ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008294 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008295 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008296 TypeSourceInfo *TInfo;
8297 QualType T = GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008298 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008299}
8300
John McCalldadc5752010-08-24 06:29:42 +00008301ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008302 Expr *E, TypeSourceInfo *TInfo,
8303 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008304 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008305
Eli Friedman121ba0c2008-08-09 23:32:40 +00008306 // Get the va_list type
8307 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008308 if (VaListType->isArrayType()) {
8309 // Deal with implicit array decay; for example, on x86-64,
8310 // va_list is an array, but it's supposed to decay to
8311 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008312 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008313 // Make sure the input expression also decays appropriately.
8314 UsualUnaryConversions(E);
8315 } else {
8316 // Otherwise, the va_list argument must be an l-value because
8317 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008318 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008319 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008320 return ExprError();
8321 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008322
Douglas Gregorad3150c2009-05-19 23:10:31 +00008323 if (!E->isTypeDependent() &&
8324 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008325 return ExprError(Diag(E->getLocStart(),
8326 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008327 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008328 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008329
Eli Friedmanba961a92009-03-23 00:24:07 +00008330 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008331 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008332
Abramo Bagnara27db2392010-08-10 10:06:15 +00008333 QualType T = TInfo->getType().getNonLValueExprType(Context);
8334 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008335}
8336
John McCalldadc5752010-08-24 06:29:42 +00008337ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008338 // The type of __null will be int or long, depending on the size of
8339 // pointers on the target.
8340 QualType Ty;
8341 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
8342 Ty = Context.IntTy;
8343 else
8344 Ty = Context.LongTy;
8345
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008346 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008347}
8348
Alexis Huntc46382e2010-04-28 23:02:27 +00008349static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008350 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008351 if (!SemaRef.getLangOptions().ObjC1)
8352 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008353
Anders Carlssonace5d072009-11-10 04:46:30 +00008354 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8355 if (!PT)
8356 return;
8357
8358 // Check if the destination is of type 'id'.
8359 if (!PT->isObjCIdType()) {
8360 // Check if the destination is the 'NSString' interface.
8361 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8362 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8363 return;
8364 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008365
Anders Carlssonace5d072009-11-10 04:46:30 +00008366 // Strip off any parens and casts.
8367 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8368 if (!SL || SL->isWide())
8369 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008370
Douglas Gregora771f462010-03-31 17:46:05 +00008371 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008372}
8373
Chris Lattner9bad62c2008-01-04 18:04:52 +00008374bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8375 SourceLocation Loc,
8376 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008377 Expr *SrcExpr, AssignmentAction Action,
8378 bool *Complained) {
8379 if (Complained)
8380 *Complained = false;
8381
Chris Lattner9bad62c2008-01-04 18:04:52 +00008382 // Decode the result (notice that AST's are still created for extensions).
8383 bool isInvalid = false;
8384 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008385 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008386
Chris Lattner9bad62c2008-01-04 18:04:52 +00008387 switch (ConvTy) {
8388 default: assert(0 && "Unknown conversion type");
8389 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008390 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008391 DiagKind = diag::ext_typecheck_convert_pointer_int;
8392 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008393 case IntToPointer:
8394 DiagKind = diag::ext_typecheck_convert_int_pointer;
8395 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008396 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008397 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008398 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
8399 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008400 case IncompatiblePointerSign:
8401 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8402 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008403 case FunctionVoidPointer:
8404 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8405 break;
8406 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008407 // If the qualifiers lost were because we were applying the
8408 // (deprecated) C++ conversion from a string literal to a char*
8409 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8410 // Ideally, this check would be performed in
8411 // CheckPointerTypesForAssignment. However, that would require a
8412 // bit of refactoring (so that the second argument is an
8413 // expression, rather than a type), which should be done as part
8414 // of a larger effort to fix CheckPointerTypesForAssignment for
8415 // C++ semantics.
8416 if (getLangOptions().CPlusPlus &&
8417 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8418 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008419 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8420 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008421 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008422 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008423 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008424 case IntToBlockPointer:
8425 DiagKind = diag::err_int_to_block_pointer;
8426 break;
8427 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008428 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008429 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008430 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008431 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008432 // it can give a more specific diagnostic.
8433 DiagKind = diag::warn_incompatible_qualified_id;
8434 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008435 case IncompatibleVectors:
8436 DiagKind = diag::warn_incompatible_vectors;
8437 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008438 case Incompatible:
8439 DiagKind = diag::err_typecheck_convert_incompatible;
8440 isInvalid = true;
8441 break;
8442 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008443
Douglas Gregorc68e1402010-04-09 00:35:39 +00008444 QualType FirstType, SecondType;
8445 switch (Action) {
8446 case AA_Assigning:
8447 case AA_Initializing:
8448 // The destination type comes first.
8449 FirstType = DstType;
8450 SecondType = SrcType;
8451 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00008452
Douglas Gregorc68e1402010-04-09 00:35:39 +00008453 case AA_Returning:
8454 case AA_Passing:
8455 case AA_Converting:
8456 case AA_Sending:
8457 case AA_Casting:
8458 // The source type comes first.
8459 FirstType = SrcType;
8460 SecondType = DstType;
8461 break;
8462 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008463
Douglas Gregorc68e1402010-04-09 00:35:39 +00008464 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00008465 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008466 if (Complained)
8467 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008468 return isInvalid;
8469}
Anders Carlssone54e8a12008-11-30 19:50:32 +00008470
Chris Lattnerc71d08b2009-04-25 21:59:05 +00008471bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008472 llvm::APSInt ICEResult;
8473 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8474 if (Result)
8475 *Result = ICEResult;
8476 return false;
8477 }
8478
Anders Carlssone54e8a12008-11-30 19:50:32 +00008479 Expr::EvalResult EvalResult;
8480
Mike Stump4e1f26a2009-02-19 03:04:26 +00008481 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00008482 EvalResult.HasSideEffects) {
8483 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8484
8485 if (EvalResult.Diag) {
8486 // We only show the note if it's not the usual "invalid subexpression"
8487 // or if it's actually in a subexpression.
8488 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8489 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8490 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8491 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008492
Anders Carlssone54e8a12008-11-30 19:50:32 +00008493 return true;
8494 }
8495
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008496 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8497 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00008498
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008499 if (EvalResult.Diag &&
8500 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
8501 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008502
Anders Carlssone54e8a12008-11-30 19:50:32 +00008503 if (Result)
8504 *Result = EvalResult.Val.getInt();
8505 return false;
8506}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008507
Douglas Gregorff790f12009-11-26 00:44:06 +00008508void
Mike Stump11289f42009-09-09 15:08:12 +00008509Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008510 ExprEvalContexts.push_back(
8511 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008512}
8513
Mike Stump11289f42009-09-09 15:08:12 +00008514void
Douglas Gregorff790f12009-11-26 00:44:06 +00008515Sema::PopExpressionEvaluationContext() {
8516 // Pop the current expression evaluation context off the stack.
8517 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8518 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008519
Douglas Gregorfab31f42009-12-12 07:57:52 +00008520 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8521 if (Rec.PotentiallyReferenced) {
8522 // Mark any remaining declarations in the current position of the stack
8523 // as "referenced". If they were not meant to be referenced, semantic
8524 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008525 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00008526 I = Rec.PotentiallyReferenced->begin(),
8527 IEnd = Rec.PotentiallyReferenced->end();
8528 I != IEnd; ++I)
8529 MarkDeclarationReferenced(I->first, I->second);
8530 }
8531
8532 if (Rec.PotentiallyDiagnosed) {
8533 // Emit any pending diagnostics.
8534 for (PotentiallyEmittedDiagnostics::iterator
8535 I = Rec.PotentiallyDiagnosed->begin(),
8536 IEnd = Rec.PotentiallyDiagnosed->end();
8537 I != IEnd; ++I)
8538 Diag(I->first, I->second);
8539 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008540 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008541
8542 // When are coming out of an unevaluated context, clear out any
8543 // temporaries that we may have created as part of the evaluation of
8544 // the expression in that context: they aren't relevant because they
8545 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008546 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00008547 ExprTemporaries.size() > Rec.NumTemporaries)
8548 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
8549 ExprTemporaries.end());
8550
8551 // Destroy the popped expression evaluation record.
8552 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008553}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008554
8555/// \brief Note that the given declaration was referenced in the source code.
8556///
8557/// This routine should be invoke whenever a given declaration is referenced
8558/// in the source code, and where that reference occurred. If this declaration
8559/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
8560/// C99 6.9p3), then the declaration will be marked as used.
8561///
8562/// \param Loc the location where the declaration was referenced.
8563///
8564/// \param D the declaration that has been referenced by the source code.
8565void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
8566 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00008567
Douglas Gregorebada0772010-06-17 23:14:26 +00008568 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00008569 return;
Mike Stump11289f42009-09-09 15:08:12 +00008570
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00008571 // Mark a parameter or variable declaration "used", regardless of whether we're in a
8572 // template or not. The reason for this is that unevaluated expressions
8573 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
8574 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008575 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008576 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00008577 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008578 return;
8579 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008580
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008581 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
8582 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00008583
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008584 // Do not mark anything as "used" within a dependent context; wait for
8585 // an instantiation.
8586 if (CurContext->isDependentContext())
8587 return;
Mike Stump11289f42009-09-09 15:08:12 +00008588
Douglas Gregorff790f12009-11-26 00:44:06 +00008589 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008590 case Unevaluated:
8591 // We are in an expression that is not potentially evaluated; do nothing.
8592 return;
Mike Stump11289f42009-09-09 15:08:12 +00008593
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008594 case PotentiallyEvaluated:
8595 // We are in a potentially-evaluated expression, so this declaration is
8596 // "used"; handle this below.
8597 break;
Mike Stump11289f42009-09-09 15:08:12 +00008598
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008599 case PotentiallyPotentiallyEvaluated:
8600 // We are in an expression that may be potentially evaluated; queue this
8601 // declaration reference until we know whether the expression is
8602 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00008603 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008604 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008605
8606 case PotentiallyEvaluatedIfUsed:
8607 // Referenced declarations will only be used if the construct in the
8608 // containing expression is used.
8609 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008610 }
Mike Stump11289f42009-09-09 15:08:12 +00008611
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008612 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00008613 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008614 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008615 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00008616 if (Constructor->getParent()->hasTrivialConstructor())
8617 return;
8618 if (!Constructor->isUsed(false))
8619 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00008620 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00008621 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008622 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008623 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
8624 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008625
Douglas Gregor88d292c2010-05-13 16:44:06 +00008626 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008627 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008628 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008629 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008630 if (Destructor->isVirtual())
8631 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008632 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
8633 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
8634 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008635 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00008636 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008637 } else if (MethodDecl->isVirtual())
8638 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008639 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00008640 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00008641 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00008642 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00008643 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00008644 bool AlreadyInstantiated = false;
8645 if (FunctionTemplateSpecializationInfo *SpecInfo
8646 = Function->getTemplateSpecializationInfo()) {
8647 if (SpecInfo->getPointOfInstantiation().isInvalid())
8648 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008649 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008650 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008651 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008652 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00008653 = Function->getMemberSpecializationInfo()) {
8654 if (MSInfo->getPointOfInstantiation().isInvalid())
8655 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008656 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008657 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008658 AlreadyInstantiated = true;
8659 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008660
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008661 if (!AlreadyInstantiated) {
8662 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
8663 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
8664 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
8665 Loc));
8666 else
Chandler Carruth54080172010-08-25 08:44:16 +00008667 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008668 }
Gabor Greifb6aba3e2010-08-28 00:16:06 +00008669 } else // Walk redefinitions, as some of them may be instantiable.
8670 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
8671 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00008672 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00008673 MarkDeclarationReferenced(Loc, *i);
8674 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008675
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008676 // FIXME: keep track of references to static functions
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00008677
8678 // Recursive functions should be marked when used from another function.
8679 if (CurContext != Function)
8680 Function->setUsed(true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008681
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008682 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00008683 }
Mike Stump11289f42009-09-09 15:08:12 +00008684
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008685 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008686 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00008687 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00008688 Var->getInstantiatedFromStaticDataMember()) {
8689 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
8690 assert(MSInfo && "Missing member specialization information?");
8691 if (MSInfo->getPointOfInstantiation().isInvalid() &&
8692 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
8693 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +00008694 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00008695 }
8696 }
Mike Stump11289f42009-09-09 15:08:12 +00008697
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008698 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008699
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008700 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008701 return;
Sam Weinigbae69142009-09-11 03:29:30 +00008702 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008703}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008704
Douglas Gregor5597ab42010-05-07 23:12:07 +00008705namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00008706 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00008707 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00008708 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00008709 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
8710 Sema &S;
8711 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00008712
Douglas Gregor5597ab42010-05-07 23:12:07 +00008713 public:
8714 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00008715
Douglas Gregor5597ab42010-05-07 23:12:07 +00008716 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00008717
8718 bool TraverseTemplateArgument(const TemplateArgument &Arg);
8719 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00008720 };
8721}
8722
Chandler Carruthaf80f662010-06-09 08:17:30 +00008723bool MarkReferencedDecls::TraverseTemplateArgument(
8724 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00008725 if (Arg.getKind() == TemplateArgument::Declaration) {
8726 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
8727 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00008728
8729 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00008730}
8731
Chandler Carruthaf80f662010-06-09 08:17:30 +00008732bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00008733 if (ClassTemplateSpecializationDecl *Spec
8734 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
8735 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008736 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00008737 }
8738
Chandler Carruthc65667c2010-06-10 10:31:57 +00008739 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00008740}
8741
8742void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
8743 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00008744 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00008745}
8746
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008747namespace {
8748 /// \brief Helper class that marks all of the declarations referenced by
8749 /// potentially-evaluated subexpressions as "referenced".
8750 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
8751 Sema &S;
8752
8753 public:
8754 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
8755
8756 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
8757
8758 void VisitDeclRefExpr(DeclRefExpr *E) {
8759 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
8760 }
8761
8762 void VisitMemberExpr(MemberExpr *E) {
8763 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00008764 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008765 }
8766
8767 void VisitCXXNewExpr(CXXNewExpr *E) {
8768 if (E->getConstructor())
8769 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
8770 if (E->getOperatorNew())
8771 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
8772 if (E->getOperatorDelete())
8773 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00008774 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008775 }
8776
8777 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
8778 if (E->getOperatorDelete())
8779 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00008780 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
8781 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
8782 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
8783 S.MarkDeclarationReferenced(E->getLocStart(),
8784 S.LookupDestructor(Record));
8785 }
8786
Douglas Gregor32b3de52010-09-11 23:32:50 +00008787 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008788 }
8789
8790 void VisitCXXConstructExpr(CXXConstructExpr *E) {
8791 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00008792 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008793 }
8794
8795 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
8796 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
8797 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00008798
8799 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
8800 Visit(E->getExpr());
8801 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008802 };
8803}
8804
8805/// \brief Mark any declarations that appear within this expression or any
8806/// potentially-evaluated subexpressions as "referenced".
8807void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
8808 EvaluatedExprMarker(*this).Visit(E);
8809}
8810
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008811/// \brief Emit a diagnostic that describes an effect on the run-time behavior
8812/// of the program being compiled.
8813///
8814/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008815/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008816/// possibility that the code will actually be executable. Code in sizeof()
8817/// expressions, code used only during overload resolution, etc., are not
8818/// potentially evaluated. This routine will suppress such diagnostics or,
8819/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008820/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008821/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008822///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008823/// This routine should be used for all diagnostics that describe the run-time
8824/// behavior of a program, such as passing a non-POD value through an ellipsis.
8825/// Failure to do so will likely result in spurious diagnostics or failures
8826/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008827bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008828 const PartialDiagnostic &PD) {
8829 switch (ExprEvalContexts.back().Context ) {
8830 case Unevaluated:
8831 // The argument will never be evaluated, so don't complain.
8832 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008833
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008834 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008835 case PotentiallyEvaluatedIfUsed:
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008836 Diag(Loc, PD);
8837 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008838
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008839 case PotentiallyPotentiallyEvaluated:
8840 ExprEvalContexts.back().addDiagnostic(Loc, PD);
8841 break;
8842 }
8843
8844 return false;
8845}
8846
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008847bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
8848 CallExpr *CE, FunctionDecl *FD) {
8849 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
8850 return false;
8851
8852 PartialDiagnostic Note =
8853 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
8854 << FD->getDeclName() : PDiag();
8855 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008856
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008857 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008858 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008859 PDiag(diag::err_call_function_incomplete_return)
8860 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008861 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008862 << CE->getSourceRange(),
8863 std::make_pair(NoteLoc, Note)))
8864 return true;
8865
8866 return false;
8867}
8868
John McCalld5707ab2009-10-12 21:59:07 +00008869// Diagnose the common s/=/==/ typo. Note that adding parentheses
8870// will prevent this condition from triggering, which is what we want.
8871void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
8872 SourceLocation Loc;
8873
John McCall0506e4a2009-11-11 02:41:58 +00008874 unsigned diagnostic = diag::warn_condition_is_assignment;
8875
John McCalld5707ab2009-10-12 21:59:07 +00008876 if (isa<BinaryOperator>(E)) {
8877 BinaryOperator *Op = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00008878 if (Op->getOpcode() != BO_Assign)
John McCalld5707ab2009-10-12 21:59:07 +00008879 return;
8880
John McCallb0e419e2009-11-12 00:06:05 +00008881 // Greylist some idioms by putting them into a warning subcategory.
8882 if (ObjCMessageExpr *ME
8883 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
8884 Selector Sel = ME->getSelector();
8885
John McCallb0e419e2009-11-12 00:06:05 +00008886 // self = [<foo> init...]
8887 if (isSelfExpr(Op->getLHS())
8888 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
8889 diagnostic = diag::warn_condition_is_idiomatic_assignment;
8890
8891 // <foo> = [<bar> nextObject]
8892 else if (Sel.isUnarySelector() &&
8893 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
8894 diagnostic = diag::warn_condition_is_idiomatic_assignment;
8895 }
John McCall0506e4a2009-11-11 02:41:58 +00008896
John McCalld5707ab2009-10-12 21:59:07 +00008897 Loc = Op->getOperatorLoc();
8898 } else if (isa<CXXOperatorCallExpr>(E)) {
8899 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
8900 if (Op->getOperator() != OO_Equal)
8901 return;
8902
8903 Loc = Op->getOperatorLoc();
8904 } else {
8905 // Not an assignment.
8906 return;
8907 }
8908
John McCalld5707ab2009-10-12 21:59:07 +00008909 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00008910 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008911
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008912 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008913 Diag(Loc, diag::note_condition_assign_to_comparison)
Douglas Gregora771f462010-03-31 17:46:05 +00008914 << FixItHint::CreateReplacement(Loc, "==");
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008915 Diag(Loc, diag::note_condition_assign_silence)
8916 << FixItHint::CreateInsertion(Open, "(")
8917 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +00008918}
8919
8920bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
8921 DiagnoseAssignmentAsCondition(E);
8922
8923 if (!E->isTypeDependent()) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00008924 if (E->isBoundMemberFunction(Context))
8925 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
8926 << E->getSourceRange();
8927
Douglas Gregorb92a1562010-02-03 00:27:59 +00008928 DefaultFunctionArrayLvalueConversion(E);
John McCalld5707ab2009-10-12 21:59:07 +00008929
8930 QualType T = E->getType();
8931
8932 if (getLangOptions().CPlusPlus) {
8933 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
8934 return true;
8935 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
8936 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
8937 << T << E->getSourceRange();
8938 return true;
8939 }
8940 }
8941
8942 return false;
8943}
Douglas Gregore60e41a2010-05-06 17:25:47 +00008944
John McCalldadc5752010-08-24 06:29:42 +00008945ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
8946 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00008947 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00008948 return ExprError();
8949
Douglas Gregorb412e172010-07-25 18:17:45 +00008950 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00008951 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00008952
8953 return Owned(Sub);
8954}
John McCall36e7fe32010-10-12 00:20:44 +00008955
8956/// Check for operands with placeholder types and complain if found.
8957/// Returns true if there was an error and no recovery was possible.
8958ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
8959 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
8960 if (!BT || !BT->isPlaceholderType()) return Owned(E);
8961
8962 // If this is overload, check for a single overload.
8963 if (BT->getKind() == BuiltinType::Overload) {
8964 if (FunctionDecl *Specialization
8965 = ResolveSingleFunctionTemplateSpecialization(E)) {
8966 // The access doesn't really matter in this case.
8967 DeclAccessPair Found = DeclAccessPair::make(Specialization,
8968 Specialization->getAccess());
8969 E = FixOverloadedFunctionReference(E, Found, Specialization);
8970 if (!E) return ExprError();
8971 return Owned(E);
8972 }
8973
John McCall36226622010-10-12 02:09:17 +00008974 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
John McCall36e7fe32010-10-12 00:20:44 +00008975 return ExprError();
8976 }
8977
8978 // Otherwise it's a use of undeduced auto.
8979 assert(BT->getKind() == BuiltinType::UndeducedAuto);
8980
8981 DeclRefExpr *DRE = cast<DeclRefExpr>(E->IgnoreParens());
8982 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
8983 << DRE->getDecl() << E->getSourceRange();
8984 return ExprError();
8985}