blob: 429804d6e93affc63f0e14a460c603457f5df140 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/ASTContext.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000023#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000024#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000026#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000027#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000031#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000033#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Designator.h"
35#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000036#include "clang/Sema/ScopeInfo.h"
John McCall19510852010-08-20 18:27:03 +000037#include "clang/Sema/ParsedTemplate.h"
John McCall7cd088e2010-08-24 07:21:54 +000038#include "clang/Sema/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000039using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000040using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000041
David Chisnall0f436562009-08-17 16:35:33 +000042
Douglas Gregor48f3bb92009-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///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000052/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattner52338262009-10-25 22:31:57 +000053/// decls.
54///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000055/// \returns true if there was an error (this declaration cannot be
56/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000057///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000058bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Peter Collingbourne743b82b2011-01-02 19:53:12 +000059 bool UnknownObjCClass) {
Douglas Gregor9b623632010-10-12 23:32:35 +000060 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
61 // If there were any diagnostics suppressed by template argument deduction,
62 // emit them now.
63 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
64 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
65 if (Pos != SuppressedDiagnostics.end()) {
66 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
67 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
68 Diag(Suppressed[I].first, Suppressed[I].second);
69
70 // Clear out the list of suppressed diagnostics, so that we don't emit
71 // them again for this specialization. However, we don't remove this
72 // entry from the table, because we want to avoid ever emitting these
73 // diagnostics again.
74 Suppressed.clear();
75 }
76 }
77
Chris Lattner76a642f2009-02-15 22:43:40 +000078 // See if the decl is deprecated.
Benjamin Kramerce2d1862010-10-09 15:49:00 +000079 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>())
Peter Collingbourne743b82b2011-01-02 19:53:12 +000080 EmitDeprecationWarning(D, DA->getMessage(), Loc, UnknownObjCClass);
Chris Lattner76a642f2009-02-15 22:43:40 +000081
Chris Lattnerffb93682009-10-25 17:21:40 +000082 // See if the decl is unavailable
Fariborz Jahanianc784dc12010-10-06 23:12:32 +000083 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) {
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000084 if (UA->getMessage().empty()) {
Peter Collingbourne743b82b2011-01-02 19:53:12 +000085 if (!UnknownObjCClass)
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000086 Diag(Loc, diag::err_unavailable) << D->getDeclName();
87 else
88 Diag(Loc, diag::warn_unavailable_fwdclass_message)
89 << D->getDeclName();
90 }
91 else
Fariborz Jahanianc784dc12010-10-06 23:12:32 +000092 Diag(Loc, diag::err_unavailable_message)
Benjamin Kramerce2d1862010-10-09 15:49:00 +000093 << D->getDeclName() << UA->getMessage();
Chris Lattnerffb93682009-10-25 17:21:40 +000094 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
95 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000096
Douglas Gregor48f3bb92009-02-18 21:56:37 +000097 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000098 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000099 if (FD->isDeleted()) {
100 Diag(Loc, diag::err_deleted_function_use);
101 Diag(D->getLocation(), diag::note_unavailable_here) << true;
102 return true;
103 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000104 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000105
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000106 // Warn if this is used but marked unused.
107 if (D->hasAttr<UnusedAttr>())
108 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
109
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000110 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000111}
112
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000113/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +0000114/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000115/// attribute. It warns if call does not have the sentinel argument.
116///
117void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000118 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000119 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000120 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000121 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000122
123 // FIXME: In C++0x, if any of the arguments are parameter pack
124 // expansions, we can't check for the sentinel now.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000125 int sentinelPos = attr->getSentinel();
126 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +0000127
Mike Stump390b4cc2009-05-16 07:39:55 +0000128 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
129 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000130 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000131 bool warnNotEnoughArgs = false;
132 int isMethod = 0;
133 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
134 // skip over named parameters.
135 ObjCMethodDecl::param_iterator P, E = MD->param_end();
136 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
137 if (nullPos)
138 --nullPos;
139 else
140 ++i;
141 }
142 warnNotEnoughArgs = (P != E || i >= NumArgs);
143 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000144 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000145 // skip over named parameters.
146 ObjCMethodDecl::param_iterator P, E = FD->param_end();
147 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
148 if (nullPos)
149 --nullPos;
150 else
151 ++i;
152 }
153 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000154 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000155 // block or function pointer call.
156 QualType Ty = V->getType();
157 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000158 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000159 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
160 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000161 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
162 unsigned NumArgsInProto = Proto->getNumArgs();
163 unsigned k;
164 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
165 if (nullPos)
166 --nullPos;
167 else
168 ++i;
169 }
170 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
171 }
172 if (Ty->isBlockPointerType())
173 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000174 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000175 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000176 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000177 return;
178
179 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000180 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000181 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000182 return;
183 }
184 int sentinel = i;
185 while (sentinelPos > 0 && i < NumArgs-1) {
186 --sentinelPos;
187 ++i;
188 }
189 if (sentinelPos > 0) {
190 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000191 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000192 return;
193 }
194 while (i < NumArgs-1) {
195 ++i;
196 ++sentinel;
197 }
198 Expr *sentinelExpr = Args[sentinel];
John McCall8eb662e2010-05-06 23:53:00 +0000199 if (!sentinelExpr) return;
200 if (sentinelExpr->isTypeDependent()) return;
201 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000202
203 // nullptr_t is always treated as null.
204 if (sentinelExpr->getType()->isNullPtrType()) return;
205
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000206 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000207 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
208 Expr::NPC_ValueDependentIsNull))
209 return;
210
211 // Unfortunately, __null has type 'int'.
212 if (isa<GNUNullExpr>(sentinelExpr)) return;
213
214 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
215 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000216}
217
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000218SourceRange Sema::getExprRange(ExprTy *E) const {
219 Expr *Ex = (Expr *)E;
220 return Ex? Ex->getSourceRange() : SourceRange();
221}
222
Chris Lattnere7a2e912008-07-25 21:10:04 +0000223//===----------------------------------------------------------------------===//
224// Standard Promotions and Conversions
225//===----------------------------------------------------------------------===//
226
Chris Lattnere7a2e912008-07-25 21:10:04 +0000227/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
228void Sema::DefaultFunctionArrayConversion(Expr *&E) {
229 QualType Ty = E->getType();
230 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
231
Chris Lattnere7a2e912008-07-25 21:10:04 +0000232 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000233 ImpCastExprToType(E, Context.getPointerType(Ty),
John McCall2de56d12010-08-25 11:45:40 +0000234 CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000235 else if (Ty->isArrayType()) {
236 // In C90 mode, arrays only promote to pointers if the array expression is
237 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
238 // type 'array of type' is converted to an expression that has type 'pointer
239 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
240 // that has type 'array of type' ...". The relevant change is "an lvalue"
241 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000242 //
243 // C++ 4.2p1:
244 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
245 // T" can be converted to an rvalue of type "pointer to T".
246 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000247 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
Anders Carlsson112a0a82009-08-07 23:48:20 +0000248 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
John McCall2de56d12010-08-25 11:45:40 +0000249 CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000250 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000251}
252
John McCall409fa9a2010-12-06 20:48:59 +0000253void Sema::DefaultLvalueConversion(Expr *&E) {
John McCall0ae287a2010-12-01 04:43:34 +0000254 // C++ [conv.lval]p1:
255 // A glvalue of a non-function, non-array type T can be
256 // converted to a prvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000257 if (!E->isGLValue()) return;
John McCallf6a16482010-12-04 03:47:34 +0000258
John McCall409fa9a2010-12-06 20:48:59 +0000259 QualType T = E->getType();
260 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000261
John McCall409fa9a2010-12-06 20:48:59 +0000262 // Create a load out of an ObjCProperty l-value, if necessary.
263 if (E->getObjectKind() == OK_ObjCProperty) {
264 ConvertPropertyForRValue(E);
265 if (!E->isGLValue())
John McCallf6a16482010-12-04 03:47:34 +0000266 return;
Douglas Gregora873dfc2010-02-03 00:27:59 +0000267 }
John McCall409fa9a2010-12-06 20:48:59 +0000268
269 // We don't want to throw lvalue-to-rvalue casts on top of
270 // expressions of certain types in C++.
271 if (getLangOptions().CPlusPlus &&
272 (E->getType() == Context.OverloadTy ||
273 T->isDependentType() ||
274 T->isRecordType()))
275 return;
276
277 // The C standard is actually really unclear on this point, and
278 // DR106 tells us what the result should be but not why. It's
279 // generally best to say that void types just doesn't undergo
280 // lvalue-to-rvalue at all. Note that expressions of unqualified
281 // 'void' type are never l-values, but qualified void can be.
282 if (T->isVoidType())
283 return;
284
285 // C++ [conv.lval]p1:
286 // [...] If T is a non-class type, the type of the prvalue is the
287 // cv-unqualified version of T. Otherwise, the type of the
288 // rvalue is T.
289 //
290 // C99 6.3.2.1p2:
291 // If the lvalue has qualified type, the value has the unqualified
292 // version of the type of the lvalue; otherwise, the value has the
293 // type of the lvalue.
294 if (T.hasQualifiers())
295 T = T.getUnqualifiedType();
296
297 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
298 E, 0, VK_RValue);
299}
300
301void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
302 DefaultFunctionArrayConversion(E);
303 DefaultLvalueConversion(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000304}
305
306
Chris Lattnere7a2e912008-07-25 21:10:04 +0000307/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000308/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000309/// sometimes surpressed. For example, the array->pointer conversion doesn't
310/// apply if the array is an argument to the sizeof or address (&) operators.
311/// In these instances, this routine should *not* be called.
John McCall0ae287a2010-12-01 04:43:34 +0000312Expr *Sema::UsualUnaryConversions(Expr *&E) {
313 // First, convert to an r-value.
314 DefaultFunctionArrayLvalueConversion(E);
315
316 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000317 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000318
319 // Try to perform integral promotions if the object has a theoretically
320 // promotable type.
321 if (Ty->isIntegralOrUnscopedEnumerationType()) {
322 // C99 6.3.1.1p2:
323 //
324 // The following may be used in an expression wherever an int or
325 // unsigned int may be used:
326 // - an object or expression with an integer type whose integer
327 // conversion rank is less than or equal to the rank of int
328 // and unsigned int.
329 // - A bit-field of type _Bool, int, signed int, or unsigned int.
330 //
331 // If an int can represent all values of the original type, the
332 // value is converted to an int; otherwise, it is converted to an
333 // unsigned int. These are called the integer promotions. All
334 // other types are unchanged by the integer promotions.
335
336 QualType PTy = Context.isPromotableBitField(E);
337 if (!PTy.isNull()) {
338 ImpCastExprToType(E, PTy, CK_IntegralCast);
339 return E;
340 }
341 if (Ty->isPromotableIntegerType()) {
342 QualType PT = Context.getPromotedIntegerType(Ty);
343 ImpCastExprToType(E, PT, CK_IntegralCast);
344 return E;
345 }
Eli Friedman04e83572009-08-20 04:21:42 +0000346 }
347
John McCall0ae287a2010-12-01 04:43:34 +0000348 return E;
Chris Lattnere7a2e912008-07-25 21:10:04 +0000349}
350
Chris Lattner05faf172008-07-25 22:25:12 +0000351/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000352/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000353/// double. All other argument types are converted by UsualUnaryConversions().
354void Sema::DefaultArgumentPromotion(Expr *&Expr) {
355 QualType Ty = Expr->getType();
356 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000357
John McCall40c29132010-12-06 18:36:11 +0000358 UsualUnaryConversions(Expr);
359
Chris Lattner05faf172008-07-25 22:25:12 +0000360 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000361 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John McCall40c29132010-12-06 18:36:11 +0000362 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
Chris Lattner05faf172008-07-25 22:25:12 +0000363}
364
Chris Lattner312531a2009-04-12 08:11:20 +0000365/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
366/// will warn if the resulting type is not a POD type, and rejects ObjC
367/// interfaces passed by value. This returns true if the argument type is
368/// completely illegal.
Chris Lattner40378332010-05-16 04:01:30 +0000369bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
370 FunctionDecl *FDecl) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000371 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Chris Lattner40378332010-05-16 04:01:30 +0000373 // __builtin_va_start takes the second argument as a "varargs" argument, but
374 // it doesn't actually do anything with it. It doesn't need to be non-pod
375 // etc.
376 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
377 return false;
378
John McCallc12c5bb2010-05-15 11:32:37 +0000379 if (Expr->getType()->isObjCObjectType() &&
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000380 DiagRuntimeBehavior(Expr->getLocStart(),
381 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
382 << Expr->getType() << CT))
383 return true;
Douglas Gregor75b699a2009-12-12 07:25:49 +0000384
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000385 if (!Expr->getType()->isPODType() &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000386 DiagRuntimeBehavior(Expr->getLocStart(),
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000387 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
388 << Expr->getType() << CT))
389 return true;
Chris Lattner312531a2009-04-12 08:11:20 +0000390
391 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000392}
393
Chris Lattnere7a2e912008-07-25 21:10:04 +0000394/// UsualArithmeticConversions - Performs various conversions that are common to
395/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000396/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000397/// responsible for emitting appropriate error diagnostics.
398/// FIXME: verify the conversion rules for "complex int" are consistent with
399/// GCC.
400QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
401 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000402 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000403 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000404
405 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000406
Mike Stump1eb44332009-09-09 15:08:12 +0000407 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000408 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000409 QualType lhs =
410 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000411 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000412 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000413
414 // If both types are identical, no conversion is needed.
415 if (lhs == rhs)
416 return lhs;
417
418 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
419 // The caller can deal with this (e.g. pointer + int).
420 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
421 return lhs;
422
John McCallcf33b242010-11-13 08:17:45 +0000423 // Apply unary and bitfield promotions to the LHS's type.
424 QualType lhs_unpromoted = lhs;
425 if (lhs->isPromotableIntegerType())
426 lhs = Context.getPromotedIntegerType(lhs);
Eli Friedman04e83572009-08-20 04:21:42 +0000427 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000428 if (!LHSBitfieldPromoteTy.isNull())
429 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000430 if (lhs != lhs_unpromoted && !isCompAssign)
431 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000432
John McCallcf33b242010-11-13 08:17:45 +0000433 // If both types are identical, no conversion is needed.
434 if (lhs == rhs)
435 return lhs;
436
437 // At this point, we have two different arithmetic types.
438
439 // Handle complex types first (C99 6.3.1.8p1).
440 bool LHSComplexFloat = lhs->isComplexType();
441 bool RHSComplexFloat = rhs->isComplexType();
442 if (LHSComplexFloat || RHSComplexFloat) {
443 // if we have an integer operand, the result is the complex type.
444
John McCall2bb5d002010-11-13 09:02:35 +0000445 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
446 if (rhs->isIntegerType()) {
447 QualType fp = cast<ComplexType>(lhs)->getElementType();
448 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
449 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
450 } else {
451 assert(rhs->isComplexIntegerType());
John McCallf3ea8cf2010-11-14 08:17:51 +0000452 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000453 }
John McCallcf33b242010-11-13 08:17:45 +0000454 return lhs;
455 }
456
John McCall2bb5d002010-11-13 09:02:35 +0000457 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
458 if (!isCompAssign) {
459 // int -> float -> _Complex float
460 if (lhs->isIntegerType()) {
461 QualType fp = cast<ComplexType>(rhs)->getElementType();
462 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
463 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
464 } else {
465 assert(lhs->isComplexIntegerType());
John McCallf3ea8cf2010-11-14 08:17:51 +0000466 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000467 }
468 }
John McCallcf33b242010-11-13 08:17:45 +0000469 return rhs;
470 }
471
472 // This handles complex/complex, complex/float, or float/complex.
473 // When both operands are complex, the shorter operand is converted to the
474 // type of the longer, and that is the type of the result. This corresponds
475 // to what is done when combining two real floating-point operands.
476 // The fun begins when size promotion occur across type domains.
477 // From H&S 6.3.4: When one operand is complex and the other is a real
478 // floating-point type, the less precise type is converted, within it's
479 // real or complex domain, to the precision of the other type. For example,
480 // when combining a "long double" with a "double _Complex", the
481 // "double _Complex" is promoted to "long double _Complex".
482 int order = Context.getFloatingTypeOrder(lhs, rhs);
483
484 // If both are complex, just cast to the more precise type.
485 if (LHSComplexFloat && RHSComplexFloat) {
486 if (order > 0) {
487 // _Complex float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000488 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000489 return lhs;
490
491 } else if (order < 0) {
492 // _Complex float -> _Complex double
493 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000494 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000495 return rhs;
496 }
497 return lhs;
498 }
499
500 // If just the LHS is complex, the RHS needs to be converted,
501 // and the LHS might need to be promoted.
502 if (LHSComplexFloat) {
503 if (order > 0) { // LHS is wider
504 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000505 QualType fp = cast<ComplexType>(lhs)->getElementType();
506 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
507 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000508 return lhs;
509 }
510
511 // RHS is at least as wide. Find its corresponding complex type.
512 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
513
514 // double -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000515 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000516
517 // _Complex float -> _Complex double
518 if (!isCompAssign && order < 0)
John McCall2bb5d002010-11-13 09:02:35 +0000519 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000520
521 return result;
522 }
523
524 // Just the RHS is complex, so the LHS needs to be converted
525 // and the RHS might need to be promoted.
526 assert(RHSComplexFloat);
527
528 if (order < 0) { // RHS is wider
529 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000530 if (!isCompAssign) {
Argyrios Kyrtzidise1889332011-01-18 18:49:33 +0000531 QualType fp = cast<ComplexType>(rhs)->getElementType();
532 ImpCastExprToType(lhsExpr, fp, CK_FloatingCast);
John McCall2bb5d002010-11-13 09:02:35 +0000533 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
534 }
John McCallcf33b242010-11-13 08:17:45 +0000535 return rhs;
536 }
537
538 // LHS is at least as wide. Find its corresponding complex type.
539 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
540
541 // double -> _Complex double
542 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000543 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000544
545 // _Complex float -> _Complex double
546 if (order > 0)
John McCall2bb5d002010-11-13 09:02:35 +0000547 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000548
549 return result;
550 }
551
552 // Now handle "real" floating types (i.e. float, double, long double).
553 bool LHSFloat = lhs->isRealFloatingType();
554 bool RHSFloat = rhs->isRealFloatingType();
555 if (LHSFloat || RHSFloat) {
556 // If we have two real floating types, convert the smaller operand
557 // to the bigger result.
558 if (LHSFloat && RHSFloat) {
559 int order = Context.getFloatingTypeOrder(lhs, rhs);
560 if (order > 0) {
561 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
562 return lhs;
563 }
564
565 assert(order < 0 && "illegal float comparison");
566 if (!isCompAssign)
567 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
568 return rhs;
569 }
570
571 // If we have an integer operand, the result is the real floating type.
572 if (LHSFloat) {
573 if (rhs->isIntegerType()) {
574 // Convert rhs to the lhs floating point type.
575 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
576 return lhs;
577 }
578
579 // Convert both sides to the appropriate complex float.
580 assert(rhs->isComplexIntegerType());
581 QualType result = Context.getComplexType(lhs);
582
583 // _Complex int -> _Complex float
John McCallf3ea8cf2010-11-14 08:17:51 +0000584 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000585
586 // float -> _Complex float
587 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000588 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000589
590 return result;
591 }
592
593 assert(RHSFloat);
594 if (lhs->isIntegerType()) {
595 // Convert lhs to the rhs floating point type.
596 if (!isCompAssign)
597 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
598 return rhs;
599 }
600
601 // Convert both sides to the appropriate complex float.
602 assert(lhs->isComplexIntegerType());
603 QualType result = Context.getComplexType(rhs);
604
605 // _Complex int -> _Complex float
606 if (!isCompAssign)
John McCallf3ea8cf2010-11-14 08:17:51 +0000607 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000608
609 // float -> _Complex float
John McCall2bb5d002010-11-13 09:02:35 +0000610 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000611
612 return result;
613 }
614
615 // Handle GCC complex int extension.
616 // FIXME: if the operands are (int, _Complex long), we currently
617 // don't promote the complex. Also, signedness?
618 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
619 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
620 if (lhsComplexInt && rhsComplexInt) {
621 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
622 rhsComplexInt->getElementType());
623 assert(order && "inequal types with equal element ordering");
624 if (order > 0) {
625 // _Complex int -> _Complex long
John McCall2bb5d002010-11-13 09:02:35 +0000626 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000627 return lhs;
628 }
629
630 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000631 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000632 return rhs;
633 } else if (lhsComplexInt) {
634 // int -> _Complex int
John McCall2bb5d002010-11-13 09:02:35 +0000635 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000636 return lhs;
637 } else if (rhsComplexInt) {
638 // int -> _Complex int
639 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000640 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000641 return rhs;
642 }
643
644 // Finally, we have two differing integer types.
645 // The rules for this case are in C99 6.3.1.8
646 int compare = Context.getIntegerTypeOrder(lhs, rhs);
647 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
648 rhsSigned = rhs->hasSignedIntegerRepresentation();
649 if (lhsSigned == rhsSigned) {
650 // Same signedness; use the higher-ranked type
651 if (compare >= 0) {
652 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
653 return lhs;
654 } else if (!isCompAssign)
655 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
656 return rhs;
657 } else if (compare != (lhsSigned ? 1 : -1)) {
658 // The unsigned type has greater than or equal rank to the
659 // signed type, so use the unsigned type
660 if (rhsSigned) {
661 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
662 return lhs;
663 } else if (!isCompAssign)
664 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
665 return rhs;
666 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
667 // The two types are different widths; if we are here, that
668 // means the signed type is larger than the unsigned type, so
669 // use the signed type.
670 if (lhsSigned) {
671 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
672 return lhs;
673 } else if (!isCompAssign)
674 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
675 return rhs;
676 } else {
677 // The signed type is higher-ranked than the unsigned type,
678 // but isn't actually any bigger (like unsigned int and long
679 // on most 32-bit systems). Use the unsigned type corresponding
680 // to the signed type.
681 QualType result =
682 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
683 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
684 if (!isCompAssign)
685 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
686 return result;
687 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000688}
689
Chris Lattnere7a2e912008-07-25 21:10:04 +0000690//===----------------------------------------------------------------------===//
691// Semantic Analysis for various Expression Types
692//===----------------------------------------------------------------------===//
693
694
Steve Narofff69936d2007-09-16 03:34:24 +0000695/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000696/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
697/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
698/// multiple tokens. However, the common case is that StringToks points to one
699/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000700///
John McCall60d7b3a2010-08-24 06:29:42 +0000701ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +0000702Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000703 assert(NumStringToks && "Must have at least one string!");
704
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000705 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000706 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000707 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000708
709 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
710 for (unsigned i = 0; i != NumStringToks; ++i)
711 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000712
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000713 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000714 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000715 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000716
717 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +0000718 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +0000719 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000720
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000721 // Get an array type for the string, according to C99 6.4.5. This includes
722 // the nul terminator character as well as the string length for pascal
723 // strings.
724 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000725 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000726 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +0000729 return Owned(StringLiteral::Create(Context, Literal.GetString(),
730 Literal.GetStringLength(),
731 Literal.AnyWide, StrTy,
732 &StringTokLocs[0],
733 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000734}
735
John McCall469a1eb2011-02-02 13:00:07 +0000736enum CaptureResult {
737 /// No capture is required.
738 CR_NoCapture,
739
740 /// A capture is required.
741 CR_Capture,
742
John McCall6b5a61b2011-02-07 10:33:21 +0000743 /// A by-ref capture is required.
744 CR_CaptureByRef,
745
John McCall469a1eb2011-02-02 13:00:07 +0000746 /// An error occurred when trying to capture the given variable.
747 CR_Error
748};
749
750/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +0000751///
John McCall469a1eb2011-02-02 13:00:07 +0000752/// \param var - the variable referenced
753/// \param DC - the context which we couldn't capture through
754static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +0000755diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +0000756 VarDecl *var, DeclContext *DC) {
757 switch (S.ExprEvalContexts.back().Context) {
758 case Sema::Unevaluated:
759 // The argument will never be evaluated, so don't complain.
760 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +0000761
John McCall469a1eb2011-02-02 13:00:07 +0000762 case Sema::PotentiallyEvaluated:
763 case Sema::PotentiallyEvaluatedIfUsed:
764 break;
Chris Lattner639e2d32008-10-20 05:16:36 +0000765
John McCall469a1eb2011-02-02 13:00:07 +0000766 case Sema::PotentiallyPotentiallyEvaluated:
767 // FIXME: delay these!
768 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000769 }
Mike Stump1eb44332009-09-09 15:08:12 +0000770
John McCall469a1eb2011-02-02 13:00:07 +0000771 // Don't diagnose about capture if we're not actually in code right
772 // now; in general, there are more appropriate places that will
773 // diagnose this.
774 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
775
776 // This particular madness can happen in ill-formed default
777 // arguments; claim it's okay and let downstream code handle it.
778 if (isa<ParmVarDecl>(var) &&
779 S.CurContext == var->getDeclContext()->getParent())
780 return CR_NoCapture;
781
782 DeclarationName functionName;
783 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
784 functionName = fn->getDeclName();
785 // FIXME: variable from enclosing block that we couldn't capture from!
786
787 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
788 << var->getIdentifier() << functionName;
789 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
790 << var->getIdentifier();
791
792 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +0000793}
794
John McCall6b5a61b2011-02-07 10:33:21 +0000795/// There is a well-formed capture at a particular scope level;
796/// propagate it through all the nested blocks.
797static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
798 const BlockDecl::Capture &capture) {
799 VarDecl *var = capture.getVariable();
800
801 // Update all the inner blocks with the capture information.
802 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
803 i != e; ++i) {
804 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
805 innerBlock->Captures.push_back(
806 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
807 /*nested*/ true, capture.getCopyExpr()));
808 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
809 }
810
811 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
812}
813
814/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +0000815/// given value in the current context requires a variable capture.
816///
817/// This also keeps the captures set in the BlockScopeInfo records
818/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +0000819static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +0000820 ValueDecl *value) {
821 // Only variables ever require capture.
822 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +0000823 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +0000824
825 // Fast path: variables from the current context never require capture.
826 DeclContext *DC = S.CurContext;
827 if (var->getDeclContext() == DC) return CR_NoCapture;
828
829 // Only variables with local storage require capture.
830 // FIXME: What about 'const' variables in C++?
831 if (!var->hasLocalStorage()) return CR_NoCapture;
832
833 // Otherwise, we need to capture.
834
835 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +0000836 do {
837 // Only blocks (and eventually C++0x closures) can capture; other
838 // scopes don't work.
839 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +0000840 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +0000841
842 BlockScopeInfo *blockScope =
843 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
844 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
845
John McCall6b5a61b2011-02-07 10:33:21 +0000846 // Check whether we've already captured it in this block. If so,
847 // we're done.
848 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
849 return propagateCapture(S, functionScopesIndex,
850 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +0000851
852 functionScopesIndex--;
853 DC = cast<BlockDecl>(DC)->getDeclContext();
854 } while (var->getDeclContext() != DC);
855
John McCall6b5a61b2011-02-07 10:33:21 +0000856 // Okay, we descended all the way to the block that defines the variable.
857 // Actually try to capture it.
858 QualType type = var->getType();
859
860 // Prohibit variably-modified types.
861 if (type->isVariablyModifiedType()) {
862 S.Diag(loc, diag::err_ref_vm_type);
863 S.Diag(var->getLocation(), diag::note_declared_at);
864 return CR_Error;
865 }
866
867 // Prohibit arrays, even in __block variables, but not references to
868 // them.
869 if (type->isArrayType()) {
870 S.Diag(loc, diag::err_ref_array_type);
871 S.Diag(var->getLocation(), diag::note_declared_at);
872 return CR_Error;
873 }
874
875 S.MarkDeclarationReferenced(loc, var);
876
877 // The BlocksAttr indicates the variable is bound by-reference.
878 bool byRef = var->hasAttr<BlocksAttr>();
879
880 // Build a copy expression.
881 Expr *copyExpr = 0;
882 if (!byRef && S.getLangOptions().CPlusPlus &&
883 !type->isDependentType() && type->isStructureOrClassType()) {
884 // According to the blocks spec, the capture of a variable from
885 // the stack requires a const copy constructor. This is not true
886 // of the copy/move done to move a __block variable to the heap.
887 type.addConst();
888
889 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
890 ExprResult result =
891 S.PerformCopyInitialization(
892 InitializedEntity::InitializeBlock(var->getLocation(),
893 type, false),
894 loc, S.Owned(declRef));
895
896 // Build a full-expression copy expression if initialization
897 // succeeded and used a non-trivial constructor. Recover from
898 // errors by pretending that the copy isn't necessary.
899 if (!result.isInvalid() &&
900 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
901 result = S.MaybeCreateExprWithCleanups(result);
902 copyExpr = result.take();
903 }
904 }
905
906 // We're currently at the declarer; go back to the closure.
907 functionScopesIndex++;
908 BlockScopeInfo *blockScope =
909 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
910
911 // Build a valid capture in this scope.
912 blockScope->Captures.push_back(
913 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
914 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
915
916 // Propagate that to inner captures if necessary.
917 return propagateCapture(S, functionScopesIndex,
918 blockScope->Captures.back());
919}
920
921static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
922 const DeclarationNameInfo &NameInfo,
923 bool byRef) {
924 assert(isa<VarDecl>(vd) && "capturing non-variable");
925
926 VarDecl *var = cast<VarDecl>(vd);
927 assert(var->hasLocalStorage() && "capturing non-local");
928 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
929
930 QualType exprType = var->getType().getNonReferenceType();
931
932 BlockDeclRefExpr *BDRE;
933 if (!byRef) {
934 // The variable will be bound by copy; make it const within the
935 // closure, but record that this was done in the expression.
936 bool constAdded = !exprType.isConstQualified();
937 exprType.addConst();
938
939 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
940 NameInfo.getLoc(), false,
941 constAdded);
942 } else {
943 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
944 NameInfo.getLoc(), true);
945 }
946
947 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +0000948}
Chris Lattner639e2d32008-10-20 05:16:36 +0000949
John McCall60d7b3a2010-08-24 06:29:42 +0000950ExprResult
John McCallf89e55a2010-11-18 06:31:45 +0000951Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +0000952 SourceLocation Loc,
953 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000954 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +0000955 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +0000956}
957
John McCall76a40212011-02-09 01:13:10 +0000958/// BuildDeclRefExpr - Build an expression that references a
959/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +0000960ExprResult
John McCall76a40212011-02-09 01:13:10 +0000961Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +0000962 const DeclarationNameInfo &NameInfo,
963 const CXXScopeSpec *SS) {
John McCall76a40212011-02-09 01:13:10 +0000964 if (Ty == Context.UndeducedAutoTy) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000965 Diag(NameInfo.getLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +0000966 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000967 << D->getDeclName();
968 return ExprError();
969 }
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Abramo Bagnara25777432010-08-11 22:01:17 +0000971 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +0000972
John McCall7eb0a9e2010-11-24 05:12:34 +0000973 Expr *E = DeclRefExpr::Create(Context,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000974 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
John McCall7eb0a9e2010-11-24 05:12:34 +0000975 SS? SS->getRange() : SourceRange(),
976 D, NameInfo, Ty, VK);
977
978 // Just in case we're building an illegal pointer-to-member.
979 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
980 E->setObjectKind(OK_BitField);
981
982 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +0000983}
984
John McCalldfa1edb2010-11-23 20:48:44 +0000985static ExprResult
986BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
987 const CXXScopeSpec &SS, FieldDecl *Field,
988 DeclAccessPair FoundDecl,
989 const DeclarationNameInfo &MemberNameInfo);
990
John McCall60d7b3a2010-08-24 06:29:42 +0000991ExprResult
John McCall5808ce42011-02-03 08:15:49 +0000992Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
993 SourceLocation loc,
994 IndirectFieldDecl *indirectField,
995 Expr *baseObjectExpr,
996 SourceLocation opLoc) {
997 // First, build the expression that refers to the base object.
998
999 bool baseObjectIsPointer = false;
1000 Qualifiers baseQuals;
1001
1002 // Case 1: the base of the indirect field is not a field.
1003 VarDecl *baseVariable = indirectField->getVarDecl();
1004 if (baseVariable) {
1005 assert(baseVariable->getType()->isRecordType());
1006
1007 // In principle we could have a member access expression that
1008 // accesses an anonymous struct/union that's a static member of
1009 // the base object's class. However, under the current standard,
1010 // static data members cannot be anonymous structs or unions.
1011 // Supporting this is as easy as building a MemberExpr here.
1012 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1013
1014 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1015
1016 ExprResult result =
1017 BuildDeclarationNameExpr(SS, baseNameInfo, baseVariable);
1018 if (result.isInvalid()) return ExprError();
1019
1020 baseObjectExpr = result.take();
1021 baseObjectIsPointer = false;
1022 baseQuals = baseObjectExpr->getType().getQualifiers();
1023
1024 // Case 2: the base of the indirect field is a field and the user
1025 // wrote a member expression.
1026 } else if (baseObjectExpr) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001027 // The caller provided the base object expression. Determine
1028 // whether its a pointer and whether it adds any qualifiers to the
1029 // anonymous struct/union fields we're looking into.
John McCall5808ce42011-02-03 08:15:49 +00001030 QualType objectType = baseObjectExpr->getType();
1031
1032 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1033 baseObjectIsPointer = true;
1034 objectType = ptr->getPointeeType();
1035 } else {
1036 baseObjectIsPointer = false;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001037 }
John McCall5808ce42011-02-03 08:15:49 +00001038 baseQuals = objectType.getQualifiers();
1039
1040 // Case 3: the base of the indirect field is a field and we should
1041 // build an implicit member access.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001042 } else {
1043 // We've found a member of an anonymous struct/union that is
1044 // inside a non-anonymous struct/union, so in a well-formed
1045 // program our base object expression is "this".
John McCall5808ce42011-02-03 08:15:49 +00001046 CXXMethodDecl *method = tryCaptureCXXThis();
1047 if (!method) {
1048 Diag(loc, diag::err_invalid_member_use_in_static_method)
1049 << indirectField->getDeclName();
1050 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001051 }
1052
John McCall5808ce42011-02-03 08:15:49 +00001053 // Our base object expression is "this".
1054 baseObjectExpr =
1055 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1056 /*isImplicit=*/ true);
1057 baseObjectIsPointer = true;
1058 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001059 }
1060
1061 // Build the implicit member references to the field of the
1062 // anonymous struct/union.
John McCall5808ce42011-02-03 08:15:49 +00001063 Expr *result = baseObjectExpr;
1064 IndirectFieldDecl::chain_iterator
1065 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCalldfa1edb2010-11-23 20:48:44 +00001066
John McCall5808ce42011-02-03 08:15:49 +00001067 // Build the first member access in the chain with full information.
1068 if (!baseVariable) {
1069 FieldDecl *field = cast<FieldDecl>(*FI);
John McCalldfa1edb2010-11-23 20:48:44 +00001070
John McCall5808ce42011-02-03 08:15:49 +00001071 // FIXME: use the real found-decl info!
1072 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall0953e762009-09-24 19:53:00 +00001073
John McCall5808ce42011-02-03 08:15:49 +00001074 // Make a nameInfo that properly uses the anonymous name.
1075 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall0953e762009-09-24 19:53:00 +00001076
John McCall5808ce42011-02-03 08:15:49 +00001077 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
1078 SS, field, foundDecl,
1079 memberNameInfo).take();
1080 baseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +00001081
John McCall5808ce42011-02-03 08:15:49 +00001082 // FIXME: check qualified member access
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001083 }
1084
John McCall5808ce42011-02-03 08:15:49 +00001085 // In all cases, we should now skip the first declaration in the chain.
1086 ++FI;
1087
1088 for (; FI != FEnd; FI++) {
1089 FieldDecl *field = cast<FieldDecl>(*FI);
1090
1091 // FIXME: these are somewhat meaningless
1092 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1093 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
1094 CXXScopeSpec memberSS;
1095
1096 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
1097 memberSS, field, foundDecl, memberNameInfo)
1098 .take();
1099 }
1100
1101 return Owned(result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001102}
1103
Abramo Bagnara25777432010-08-11 22:01:17 +00001104/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001105/// possibly a list of template arguments.
1106///
1107/// If this produces template arguments, it is permitted to call
1108/// DecomposeTemplateName.
1109///
1110/// This actually loses a lot of source location information for
1111/// non-standard name kinds; we should consider preserving that in
1112/// some way.
1113static void DecomposeUnqualifiedId(Sema &SemaRef,
1114 const UnqualifiedId &Id,
1115 TemplateArgumentListInfo &Buffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00001116 DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00001117 const TemplateArgumentListInfo *&TemplateArgs) {
1118 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1119 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1120 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1121
1122 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1123 Id.TemplateId->getTemplateArgs(),
1124 Id.TemplateId->NumArgs);
1125 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1126 TemplateArgsPtr.release();
1127
John McCall2b5289b2010-08-23 07:28:44 +00001128 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001129 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1130 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001131 TemplateArgs = &Buffer;
1132 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001133 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001134 TemplateArgs = 0;
1135 }
1136}
1137
John McCallaa81e162009-12-01 22:10:20 +00001138/// Determines if the given class is provably not derived from all of
1139/// the prospective base classes.
1140static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1141 CXXRecordDecl *Record,
1142 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +00001143 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +00001144 return false;
1145
Douglas Gregor952b0172010-02-11 01:04:33 +00001146 RecordDecl *RD = Record->getDefinition();
John McCallb1b42562009-12-01 22:28:41 +00001147 if (!RD) return false;
1148 Record = cast<CXXRecordDecl>(RD);
1149
John McCallaa81e162009-12-01 22:10:20 +00001150 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1151 E = Record->bases_end(); I != E; ++I) {
1152 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1153 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1154 if (!BaseRT) return false;
1155
1156 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +00001157 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1158 return false;
1159 }
1160
1161 return true;
1162}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001163
John McCallaa81e162009-12-01 22:10:20 +00001164enum IMAKind {
1165 /// The reference is definitely not an instance member access.
1166 IMA_Static,
1167
1168 /// The reference may be an implicit instance member access.
1169 IMA_Mixed,
1170
1171 /// The reference may be to an instance member, but it is invalid if
1172 /// so, because the context is not an instance method.
1173 IMA_Mixed_StaticContext,
1174
1175 /// The reference may be to an instance member, but it is invalid if
1176 /// so, because the context is from an unrelated class.
1177 IMA_Mixed_Unrelated,
1178
1179 /// The reference is definitely an implicit instance member access.
1180 IMA_Instance,
1181
1182 /// The reference may be to an unresolved using declaration.
1183 IMA_Unresolved,
1184
1185 /// The reference may be to an unresolved using declaration and the
1186 /// context is not an instance method.
1187 IMA_Unresolved_StaticContext,
1188
John McCallaa81e162009-12-01 22:10:20 +00001189 /// All possible referrents are instance members and the current
1190 /// context is not an instance method.
1191 IMA_Error_StaticContext,
1192
1193 /// All possible referrents are instance members of an unrelated
1194 /// class.
1195 IMA_Error_Unrelated
1196};
1197
1198/// The given lookup names class member(s) and is not being used for
1199/// an address-of-member expression. Classify the type of access
1200/// according to whether it's possible that this reference names an
1201/// instance member. This is best-effort; it is okay to
1202/// conservatively answer "yes", in which case some errors will simply
1203/// not be caught until template-instantiation.
1204static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1205 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +00001206 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +00001207
John McCallea1471e2010-05-20 01:18:31 +00001208 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCallaa81e162009-12-01 22:10:20 +00001209 bool isStaticContext =
John McCallea1471e2010-05-20 01:18:31 +00001210 (!isa<CXXMethodDecl>(DC) ||
1211 cast<CXXMethodDecl>(DC)->isStatic());
John McCallaa81e162009-12-01 22:10:20 +00001212
1213 if (R.isUnresolvableResult())
1214 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1215
1216 // Collect all the declaring classes of instance members we find.
1217 bool hasNonInstance = false;
Sebastian Redlf9780002010-11-26 16:28:07 +00001218 bool hasField = false;
John McCallaa81e162009-12-01 22:10:20 +00001219 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1220 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall161755a2010-04-06 21:38:20 +00001221 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00001222
John McCall161755a2010-04-06 21:38:20 +00001223 if (D->isCXXInstanceMember()) {
Sebastian Redlf9780002010-11-26 16:28:07 +00001224 if (dyn_cast<FieldDecl>(D))
1225 hasField = true;
1226
John McCallaa81e162009-12-01 22:10:20 +00001227 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCallaa81e162009-12-01 22:10:20 +00001228 Classes.insert(R->getCanonicalDecl());
1229 }
1230 else
1231 hasNonInstance = true;
1232 }
1233
1234 // If we didn't find any instance members, it can't be an implicit
1235 // member reference.
1236 if (Classes.empty())
1237 return IMA_Static;
1238
1239 // If the current context is not an instance method, it can't be
1240 // an implicit member reference.
Sebastian Redlf9780002010-11-26 16:28:07 +00001241 if (isStaticContext) {
1242 if (hasNonInstance)
1243 return IMA_Mixed_StaticContext;
1244
1245 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1246 // C++0x [expr.prim.general]p10:
1247 // An id-expression that denotes a non-static data member or non-static
1248 // member function of a class can only be used:
1249 // (...)
1250 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1251 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1252 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1253 if (isUnevaluatedExpression)
1254 return IMA_Mixed_StaticContext;
1255 }
1256
1257 return IMA_Error_StaticContext;
1258 }
John McCallaa81e162009-12-01 22:10:20 +00001259
1260 // If we can prove that the current context is unrelated to all the
1261 // declaring classes, it can't be an implicit member reference (in
1262 // which case it's an error if any of those members are selected).
1263 if (IsProvablyNotDerivedFrom(SemaRef,
John McCallea1471e2010-05-20 01:18:31 +00001264 cast<CXXMethodDecl>(DC)->getParent(),
John McCallaa81e162009-12-01 22:10:20 +00001265 Classes))
1266 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1267
1268 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1269}
1270
1271/// Diagnose a reference to a field with no object available.
1272static void DiagnoseInstanceReference(Sema &SemaRef,
1273 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00001274 NamedDecl *rep,
1275 const DeclarationNameInfo &nameInfo) {
1276 SourceLocation Loc = nameInfo.getLoc();
John McCallaa81e162009-12-01 22:10:20 +00001277 SourceRange Range(Loc);
1278 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1279
John McCall5808ce42011-02-03 08:15:49 +00001280 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCallaa81e162009-12-01 22:10:20 +00001281 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1282 if (MD->isStatic()) {
1283 // "invalid use of member 'x' in static member function"
1284 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCall5808ce42011-02-03 08:15:49 +00001285 << Range << nameInfo.getName();
John McCallaa81e162009-12-01 22:10:20 +00001286 return;
1287 }
1288 }
1289
1290 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCall5808ce42011-02-03 08:15:49 +00001291 << nameInfo.getName() << Range;
John McCallaa81e162009-12-01 22:10:20 +00001292 return;
1293 }
1294
1295 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +00001296}
1297
John McCall578b69b2009-12-16 08:11:27 +00001298/// Diagnose an empty lookup.
1299///
1300/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001301bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1302 CorrectTypoContext CTC) {
John McCall578b69b2009-12-16 08:11:27 +00001303 DeclarationName Name = R.getLookupName();
1304
John McCall578b69b2009-12-16 08:11:27 +00001305 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001306 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001307 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1308 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001309 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001310 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001311 diagnostic_suggest = diag::err_undeclared_use_suggest;
1312 }
John McCall578b69b2009-12-16 08:11:27 +00001313
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001314 // If the original lookup was an unqualified lookup, fake an
1315 // unqualified lookup. This is useful when (for example) the
1316 // original lookup would not have found something because it was a
1317 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001318 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001319 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001320 if (isa<CXXRecordDecl>(DC)) {
1321 LookupQualifiedName(R, DC);
1322
1323 if (!R.empty()) {
1324 // Don't give errors about ambiguities in this lookup.
1325 R.suppressDiagnostics();
1326
1327 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1328 bool isInstance = CurMethod &&
1329 CurMethod->isInstance() &&
1330 DC == CurMethod->getParent();
1331
1332 // Give a code modification hint to insert 'this->'.
1333 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1334 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001335 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001336 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1337 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001338 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001339 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001340 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001341 Diag(R.getNameLoc(), diagnostic) << Name
1342 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1343 QualType DepThisType = DepMethod->getThisType(Context);
1344 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1345 R.getNameLoc(), DepThisType, false);
1346 TemplateArgumentListInfo TList;
1347 if (ULE->hasExplicitTemplateArgs())
1348 ULE->copyTemplateArgumentsInto(TList);
1349 CXXDependentScopeMemberExpr *DepExpr =
1350 CXXDependentScopeMemberExpr::Create(
1351 Context, DepThis, DepThisType, true, SourceLocation(),
1352 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
1353 R.getLookupNameInfo(), &TList);
1354 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001355 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001356 // FIXME: we should be able to handle this case too. It is correct
1357 // to add this-> here. This is a workaround for PR7947.
1358 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001359 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001360 } else {
John McCall578b69b2009-12-16 08:11:27 +00001361 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001362 }
John McCall578b69b2009-12-16 08:11:27 +00001363
1364 // Do we really want to note all of these?
1365 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1366 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1367
1368 // Tell the callee to try to recover.
1369 return false;
1370 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001371
1372 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001373 }
1374 }
1375
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001376 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001377 DeclarationName Corrected;
Daniel Dunbardc32cdf2010-06-02 15:46:52 +00001378 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001379 if (!R.empty()) {
1380 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1381 if (SS.isEmpty())
1382 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1383 << FixItHint::CreateReplacement(R.getNameLoc(),
1384 R.getLookupName().getAsString());
1385 else
1386 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1387 << Name << computeDeclContext(SS, false) << R.getLookupName()
1388 << SS.getRange()
1389 << FixItHint::CreateReplacement(R.getNameLoc(),
1390 R.getLookupName().getAsString());
1391 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1392 Diag(ND->getLocation(), diag::note_previous_decl)
1393 << ND->getDeclName();
1394
1395 // Tell the callee to try to recover.
1396 return false;
1397 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001398
Douglas Gregoraaf87162010-04-14 20:04:41 +00001399 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1400 // FIXME: If we ended up with a typo for a type name or
1401 // Objective-C class name, we're in trouble because the parser
1402 // is in the wrong place to recover. Suggest the typo
1403 // correction, but don't make it a fix-it since we're not going
1404 // to recover well anyway.
1405 if (SS.isEmpty())
1406 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1407 else
1408 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1409 << Name << computeDeclContext(SS, false) << R.getLookupName()
1410 << SS.getRange();
1411
1412 // Don't try to recover; it won't work.
1413 return true;
1414 }
1415 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001416 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001417 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001418 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +00001419 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001420 else
Douglas Gregord203a162010-01-01 00:15:04 +00001421 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001422 << Name << computeDeclContext(SS, false) << Corrected
1423 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001424 return true;
1425 }
Douglas Gregord203a162010-01-01 00:15:04 +00001426 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001427 }
1428
1429 // Emit a special diagnostic for failed member lookups.
1430 // FIXME: computing the declaration context might fail here (?)
1431 if (!SS.isEmpty()) {
1432 Diag(R.getNameLoc(), diag::err_no_member)
1433 << Name << computeDeclContext(SS, false)
1434 << SS.getRange();
1435 return true;
1436 }
1437
John McCall578b69b2009-12-16 08:11:27 +00001438 // Give up, we can't recover.
1439 Diag(R.getNameLoc(), diagnostic) << Name;
1440 return true;
1441}
1442
Douglas Gregorca45da02010-11-02 20:36:02 +00001443ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1444 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001445 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1446 if (!IDecl)
1447 return 0;
1448 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1449 if (!ClassImpDecl)
1450 return 0;
Douglas Gregorca45da02010-11-02 20:36:02 +00001451 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001452 if (!property)
1453 return 0;
1454 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregorca45da02010-11-02 20:36:02 +00001455 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1456 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001457 return 0;
1458 return property;
1459}
1460
Douglas Gregorca45da02010-11-02 20:36:02 +00001461bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1462 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1463 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1464 if (!IDecl)
1465 return false;
1466 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1467 if (!ClassImpDecl)
1468 return false;
1469 if (ObjCPropertyImplDecl *PIDecl
1470 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1471 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1472 PIDecl->getPropertyIvarDecl())
1473 return false;
1474
1475 return true;
1476}
1477
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001478static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001479 LookupResult &Lookup,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001480 IdentifierInfo *II,
1481 SourceLocation NameLoc) {
1482 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001483 bool LookForIvars;
1484 if (Lookup.empty())
1485 LookForIvars = true;
1486 else if (CurMeth->isClassMethod())
1487 LookForIvars = false;
1488 else
1489 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahaniand0fbadd2011-01-26 00:57:01 +00001490 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1491 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001492 if (!LookForIvars)
1493 return 0;
1494
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001495 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1496 if (!IDecl)
1497 return 0;
1498 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001499 if (!ClassImpDecl)
1500 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001501 bool DynamicImplSeen = false;
1502 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1503 if (!property)
1504 return 0;
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001505 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001506 DynamicImplSeen =
1507 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001508 // property implementation has a designated ivar. No need to assume a new
1509 // one.
1510 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1511 return 0;
1512 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001513 if (!DynamicImplSeen) {
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001514 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1515 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001516 NameLoc,
1517 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian75049662010-12-15 23:29:04 +00001518 ObjCIvarDecl::Private,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001519 (Expr *)0, true);
1520 ClassImpDecl->addDecl(Ivar);
1521 IDecl->makeDeclVisibleInContext(Ivar, false);
1522 property->setPropertyIvarDecl(Ivar);
1523 return Ivar;
1524 }
1525 return 0;
1526}
1527
John McCall60d7b3a2010-08-24 06:29:42 +00001528ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001529 CXXScopeSpec &SS,
1530 UnqualifiedId &Id,
1531 bool HasTrailingLParen,
1532 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001533 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1534 "cannot be direct & operand and have a trailing lparen");
1535
1536 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001537 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001538
John McCall129e2df2009-11-30 22:42:35 +00001539 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001540
1541 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001542 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001543 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnara25777432010-08-11 22:01:17 +00001544 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001545
Abramo Bagnara25777432010-08-11 22:01:17 +00001546 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001547 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001548 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001549
John McCallf7a1a742009-11-24 19:00:30 +00001550 // C++ [temp.dep.expr]p3:
1551 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001552 // -- an identifier that was declared with a dependent type,
1553 // (note: handled after lookup)
1554 // -- a template-id that is dependent,
1555 // (note: handled in BuildTemplateIdExpr)
1556 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001557 // -- a nested-name-specifier that contains a class-name that
1558 // names a dependent type.
1559 // Determine whether this is a member of an unknown specialization;
1560 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001561 bool DependentID = false;
1562 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1563 Name.getCXXNameType()->isDependentType()) {
1564 DependentID = true;
1565 } else if (SS.isSet()) {
1566 DeclContext *DC = computeDeclContext(SS, false);
1567 if (DC) {
1568 if (RequireCompleteDeclContext(SS, DC))
1569 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001570 } else {
1571 DependentID = true;
1572 }
1573 }
1574
1575 if (DependentID) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001576 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001577 TemplateArgs);
1578 }
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001579 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001580 // Perform the required lookup.
Abramo Bagnara25777432010-08-11 22:01:17 +00001581 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001582 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001583 // Lookup the template name again to correctly establish the context in
1584 // which it was found. This is really unfortunate as we already did the
1585 // lookup to determine that it was a template name in the first place. If
1586 // this becomes a performance hit, we can work harder to preserve those
1587 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001588 bool MemberOfUnknownSpecialization;
1589 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1590 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001591
1592 if (MemberOfUnknownSpecialization ||
1593 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1594 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1595 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001596 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001597 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001598 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001600 // If the result might be in a dependent base class, this is a dependent
1601 // id-expression.
1602 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1603 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1604 TemplateArgs);
1605
John McCallf7a1a742009-11-24 19:00:30 +00001606 // If this reference is in an Objective-C method, then we need to do
1607 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001608 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001609 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001610 if (E.isInvalid())
1611 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001612
John McCallf7a1a742009-11-24 19:00:30 +00001613 Expr *Ex = E.takeAs<Expr>();
1614 if (Ex) return Owned(Ex);
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001615 // Synthesize ivars lazily
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001616 if (getLangOptions().ObjCDefaultSynthProperties &&
1617 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahaniande267602010-11-17 19:41:23 +00001618 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1619 if (const ObjCPropertyDecl *Property =
1620 canSynthesizeProvisionalIvar(II)) {
1621 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1622 Diag(Property->getLocation(), diag::note_property_declare);
1623 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001624 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1625 isAddressOfOperand);
Fariborz Jahaniande267602010-11-17 19:41:23 +00001626 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001627 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001628 // for further use, this must be set to false if in class method.
1629 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001630 }
Chris Lattner8a934232008-03-31 00:36:02 +00001631 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001632
John McCallf7a1a742009-11-24 19:00:30 +00001633 if (R.isAmbiguous())
1634 return ExprError();
1635
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001636 // Determine whether this name might be a candidate for
1637 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001638 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001639
John McCallf7a1a742009-11-24 19:00:30 +00001640 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001641 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001642 // in C90, extension in C99, forbidden in C++).
1643 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1644 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1645 if (D) R.addDecl(D);
1646 }
1647
1648 // If this name wasn't predeclared and if this is not a function
1649 // call, diagnose the problem.
1650 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001651 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001652 return ExprError();
1653
1654 assert(!R.empty() &&
1655 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001656
1657 // If we found an Objective-C instance variable, let
1658 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001659 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001660 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1661 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001662 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001663 assert(E.isInvalid() || E.get());
1664 return move(E);
1665 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 }
1667 }
Mike Stump1eb44332009-09-09 15:08:12 +00001668
John McCallf7a1a742009-11-24 19:00:30 +00001669 // This is guaranteed from this point on.
1670 assert(!R.empty() || ADL);
1671
1672 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001673 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001674 !(getLangOptions().ObjCDefaultSynthProperties &&
1675 getLangOptions().ObjCNonFragileABI2) &&
Fariborz Jahanianb1d58e32010-07-29 16:53:53 +00001676 Var->isFileVarDecl()) {
Douglas Gregorca45da02010-11-02 20:36:02 +00001677 ObjCPropertyDecl *Property = canSynthesizeProvisionalIvar(II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001678 if (Property) {
1679 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1680 Diag(Property->getLocation(), diag::note_property_declare);
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001681 Diag(Var->getLocation(), diag::note_global_declared_at);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001682 }
1683 }
Douglas Gregor751f9a42009-06-30 15:47:41 +00001684 }
Mike Stump1eb44332009-09-09 15:08:12 +00001685
John McCallaa81e162009-12-01 22:10:20 +00001686 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001687 // C++ [class.mfct.non-static]p3:
1688 // When an id-expression that is not part of a class member access
1689 // syntax and not used to form a pointer to member is used in the
1690 // body of a non-static member function of class X, if name lookup
1691 // resolves the name in the id-expression to a non-static non-type
1692 // member of some class C, the id-expression is transformed into a
1693 // class member access expression using (*this) as the
1694 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001695 //
1696 // But we don't actually need to do this for '&' operands if R
1697 // resolved to a function or overloaded function set, because the
1698 // expression is ill-formed if it actually works out to be a
1699 // non-static member function:
1700 //
1701 // C++ [expr.ref]p4:
1702 // Otherwise, if E1.E2 refers to a non-static member function. . .
1703 // [t]he expression can be used only as the left-hand operand of a
1704 // member function call.
1705 //
1706 // There are other safeguards against such uses, but it's important
1707 // to get this right here so that we don't end up making a
1708 // spuriously dependent expression if we're inside a dependent
1709 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001710 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001711 bool MightBeImplicitMember;
1712 if (!isAddressOfOperand)
1713 MightBeImplicitMember = true;
1714 else if (!SS.isEmpty())
1715 MightBeImplicitMember = false;
1716 else if (R.isOverloadedResult())
1717 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001718 else if (R.isUnresolvableResult())
1719 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001720 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001721 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1722 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001723
1724 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001725 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001726 }
1727
John McCallf7a1a742009-11-24 19:00:30 +00001728 if (TemplateArgs)
1729 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001730
John McCallf7a1a742009-11-24 19:00:30 +00001731 return BuildDeclarationNameExpr(SS, R, ADL);
1732}
1733
John McCall3b4294e2009-12-16 12:17:52 +00001734/// Builds an expression which might be an implicit member expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001735ExprResult
John McCall3b4294e2009-12-16 12:17:52 +00001736Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1737 LookupResult &R,
1738 const TemplateArgumentListInfo *TemplateArgs) {
1739 switch (ClassifyImplicitMemberAccess(*this, R)) {
1740 case IMA_Instance:
1741 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1742
John McCall3b4294e2009-12-16 12:17:52 +00001743 case IMA_Mixed:
1744 case IMA_Mixed_Unrelated:
1745 case IMA_Unresolved:
1746 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1747
1748 case IMA_Static:
1749 case IMA_Mixed_StaticContext:
1750 case IMA_Unresolved_StaticContext:
1751 if (TemplateArgs)
1752 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1753 return BuildDeclarationNameExpr(SS, R, false);
1754
1755 case IMA_Error_StaticContext:
1756 case IMA_Error_Unrelated:
John McCall5808ce42011-02-03 08:15:49 +00001757 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1758 R.getLookupNameInfo());
John McCall3b4294e2009-12-16 12:17:52 +00001759 return ExprError();
1760 }
1761
1762 llvm_unreachable("unexpected instance member access kind");
1763 return ExprError();
1764}
1765
John McCall129e2df2009-11-30 22:42:35 +00001766/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1767/// declaration name, generally during template instantiation.
1768/// There's a large number of things which don't need to be done along
1769/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001770ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001771Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001772 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001773 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001774 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001775 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001776
John McCall77bb1aa2010-05-01 00:40:08 +00001777 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001778 return ExprError();
1779
Abramo Bagnara25777432010-08-11 22:01:17 +00001780 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001781 LookupQualifiedName(R, DC);
1782
1783 if (R.isAmbiguous())
1784 return ExprError();
1785
1786 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001787 Diag(NameInfo.getLoc(), diag::err_no_member)
1788 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001789 return ExprError();
1790 }
1791
1792 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1793}
1794
1795/// LookupInObjCMethod - The parser has read a name in, and Sema has
1796/// detected that we're currently inside an ObjC method. Perform some
1797/// additional lookup.
1798///
1799/// Ideally, most of this would be done by lookup, but there's
1800/// actually quite a lot of extra work involved.
1801///
1802/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001803ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001804Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001805 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001806 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001807 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001808
John McCallf7a1a742009-11-24 19:00:30 +00001809 // There are two cases to handle here. 1) scoped lookup could have failed,
1810 // in which case we should look for an ivar. 2) scoped lookup could have
1811 // found a decl, but that decl is outside the current instance method (i.e.
1812 // a global variable). In these two cases, we do a lookup for an ivar with
1813 // this name, if the lookup sucedes, we replace it our current decl.
1814
1815 // If we're in a class method, we don't normally want to look for
1816 // ivars. But if we don't find anything else, and there's an
1817 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001818 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001819
1820 bool LookForIvars;
1821 if (Lookup.empty())
1822 LookForIvars = true;
1823 else if (IsClassMethod)
1824 LookForIvars = false;
1825 else
1826 LookForIvars = (Lookup.isSingleResult() &&
1827 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001828 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001829 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001830 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001831 ObjCInterfaceDecl *ClassDeclared;
1832 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1833 // Diagnose using an ivar in a class method.
1834 if (IsClassMethod)
1835 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1836 << IV->getDeclName());
1837
1838 // If we're referencing an invalid decl, just return this as a silent
1839 // error node. The error diagnostic was already emitted on the decl.
1840 if (IV->isInvalidDecl())
1841 return ExprError();
1842
1843 // Check if referencing a field with __attribute__((deprecated)).
1844 if (DiagnoseUseOfDecl(IV, Loc))
1845 return ExprError();
1846
1847 // Diagnose the use of an ivar outside of the declaring class.
1848 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1849 ClassDeclared != IFace)
1850 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1851
1852 // FIXME: This should use a new expr for a direct reference, don't
1853 // turn this into Self->ivar, just return a BareIVarExpr or something.
1854 IdentifierInfo &II = Context.Idents.get("self");
1855 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001856 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00001857 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001858 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001859 SelfName, false, false);
1860 if (SelfExpr.isInvalid())
1861 return ExprError();
1862
John McCall409fa9a2010-12-06 20:48:59 +00001863 Expr *SelfE = SelfExpr.take();
1864 DefaultLvalueConversion(SelfE);
1865
John McCallf7a1a742009-11-24 19:00:30 +00001866 MarkDeclarationReferenced(Loc, IV);
1867 return Owned(new (Context)
1868 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall409fa9a2010-12-06 20:48:59 +00001869 SelfE, true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001870 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001871 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001872 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001873 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001874 ObjCInterfaceDecl *ClassDeclared;
1875 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1876 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1877 IFace == ClassDeclared)
1878 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1879 }
1880 }
1881
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001882 if (Lookup.empty() && II && AllowBuiltinCreation) {
1883 // FIXME. Consolidate this with similar code in LookupName.
1884 if (unsigned BuiltinID = II->getBuiltinID()) {
1885 if (!(getLangOptions().CPlusPlus &&
1886 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1887 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1888 S, Lookup.isForRedeclaration(),
1889 Lookup.getNameLoc());
1890 if (D) Lookup.addDecl(D);
1891 }
1892 }
1893 }
John McCallf7a1a742009-11-24 19:00:30 +00001894 // Sentinel value saying that we didn't do anything special.
1895 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001896}
John McCallba135432009-11-21 08:51:07 +00001897
John McCall6bb80172010-03-30 21:47:33 +00001898/// \brief Cast a base object to a member's actual type.
1899///
1900/// Logically this happens in three phases:
1901///
1902/// * First we cast from the base type to the naming class.
1903/// The naming class is the class into which we were looking
1904/// when we found the member; it's the qualifier type if a
1905/// qualifier was provided, and otherwise it's the base type.
1906///
1907/// * Next we cast from the naming class to the declaring class.
1908/// If the member we found was brought into a class's scope by
1909/// a using declaration, this is that class; otherwise it's
1910/// the class declaring the member.
1911///
1912/// * Finally we cast from the declaring class to the "true"
1913/// declaring class of the member. This conversion does not
1914/// obey access control.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001915bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00001916Sema::PerformObjectMemberConversion(Expr *&From,
1917 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001918 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001919 NamedDecl *Member) {
1920 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1921 if (!RD)
1922 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001923
Douglas Gregor5fccd362010-03-03 23:55:11 +00001924 QualType DestRecordType;
1925 QualType DestType;
1926 QualType FromRecordType;
1927 QualType FromType = From->getType();
1928 bool PointerConversions = false;
1929 if (isa<FieldDecl>(Member)) {
1930 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001931
Douglas Gregor5fccd362010-03-03 23:55:11 +00001932 if (FromType->getAs<PointerType>()) {
1933 DestType = Context.getPointerType(DestRecordType);
1934 FromRecordType = FromType->getPointeeType();
1935 PointerConversions = true;
1936 } else {
1937 DestType = DestRecordType;
1938 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001939 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001940 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1941 if (Method->isStatic())
1942 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001943
Douglas Gregor5fccd362010-03-03 23:55:11 +00001944 DestType = Method->getThisType(Context);
1945 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001946
Douglas Gregor5fccd362010-03-03 23:55:11 +00001947 if (FromType->getAs<PointerType>()) {
1948 FromRecordType = FromType->getPointeeType();
1949 PointerConversions = true;
1950 } else {
1951 FromRecordType = FromType;
1952 DestType = DestRecordType;
1953 }
1954 } else {
1955 // No conversion necessary.
1956 return false;
1957 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001958
Douglas Gregor5fccd362010-03-03 23:55:11 +00001959 if (DestType->isDependentType() || FromType->isDependentType())
1960 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001961
Douglas Gregor5fccd362010-03-03 23:55:11 +00001962 // If the unqualified types are the same, no conversion is necessary.
1963 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1964 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001965
John McCall6bb80172010-03-30 21:47:33 +00001966 SourceRange FromRange = From->getSourceRange();
1967 SourceLocation FromLoc = FromRange.getBegin();
1968
John McCall5baba9d2010-08-25 10:28:54 +00001969 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00001970
Douglas Gregor5fccd362010-03-03 23:55:11 +00001971 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001972 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00001973 // class name.
1974 //
1975 // If the member was a qualified name and the qualified referred to a
1976 // specific base subobject type, we'll cast to that intermediate type
1977 // first and then to the object in which the member is declared. That allows
1978 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1979 //
1980 // class Base { public: int x; };
1981 // class Derived1 : public Base { };
1982 // class Derived2 : public Base { };
1983 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1984 //
1985 // void VeryDerived::f() {
1986 // x = 17; // error: ambiguous base subobjects
1987 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1988 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001989 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00001990 QualType QType = QualType(Qualifier->getAsType(), 0);
1991 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1992 assert(QType->isRecordType() && "lookup done with non-record type");
1993
1994 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1995
1996 // In C++98, the qualifier type doesn't actually have to be a base
1997 // type of the object type, in which case we just ignore it.
1998 // Otherwise build the appropriate casts.
1999 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002000 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002001 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002002 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00002003 return true;
2004
Douglas Gregor5fccd362010-03-03 23:55:11 +00002005 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002006 QType = Context.getPointerType(QType);
John McCall5baba9d2010-08-25 10:28:54 +00002007 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2008 VK, &BasePath);
John McCall6bb80172010-03-30 21:47:33 +00002009
2010 FromType = QType;
2011 FromRecordType = QRecordType;
2012
2013 // If the qualifier type was the same as the destination type,
2014 // we're done.
2015 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2016 return false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002017 }
2018 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002019
John McCall6bb80172010-03-30 21:47:33 +00002020 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002021
John McCall6bb80172010-03-30 21:47:33 +00002022 // If we actually found the member through a using declaration, cast
2023 // down to the using declaration's type.
2024 //
2025 // Pointer equality is fine here because only one declaration of a
2026 // class ever has member declarations.
2027 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2028 assert(isa<UsingShadowDecl>(FoundDecl));
2029 QualType URecordType = Context.getTypeDeclType(
2030 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2031
2032 // We only need to do this if the naming-class to declaring-class
2033 // conversion is non-trivial.
2034 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2035 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002036 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002037 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002038 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00002039 return true;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002040
John McCall6bb80172010-03-30 21:47:33 +00002041 QualType UType = URecordType;
2042 if (PointerConversions)
2043 UType = Context.getPointerType(UType);
John McCall2de56d12010-08-25 11:45:40 +00002044 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00002045 VK, &BasePath);
John McCall6bb80172010-03-30 21:47:33 +00002046 FromType = UType;
2047 FromRecordType = URecordType;
2048 }
2049
2050 // We don't do access control for the conversion from the
2051 // declaring class to the true declaring class.
2052 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002053 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002054
John McCallf871d0c2010-08-07 06:22:56 +00002055 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002056 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2057 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002058 IgnoreAccess))
Douglas Gregor5fccd362010-03-03 23:55:11 +00002059 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002060
John McCall2de56d12010-08-25 11:45:40 +00002061 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00002062 VK, &BasePath);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00002063 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002064}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002065
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002066/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00002067static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00002068 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00002069 DeclAccessPair FoundDecl,
Abramo Bagnara25777432010-08-11 22:01:17 +00002070 const DeclarationNameInfo &MemberNameInfo,
2071 QualType Ty,
John McCallf89e55a2010-11-18 06:31:45 +00002072 ExprValueKind VK, ExprObjectKind OK,
John McCallf7a1a742009-11-24 19:00:30 +00002073 const TemplateArgumentListInfo *TemplateArgs = 0) {
2074 NestedNameSpecifier *Qualifier = 0;
2075 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00002076 if (SS.isSet()) {
2077 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
2078 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002079 }
Mike Stump1eb44332009-09-09 15:08:12 +00002080
John McCallf7a1a742009-11-24 19:00:30 +00002081 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00002082 Member, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002083 TemplateArgs, Ty, VK, OK);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002084}
2085
John McCalldfa1edb2010-11-23 20:48:44 +00002086static ExprResult
2087BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2088 const CXXScopeSpec &SS, FieldDecl *Field,
2089 DeclAccessPair FoundDecl,
2090 const DeclarationNameInfo &MemberNameInfo) {
2091 // x.a is an l-value if 'a' has a reference type. Otherwise:
2092 // x.a is an l-value/x-value/pr-value if the base is (and note
2093 // that *x is always an l-value), except that if the base isn't
2094 // an ordinary object then we must have an rvalue.
2095 ExprValueKind VK = VK_LValue;
2096 ExprObjectKind OK = OK_Ordinary;
2097 if (!IsArrow) {
2098 if (BaseExpr->getObjectKind() == OK_Ordinary)
2099 VK = BaseExpr->getValueKind();
2100 else
2101 VK = VK_RValue;
2102 }
2103 if (VK != VK_RValue && Field->isBitField())
2104 OK = OK_BitField;
2105
2106 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2107 QualType MemberType = Field->getType();
2108 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2109 MemberType = Ref->getPointeeType();
2110 VK = VK_LValue;
2111 } else {
2112 QualType BaseType = BaseExpr->getType();
2113 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2114
2115 Qualifiers BaseQuals = BaseType.getQualifiers();
2116
2117 // GC attributes are never picked up by members.
2118 BaseQuals.removeObjCGCAttr();
2119
2120 // CVR attributes from the base are picked up by members,
2121 // except that 'mutable' members don't pick up 'const'.
2122 if (Field->isMutable()) BaseQuals.removeConst();
2123
2124 Qualifiers MemberQuals
2125 = S.Context.getCanonicalType(MemberType).getQualifiers();
2126
2127 // TR 18037 does not allow fields to be declared with address spaces.
2128 assert(!MemberQuals.hasAddressSpace());
2129
2130 Qualifiers Combined = BaseQuals + MemberQuals;
2131 if (Combined != MemberQuals)
2132 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2133 }
2134
2135 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2136 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2137 FoundDecl, Field))
2138 return ExprError();
2139 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2140 Field, FoundDecl, MemberNameInfo,
2141 MemberType, VK, OK));
2142}
2143
John McCallaa81e162009-12-01 22:10:20 +00002144/// Builds an implicit member access expression. The current context
2145/// is known to be an instance method, and the given unqualified lookup
2146/// set is known to contain only instance members, at least one of which
2147/// is from an appropriate type.
John McCall60d7b3a2010-08-24 06:29:42 +00002148ExprResult
John McCallaa81e162009-12-01 22:10:20 +00002149Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2150 LookupResult &R,
2151 const TemplateArgumentListInfo *TemplateArgs,
2152 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00002153 assert(!R.empty() && !R.isAmbiguous());
2154
John McCall5808ce42011-02-03 08:15:49 +00002155 SourceLocation loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00002156
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002157 // We may have found a field within an anonymous union or struct
2158 // (C++ [class.union]).
John McCallf7a1a742009-11-24 19:00:30 +00002159 // FIXME: template-ids inside anonymous structs?
Francois Pichet87c2e122010-11-21 06:08:52 +00002160 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCall5808ce42011-02-03 08:15:49 +00002161 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet87c2e122010-11-21 06:08:52 +00002162
John McCall5808ce42011-02-03 08:15:49 +00002163 // If this is known to be an instance access, go ahead and build an
2164 // implicit 'this' expression now.
John McCallaa81e162009-12-01 22:10:20 +00002165 // 'this' expression now.
John McCall5808ce42011-02-03 08:15:49 +00002166 CXXMethodDecl *method = tryCaptureCXXThis();
2167 assert(method && "didn't correctly pre-flight capture of 'this'");
2168
2169 QualType thisType = method->getThisType(Context);
2170 Expr *baseExpr = 0; // null signifies implicit access
John McCallaa81e162009-12-01 22:10:20 +00002171 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00002172 SourceLocation Loc = R.getNameLoc();
2173 if (SS.getRange().isValid())
2174 Loc = SS.getRange().getBegin();
John McCall5808ce42011-02-03 08:15:49 +00002175 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00002176 }
2177
John McCall5808ce42011-02-03 08:15:49 +00002178 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCallaa81e162009-12-01 22:10:20 +00002179 /*OpLoc*/ SourceLocation(),
2180 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00002181 SS,
2182 /*FirstQualifierInScope*/ 0,
2183 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00002184}
2185
John McCallf7a1a742009-11-24 19:00:30 +00002186bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002187 const LookupResult &R,
2188 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002189 // Only when used directly as the postfix-expression of a call.
2190 if (!HasTrailingLParen)
2191 return false;
2192
2193 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002194 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002195 return false;
2196
2197 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002198 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002199 return false;
2200
2201 // Turn off ADL when we find certain kinds of declarations during
2202 // normal lookup:
2203 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2204 NamedDecl *D = *I;
2205
2206 // C++0x [basic.lookup.argdep]p3:
2207 // -- a declaration of a class member
2208 // Since using decls preserve this property, we check this on the
2209 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002210 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002211 return false;
2212
2213 // C++0x [basic.lookup.argdep]p3:
2214 // -- a block-scope function declaration that is not a
2215 // using-declaration
2216 // NOTE: we also trigger this for function templates (in fact, we
2217 // don't check the decl type at all, since all other decl types
2218 // turn off ADL anyway).
2219 if (isa<UsingShadowDecl>(D))
2220 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2221 else if (D->getDeclContext()->isFunctionOrMethod())
2222 return false;
2223
2224 // C++0x [basic.lookup.argdep]p3:
2225 // -- a declaration that is neither a function or a function
2226 // template
2227 // And also for builtin functions.
2228 if (isa<FunctionDecl>(D)) {
2229 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2230
2231 // But also builtin functions.
2232 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2233 return false;
2234 } else if (!isa<FunctionTemplateDecl>(D))
2235 return false;
2236 }
2237
2238 return true;
2239}
2240
2241
John McCallba135432009-11-21 08:51:07 +00002242/// Diagnoses obvious problems with the use of the given declaration
2243/// as an expression. This is only actually called for lookups that
2244/// were not overloaded, and it doesn't promise that the declaration
2245/// will in fact be used.
2246static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2247 if (isa<TypedefDecl>(D)) {
2248 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2249 return true;
2250 }
2251
2252 if (isa<ObjCInterfaceDecl>(D)) {
2253 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2254 return true;
2255 }
2256
2257 if (isa<NamespaceDecl>(D)) {
2258 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2259 return true;
2260 }
2261
2262 return false;
2263}
2264
John McCall60d7b3a2010-08-24 06:29:42 +00002265ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002266Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002267 LookupResult &R,
2268 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002269 // If this is a single, fully-resolved result and we don't need ADL,
2270 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002271 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002272 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2273 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002274
2275 // We only need to check the declaration if there's exactly one
2276 // result, because in the overloaded case the results can only be
2277 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002278 if (R.isSingleResult() &&
2279 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002280 return ExprError();
2281
John McCallc373d482010-01-27 01:50:18 +00002282 // Otherwise, just build an unresolved lookup expression. Suppress
2283 // any lookup-related diagnostics; we'll hash these out later, when
2284 // we've picked a target.
2285 R.suppressDiagnostics();
2286
John McCallba135432009-11-21 08:51:07 +00002287 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002288 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00002289 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002290 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002291 NeedsADL, R.isOverloadedResult(),
2292 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002293
2294 return Owned(ULE);
2295}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002296
John McCallba135432009-11-21 08:51:07 +00002297/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002298ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002299Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002300 const DeclarationNameInfo &NameInfo,
2301 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002302 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002303 assert(!isa<FunctionTemplateDecl>(D) &&
2304 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002305
Abramo Bagnara25777432010-08-11 22:01:17 +00002306 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002307 if (CheckDeclInExpr(*this, Loc, D))
2308 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002309
Douglas Gregor9af2f522009-12-01 16:58:18 +00002310 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2311 // Specifically diagnose references to class templates that are missing
2312 // a template argument list.
2313 Diag(Loc, diag::err_template_decl_ref)
2314 << Template << SS.getRange();
2315 Diag(Template->getLocation(), diag::note_template_decl_here);
2316 return ExprError();
2317 }
2318
2319 // Make sure that we're referring to a value.
2320 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2321 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002322 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002323 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002324 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002325 return ExprError();
2326 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002327
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002328 // Check whether this declaration can be used. Note that we suppress
2329 // this check when we're going to perform argument-dependent lookup
2330 // on this function name, because this might not be the function
2331 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002332 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002333 return ExprError();
2334
Steve Naroffdd972f22008-09-05 22:11:13 +00002335 // Only create DeclRefExpr's for valid Decl's.
2336 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002337 return ExprError();
2338
John McCall5808ce42011-02-03 08:15:49 +00002339 // Handle members of anonymous structs and unions. If we got here,
2340 // and the reference is to a class member indirect field, then this
2341 // must be the subject of a pointer-to-member expression.
2342 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2343 if (!indirectField->isCXXClassMember())
2344 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2345 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002346
Chris Lattner639e2d32008-10-20 05:16:36 +00002347 // If the identifier reference is inside a block, and it refers to a value
2348 // that is outside the block, create a BlockDeclRefExpr instead of a
2349 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2350 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002351 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002352 // We do not do this for things like enum constants, global variables, etc,
2353 // as they do not get snapshotted.
2354 //
John McCall6b5a61b2011-02-07 10:33:21 +00002355 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002356 case CR_Error:
2357 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002358
John McCall469a1eb2011-02-02 13:00:07 +00002359 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002360 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2361 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2362
2363 case CR_CaptureByRef:
2364 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2365 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002366
2367 case CR_NoCapture: {
2368 // If this reference is not in a block or if the referenced
2369 // variable is within the block, create a normal DeclRefExpr.
2370
2371 QualType type = VD->getType();
2372 ExprValueKind valueKind;
2373
2374 switch (D->getKind()) {
2375 // Ignore all the non-ValueDecl kinds.
2376#define ABSTRACT_DECL(kind)
2377#define VALUE(type, base)
2378#define DECL(type, base) \
2379 case Decl::type:
2380#include "clang/AST/DeclNodes.inc"
2381 llvm_unreachable("invalid value decl kind");
2382 return ExprError();
2383
2384 // These shouldn't make it here.
2385 case Decl::ObjCAtDefsField:
2386 case Decl::ObjCIvar:
2387 llvm_unreachable("forming non-member reference to ivar?");
2388 return ExprError();
2389
2390 // Enum constants are always r-values and never references.
2391 // Unresolved using declarations are dependent.
2392 case Decl::EnumConstant:
2393 case Decl::UnresolvedUsingValue:
2394 valueKind = VK_RValue;
2395 break;
2396
2397 // Fields and indirect fields that got here must be for
2398 // pointer-to-member expressions; we just call them l-values for
2399 // internal consistency, because this subexpression doesn't really
2400 // exist in the high-level semantics.
2401 case Decl::Field:
2402 case Decl::IndirectField:
2403 assert(getLangOptions().CPlusPlus &&
2404 "building reference to field in C?");
2405
2406 // These can't have reference type in well-formed programs, but
2407 // for internal consistency we do this anyway.
2408 type = type.getNonReferenceType();
2409 valueKind = VK_LValue;
2410 break;
2411
2412 // Non-type template parameters are either l-values or r-values
2413 // depending on the type.
2414 case Decl::NonTypeTemplateParm: {
2415 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2416 type = reftype->getPointeeType();
2417 valueKind = VK_LValue; // even if the parameter is an r-value reference
2418 break;
2419 }
2420
2421 // For non-references, we need to strip qualifiers just in case
2422 // the template parameter was declared as 'const int' or whatever.
2423 valueKind = VK_RValue;
2424 type = type.getUnqualifiedType();
2425 break;
2426 }
2427
2428 case Decl::Var:
2429 // In C, "extern void blah;" is valid and is an r-value.
2430 if (!getLangOptions().CPlusPlus &&
2431 !type.hasQualifiers() &&
2432 type->isVoidType()) {
2433 valueKind = VK_RValue;
2434 break;
2435 }
2436 // fallthrough
2437
2438 case Decl::ImplicitParam:
2439 case Decl::ParmVar:
2440 // These are always l-values.
2441 valueKind = VK_LValue;
2442 type = type.getNonReferenceType();
2443 break;
2444
2445 case Decl::Function: {
2446 // Functions are l-values in C++.
2447 if (getLangOptions().CPlusPlus) {
2448 valueKind = VK_LValue;
2449 break;
2450 }
2451
2452 // C99 DR 316 says that, if a function type comes from a
2453 // function definition (without a prototype), that type is only
2454 // used for checking compatibility. Therefore, when referencing
2455 // the function, we pretend that we don't have the full function
2456 // type.
2457 if (!cast<FunctionDecl>(VD)->hasPrototype())
2458 if (const FunctionProtoType *proto = type->getAs<FunctionProtoType>())
2459 type = Context.getFunctionNoProtoType(proto->getResultType(),
2460 proto->getExtInfo());
2461
2462 // Functions are r-values in C.
2463 valueKind = VK_RValue;
2464 break;
2465 }
2466
2467 case Decl::CXXMethod:
2468 // C++ methods are l-values if static, r-values if non-static.
2469 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2470 valueKind = VK_LValue;
2471 break;
2472 }
2473 // fallthrough
2474
2475 case Decl::CXXConversion:
2476 case Decl::CXXDestructor:
2477 case Decl::CXXConstructor:
2478 valueKind = VK_RValue;
2479 break;
2480 }
2481
2482 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2483 }
2484
John McCall469a1eb2011-02-02 13:00:07 +00002485 }
John McCallf89e55a2010-11-18 06:31:45 +00002486
John McCall6b5a61b2011-02-07 10:33:21 +00002487 llvm_unreachable("unknown capture result");
2488 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002489}
2490
John McCall60d7b3a2010-08-24 06:29:42 +00002491ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlcd965b92009-01-18 18:53:16 +00002492 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002493 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002494
Reid Spencer5f016e22007-07-11 17:01:13 +00002495 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002496 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002497 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2498 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2499 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002500 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002501
Chris Lattnerfa28b302008-01-12 08:14:25 +00002502 // Pre-defined identifiers are of type char[x], where x is the length of the
2503 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002504
Anders Carlsson3a082d82009-09-08 18:24:21 +00002505 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002506 if (!currentDecl && getCurBlock())
2507 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002508 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002509 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002510 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002511 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002512
Anders Carlsson773f3972009-09-11 01:22:35 +00002513 QualType ResTy;
2514 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2515 ResTy = Context.DependentTy;
2516 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002517 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002518
Anders Carlsson773f3972009-09-11 01:22:35 +00002519 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002520 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002521 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2522 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002523 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002524}
2525
John McCall60d7b3a2010-08-24 06:29:42 +00002526ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002527 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002528 bool Invalid = false;
2529 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2530 if (Invalid)
2531 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002532
Benjamin Kramerddeea562010-02-27 13:44:12 +00002533 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2534 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002535 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002536 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002537
Chris Lattnere8337df2009-12-30 21:19:39 +00002538 QualType Ty;
2539 if (!getLangOptions().CPlusPlus)
2540 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2541 else if (Literal.isWide())
2542 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002543 else if (Literal.isMultiChar())
2544 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002545 else
2546 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002547
Sebastian Redle91b3bc2009-01-20 22:23:13 +00002548 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2549 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00002550 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002551}
2552
John McCall60d7b3a2010-08-24 06:29:42 +00002553ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002554 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002555 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2556 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002557 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00002558 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002559 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002560 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002561 }
Ted Kremenek28396602009-01-13 23:19:12 +00002562
Reid Spencer5f016e22007-07-11 17:01:13 +00002563 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002564 // Add padding so that NumericLiteralParser can overread by one character.
2565 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002566 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002567
Reid Spencer5f016e22007-07-11 17:01:13 +00002568 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002569 bool Invalid = false;
2570 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2571 if (Invalid)
2572 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002573
Mike Stump1eb44332009-09-09 15:08:12 +00002574 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002575 Tok.getLocation(), PP);
2576 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002577 return ExprError();
2578
Chris Lattner5d661452007-08-26 03:42:43 +00002579 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002580
Chris Lattner5d661452007-08-26 03:42:43 +00002581 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002582 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002583 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002584 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002585 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002586 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002587 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002588 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002589
2590 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2591
John McCall94c939d2009-12-24 09:08:04 +00002592 using llvm::APFloat;
2593 APFloat Val(Format);
2594
2595 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002596
2597 // Overflow is always an error, but underflow is only an error if
2598 // we underflowed to zero (APFloat reports denormals as underflow).
2599 if ((result & APFloat::opOverflow) ||
2600 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002601 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002602 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002603 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002604 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002605 APFloat::getLargest(Format).toString(buffer);
2606 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002607 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002608 APFloat::getSmallest(Format).toString(buffer);
2609 }
2610
2611 Diag(Tok.getLocation(), diagnostic)
2612 << Ty
2613 << llvm::StringRef(buffer.data(), buffer.size());
2614 }
2615
2616 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002617 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002618
Peter Collingbourne09821362010-12-04 01:50:56 +00002619 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2620 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2621
Chris Lattner5d661452007-08-26 03:42:43 +00002622 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002623 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002624 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002625 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002626
Neil Boothb9449512007-08-29 22:00:19 +00002627 // long long is a C99 feature.
2628 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002629 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002630 Diag(Tok.getLocation(), diag::ext_longlong);
2631
Reid Spencer5f016e22007-07-11 17:01:13 +00002632 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00002633 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002634
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 if (Literal.GetIntegerValue(ResultVal)) {
2636 // If this value didn't fit into uintmax_t, warn and force to ull.
2637 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002638 Ty = Context.UnsignedLongLongTy;
2639 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002640 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002641 } else {
2642 // If this value fits into a ULL, try to figure out what else it fits into
2643 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002644
Reid Spencer5f016e22007-07-11 17:01:13 +00002645 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2646 // be an unsigned int.
2647 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2648
2649 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002650 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002651 if (!Literal.isLong && !Literal.isLongLong) {
2652 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002653 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002654
Reid Spencer5f016e22007-07-11 17:01:13 +00002655 // Does it fit in a unsigned int?
2656 if (ResultVal.isIntN(IntSize)) {
2657 // Does it fit in a signed int?
2658 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002659 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002660 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002661 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002662 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002663 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002664 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002665
Reid Spencer5f016e22007-07-11 17:01:13 +00002666 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002667 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002668 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002669
Reid Spencer5f016e22007-07-11 17:01:13 +00002670 // Does it fit in a unsigned long?
2671 if (ResultVal.isIntN(LongSize)) {
2672 // Does it fit in a signed long?
2673 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002674 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002675 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002676 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002677 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002678 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002679 }
2680
Reid Spencer5f016e22007-07-11 17:01:13 +00002681 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002682 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002683 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002684
Reid Spencer5f016e22007-07-11 17:01:13 +00002685 // Does it fit in a unsigned long long?
2686 if (ResultVal.isIntN(LongLongSize)) {
2687 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002688 // To be compatible with MSVC, hex integer literals ending with the
2689 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002690 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2691 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002692 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002693 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002694 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002695 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002696 }
2697 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002698
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 // If we still couldn't decide a type, we probably have something that
2700 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002701 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002702 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002703 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002704 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002705 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002706
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002707 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002708 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002709 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002710 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002711 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002712
Chris Lattner5d661452007-08-26 03:42:43 +00002713 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2714 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002715 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002716 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002717
2718 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002719}
2720
John McCall60d7b3a2010-08-24 06:29:42 +00002721ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00002722 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002723 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002724 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002725}
2726
2727/// The UsualUnaryConversions() function is *not* called by this routine.
2728/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00002729bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00002730 SourceLocation OpLoc,
John McCall2a984ca2010-10-12 00:20:44 +00002731 SourceRange ExprRange,
Sebastian Redl05189992008-11-11 17:56:53 +00002732 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00002733 if (exprType->isDependentType())
2734 return false;
2735
Sebastian Redl5d484e82009-11-23 17:18:46 +00002736 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2737 // the result is the size of the referenced type."
2738 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2739 // result shall be the alignment of the referenced type."
2740 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2741 exprType = Ref->getPointeeType();
2742
Reid Spencer5f016e22007-07-11 17:01:13 +00002743 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00002744 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002745 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002746 if (isSizeof)
2747 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2748 return false;
2749 }
Mike Stump1eb44332009-09-09 15:08:12 +00002750
Chris Lattner1efaa952009-04-24 00:30:45 +00002751 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002752 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002753 Diag(OpLoc, diag::ext_sizeof_void_type)
2754 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00002755 return false;
2756 }
Mike Stump1eb44332009-09-09 15:08:12 +00002757
Chris Lattner1efaa952009-04-24 00:30:45 +00002758 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002759 PDiag(diag::err_sizeof_alignof_incomplete_type)
2760 << int(!isSizeof) << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002761 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002762
Chris Lattner1efaa952009-04-24 00:30:45 +00002763 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCallc12c5bb2010-05-15 11:32:37 +00002764 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002765 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00002766 << exprType << isSizeof << ExprRange;
2767 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00002768 }
Mike Stump1eb44332009-09-09 15:08:12 +00002769
Chris Lattner1efaa952009-04-24 00:30:45 +00002770 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002771}
2772
John McCall2a984ca2010-10-12 00:20:44 +00002773static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2774 SourceRange ExprRange) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002775 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002776
Mike Stump1eb44332009-09-09 15:08:12 +00002777 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002778 if (isa<DeclRefExpr>(E))
2779 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002780
2781 // Cannot know anything else if the expression is dependent.
2782 if (E->isTypeDependent())
2783 return false;
2784
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002785 if (E->getBitField()) {
John McCall2a984ca2010-10-12 00:20:44 +00002786 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002787 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002788 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002789
2790 // Alignment of a field access is always okay, so long as it isn't a
2791 // bit-field.
2792 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002793 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002794 return false;
2795
John McCall2a984ca2010-10-12 00:20:44 +00002796 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
Chris Lattner31e21e02009-01-24 20:17:12 +00002797}
2798
Douglas Gregorba498172009-03-13 21:01:28 +00002799/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002800ExprResult
John McCalla93c9342009-12-07 02:54:59 +00002801Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00002802 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002803 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002804 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002805 return ExprError();
2806
John McCalla93c9342009-12-07 02:54:59 +00002807 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002808
Douglas Gregorba498172009-03-13 21:01:28 +00002809 if (!T->isDependentType() &&
2810 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2811 return ExprError();
2812
2813 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00002814 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00002815 Context.getSizeType(), OpLoc,
2816 R.getEnd()));
2817}
2818
2819/// \brief Build a sizeof or alignof expression given an expression
2820/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002821ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00002822Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002823 bool isSizeOf, SourceRange R) {
2824 // Verify that the operand is valid.
2825 bool isInvalid = false;
2826 if (E->isTypeDependent()) {
2827 // Delay type-checking for type-dependent expressions.
2828 } else if (!isSizeOf) {
John McCall2a984ca2010-10-12 00:20:44 +00002829 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002830 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00002831 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2832 isInvalid = true;
John McCall2cd11fe2010-10-12 02:09:17 +00002833 } else if (E->getType()->isPlaceholderType()) {
2834 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2835 if (PE.isInvalid()) return ExprError();
2836 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
Douglas Gregorba498172009-03-13 21:01:28 +00002837 } else {
2838 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2839 }
2840
2841 if (isInvalid)
2842 return ExprError();
2843
2844 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2845 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2846 Context.getSizeType(), OpLoc,
2847 R.getEnd()));
2848}
2849
Sebastian Redl05189992008-11-11 17:56:53 +00002850/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2851/// the same for @c alignof and @c __alignof
2852/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00002853ExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00002854Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2855 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002856 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002857 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002858
Sebastian Redl05189992008-11-11 17:56:53 +00002859 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002860 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00002861 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
John McCalla93c9342009-12-07 02:54:59 +00002862 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002863 }
Sebastian Redl05189992008-11-11 17:56:53 +00002864
Douglas Gregorba498172009-03-13 21:01:28 +00002865 Expr *ArgEx = (Expr *)TyOrEx;
John McCall60d7b3a2010-08-24 06:29:42 +00002866 ExprResult Result
Douglas Gregorba498172009-03-13 21:01:28 +00002867 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2868
Douglas Gregorba498172009-03-13 21:01:28 +00002869 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002870}
2871
John McCall09431682010-11-18 19:01:18 +00002872static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2873 bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00002874 if (V->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00002875 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002876
John McCallf6a16482010-12-04 03:47:34 +00002877 // _Real and _Imag are only l-values for normal l-values.
2878 if (V->getObjectKind() != OK_Ordinary)
John McCall409fa9a2010-12-06 20:48:59 +00002879 S.DefaultLvalueConversion(V);
John McCallf6a16482010-12-04 03:47:34 +00002880
Chris Lattnercc26ed72007-08-26 05:39:26 +00002881 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00002882 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002883 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002884
Chris Lattnercc26ed72007-08-26 05:39:26 +00002885 // Otherwise they pass through real integer and floating point types here.
2886 if (V->getType()->isArithmeticType())
2887 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002888
John McCall2cd11fe2010-10-12 02:09:17 +00002889 // Test for placeholders.
John McCall09431682010-11-18 19:01:18 +00002890 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall2cd11fe2010-10-12 02:09:17 +00002891 if (PR.isInvalid()) return QualType();
2892 if (PR.take() != V) {
2893 V = PR.take();
John McCall09431682010-11-18 19:01:18 +00002894 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00002895 }
2896
Chris Lattnercc26ed72007-08-26 05:39:26 +00002897 // Reject anything else.
John McCall09431682010-11-18 19:01:18 +00002898 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002899 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002900 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002901}
2902
2903
Reid Spencer5f016e22007-07-11 17:01:13 +00002904
John McCall60d7b3a2010-08-24 06:29:42 +00002905ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00002906Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002907 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00002908 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00002909 switch (Kind) {
2910 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00002911 case tok::plusplus: Opc = UO_PostInc; break;
2912 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002913 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002914
John McCall9ae2f072010-08-23 23:25:46 +00002915 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002916}
2917
John McCall09431682010-11-18 19:01:18 +00002918/// Expressions of certain arbitrary types are forbidden by C from
2919/// having l-value type. These are:
2920/// - 'void', but not qualified void
2921/// - function types
2922///
2923/// The exact rule here is C99 6.3.2.1:
2924/// An lvalue is an expression with an object type or an incomplete
2925/// type other than void.
2926static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2927 return ((T->isVoidType() && !T.hasQualifiers()) ||
2928 T->isFunctionType());
2929}
2930
John McCall60d7b3a2010-08-24 06:29:42 +00002931ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002932Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2933 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00002934 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00002935 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00002936 if (Result.isInvalid()) return ExprError();
2937 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002938
John McCall9ae2f072010-08-23 23:25:46 +00002939 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00002940
Douglas Gregor337c6b92008-11-19 17:17:41 +00002941 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002942 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002943 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00002944 Context.DependentTy,
2945 VK_LValue, OK_Ordinary,
2946 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002947 }
2948
Mike Stump1eb44332009-09-09 15:08:12 +00002949 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002950 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00002951 LHSExp->getType()->isEnumeralType() ||
2952 RHSExp->getType()->isRecordType() ||
2953 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00002954 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00002955 }
2956
John McCall9ae2f072010-08-23 23:25:46 +00002957 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00002958}
2959
2960
John McCall60d7b3a2010-08-24 06:29:42 +00002961ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002962Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2963 Expr *Idx, SourceLocation RLoc) {
2964 Expr *LHSExp = Base;
2965 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00002966
Chris Lattner12d9ff62007-07-16 00:14:47 +00002967 // Perform default conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002968 if (!LHSExp->getType()->getAs<VectorType>())
2969 DefaultFunctionArrayLvalueConversion(LHSExp);
2970 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002971
Chris Lattner12d9ff62007-07-16 00:14:47 +00002972 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00002973 ExprValueKind VK = VK_LValue;
2974 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00002975
Reid Spencer5f016e22007-07-11 17:01:13 +00002976 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002977 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00002978 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00002979 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00002980 Expr *BaseExpr, *IndexExpr;
2981 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00002982 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2983 BaseExpr = LHSExp;
2984 IndexExpr = RHSExp;
2985 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002986 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00002987 BaseExpr = LHSExp;
2988 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002989 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002990 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00002991 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00002992 BaseExpr = RHSExp;
2993 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002994 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002995 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002996 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002997 BaseExpr = LHSExp;
2998 IndexExpr = RHSExp;
2999 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003000 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003001 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003002 // Handle the uncommon case of "123[Ptr]".
3003 BaseExpr = RHSExp;
3004 IndexExpr = LHSExp;
3005 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003006 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003007 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003008 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003009 VK = LHSExp->getValueKind();
3010 if (VK != VK_RValue)
3011 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003012
Chris Lattner12d9ff62007-07-16 00:14:47 +00003013 // FIXME: need to deal with const...
3014 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003015 } else if (LHSTy->isArrayType()) {
3016 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003017 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003018 // wasn't promoted because of the C90 rule that doesn't
3019 // allow promoting non-lvalue arrays. Warn, then
3020 // force the promotion here.
3021 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3022 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003023 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCall2de56d12010-08-25 11:45:40 +00003024 CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003025 LHSTy = LHSExp->getType();
3026
3027 BaseExpr = LHSExp;
3028 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003029 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003030 } else if (RHSTy->isArrayType()) {
3031 // Same as previous, except for 123[f().a] case
3032 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3033 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003034 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCall2de56d12010-08-25 11:45:40 +00003035 CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003036 RHSTy = RHSExp->getType();
3037
3038 BaseExpr = RHSExp;
3039 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003040 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003041 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003042 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3043 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003044 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003045 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003046 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003047 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3048 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003049
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003050 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003051 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3052 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003053 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3054
Douglas Gregore7450f52009-03-24 19:52:54 +00003055 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003056 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3057 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003058 // incomplete types are not object types.
3059 if (ResultType->isFunctionType()) {
3060 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3061 << ResultType << BaseExpr->getSourceRange();
3062 return ExprError();
3063 }
Mike Stump1eb44332009-09-09 15:08:12 +00003064
Abramo Bagnara46358452010-09-13 06:50:07 +00003065 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3066 // GNU extension: subscripting on pointer to void
3067 Diag(LLoc, diag::ext_gnu_void_ptr)
3068 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003069
3070 // C forbids expressions of unqualified void type from being l-values.
3071 // See IsCForbiddenLValueType.
3072 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003073 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003074 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003075 PDiag(diag::err_subscript_incomplete_type)
3076 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003077 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003078
Chris Lattner1efaa952009-04-24 00:30:45 +00003079 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003080 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003081 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3082 << ResultType << BaseExpr->getSourceRange();
3083 return ExprError();
3084 }
Mike Stump1eb44332009-09-09 15:08:12 +00003085
John McCall09431682010-11-18 19:01:18 +00003086 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3087 !IsCForbiddenLValueType(Context, ResultType));
3088
Mike Stumpeed9cac2009-02-19 03:04:26 +00003089 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003090 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003091}
3092
John McCall09431682010-11-18 19:01:18 +00003093/// Check an ext-vector component access expression.
3094///
3095/// VK should be set in advance to the value kind of the base
3096/// expression.
3097static QualType
3098CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3099 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003100 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00003101 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3102 // see FIXME there.
3103 //
3104 // FIXME: This logic can be greatly simplified by splitting it along
3105 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00003106 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00003107
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003108 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00003109 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003110
Mike Stumpeed9cac2009-02-19 03:04:26 +00003111 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00003112 // special names that indicate a subset of exactly half the elements are
3113 // to be selected.
3114 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003115
Nate Begeman353417a2009-01-18 01:47:54 +00003116 // This flag determines whether or not CompName has an 's' char prefix,
3117 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00003118 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00003119
John McCall09431682010-11-18 19:01:18 +00003120 bool HasRepeated = false;
3121 bool HasIndex[16] = {};
3122
3123 int Idx;
3124
Nate Begeman8a997642008-05-09 06:41:27 +00003125 // Check that we've found one of the special components, or that the component
3126 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003127 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00003128 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3129 HalvingSwizzle = true;
John McCall09431682010-11-18 19:01:18 +00003130 } else if (!HexSwizzle &&
3131 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3132 do {
3133 if (HasIndex[Idx]) HasRepeated = true;
3134 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003135 compStr++;
John McCall09431682010-11-18 19:01:18 +00003136 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3137 } else {
3138 if (HexSwizzle) compStr++;
3139 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3140 if (HasIndex[Idx]) HasRepeated = true;
3141 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003142 compStr++;
John McCall09431682010-11-18 19:01:18 +00003143 }
Chris Lattner88dca042007-08-02 22:33:49 +00003144 }
Nate Begeman353417a2009-01-18 01:47:54 +00003145
Mike Stumpeed9cac2009-02-19 03:04:26 +00003146 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003147 // We didn't get to the end of the string. This means the component names
3148 // didn't come from the same set *or* we encountered an illegal name.
John McCall09431682010-11-18 19:01:18 +00003149 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00003150 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003151 return QualType();
3152 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003153
Nate Begeman353417a2009-01-18 01:47:54 +00003154 // Ensure no component accessor exceeds the width of the vector type it
3155 // operates on.
3156 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00003157 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003158
3159 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003160 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00003161
3162 while (*compStr) {
3163 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall09431682010-11-18 19:01:18 +00003164 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begeman353417a2009-01-18 01:47:54 +00003165 << baseType << SourceRange(CompLoc);
3166 return QualType();
3167 }
3168 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003169 }
Nate Begeman8a997642008-05-09 06:41:27 +00003170
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003171 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003172 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003173 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00003174 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00003175 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00003176 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00003177 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00003178 if (HexSwizzle)
3179 CompSize--;
3180
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003181 if (CompSize == 1)
3182 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003183
John McCall09431682010-11-18 19:01:18 +00003184 if (HasRepeated) VK = VK_RValue;
3185
3186 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003187 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00003188 // diagostics look bad. We want extended vector types to appear built-in.
John McCall09431682010-11-18 19:01:18 +00003189 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3190 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3191 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00003192 }
3193 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003194}
3195
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003196static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003197 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003198 const Selector &Sel,
3199 ASTContext &Context) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003200 if (Member)
3201 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3202 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003203 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003204 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00003205
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003206 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3207 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003208 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3209 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003210 return D;
3211 }
3212 return 0;
3213}
3214
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003215static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3216 IdentifierInfo *Member,
3217 const Selector &Sel,
3218 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003219 // Check protocols on qualified interfaces.
3220 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003221 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003222 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003223 if (Member)
3224 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3225 GDecl = PD;
3226 break;
3227 }
3228 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003229 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003230 GDecl = OMD;
3231 break;
3232 }
3233 }
3234 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003235 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003236 E = QIdTy->qual_end(); I != E; ++I) {
3237 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003238 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3239 Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003240 if (GDecl)
3241 return GDecl;
3242 }
3243 }
3244 return GDecl;
3245}
Chris Lattner76a642f2009-02-15 22:43:40 +00003246
John McCall60d7b3a2010-08-24 06:29:42 +00003247ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003248Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCallaa81e162009-12-01 22:10:20 +00003249 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003250 const CXXScopeSpec &SS,
3251 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003252 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003253 const TemplateArgumentListInfo *TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00003254 // Even in dependent contexts, try to diagnose base expressions with
3255 // obviously wrong types, e.g.:
3256 //
3257 // T* t;
3258 // t.f;
3259 //
3260 // In Obj-C++, however, the above expression is valid, since it could be
3261 // accessing the 'f' property if T is an Obj-C interface. The extra check
3262 // allows this, while still reporting an error if T is a struct pointer.
3263 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00003264 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00003265 if (PT && (!getLangOptions().ObjC1 ||
3266 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00003267 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnara25777432010-08-11 22:01:17 +00003268 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00003269 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00003270 return ExprError();
3271 }
3272 }
3273
Abramo Bagnara25777432010-08-11 22:01:17 +00003274 assert(BaseType->isDependentType() ||
3275 NameInfo.getName().isDependentName() ||
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003276 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00003277
3278 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3279 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00003280 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003281 IsArrow, OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003282 SS.getScopeRep(),
John McCall129e2df2009-11-30 22:42:35 +00003283 SS.getRange(),
3284 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003285 NameInfo, TemplateArgs));
John McCall129e2df2009-11-30 22:42:35 +00003286}
3287
3288/// We know that the given qualified member reference points only to
3289/// declarations which do not belong to the static type of the base
3290/// expression. Diagnose the problem.
3291static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3292 Expr *BaseExpr,
3293 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003294 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00003295 NamedDecl *rep,
3296 const DeclarationNameInfo &nameInfo) {
John McCall2f841ba2009-12-02 03:53:29 +00003297 // If this is an implicit member access, use a different set of
3298 // diagnostics.
3299 if (!BaseExpr)
John McCall5808ce42011-02-03 08:15:49 +00003300 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003301
John McCall5808ce42011-02-03 08:15:49 +00003302 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3303 << SS.getRange() << rep << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00003304}
3305
3306// Check whether the declarations we found through a nested-name
3307// specifier in a member expression are actually members of the base
3308// type. The restriction here is:
3309//
3310// C++ [expr.ref]p2:
3311// ... In these cases, the id-expression shall name a
3312// member of the class or of one of its base classes.
3313//
3314// So it's perfectly legitimate for the nested-name specifier to name
3315// an unrelated class, and for us to find an overload set including
3316// decls from classes which are not superclasses, as long as the decl
3317// we actually pick through overload resolution is from a superclass.
3318bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3319 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003320 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003321 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00003322 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3323 if (!BaseRT) {
3324 // We can't check this yet because the base type is still
3325 // dependent.
3326 assert(BaseType->isDependentType());
3327 return false;
3328 }
3329 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00003330
3331 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00003332 // If this is an implicit member reference and we find a
3333 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00003334 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00003335 return false;
John McCall129e2df2009-11-30 22:42:35 +00003336
John McCallaa81e162009-12-01 22:10:20 +00003337 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman02463762010-07-27 20:51:02 +00003338 DeclContext *DC = (*I)->getDeclContext();
3339 while (DC->isTransparentContext())
3340 DC = DC->getParent();
John McCallaa81e162009-12-01 22:10:20 +00003341
Douglas Gregor9d4bb942010-07-28 22:27:52 +00003342 if (!DC->isRecord())
3343 continue;
3344
John McCallaa81e162009-12-01 22:10:20 +00003345 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman02463762010-07-27 20:51:02 +00003346 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCallaa81e162009-12-01 22:10:20 +00003347
3348 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3349 return false;
3350 }
3351
John McCall5808ce42011-02-03 08:15:49 +00003352 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3353 R.getRepresentativeDecl(),
3354 R.getLookupNameInfo());
John McCallaa81e162009-12-01 22:10:20 +00003355 return true;
3356}
3357
3358static bool
3359LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3360 SourceRange BaseRange, const RecordType *RTy,
John McCallad00b772010-06-16 08:42:20 +00003361 SourceLocation OpLoc, CXXScopeSpec &SS,
3362 bool HasTemplateArgs) {
John McCallaa81e162009-12-01 22:10:20 +00003363 RecordDecl *RDecl = RTy->getDecl();
3364 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003365 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00003366 << BaseRange))
3367 return true;
3368
John McCallad00b772010-06-16 08:42:20 +00003369 if (HasTemplateArgs) {
3370 // LookupTemplateName doesn't expect these both to exist simultaneously.
3371 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3372
3373 bool MOUS;
3374 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3375 return false;
3376 }
3377
John McCallaa81e162009-12-01 22:10:20 +00003378 DeclContext *DC = RDecl;
3379 if (SS.isSet()) {
3380 // If the member name was a qualified-id, look into the
3381 // nested-name-specifier.
3382 DC = SemaRef.computeDeclContext(SS, false);
3383
John McCall77bb1aa2010-05-01 00:40:08 +00003384 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCall2f841ba2009-12-02 03:53:29 +00003385 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3386 << SS.getRange() << DC;
3387 return true;
3388 }
3389
John McCallaa81e162009-12-01 22:10:20 +00003390 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003391
John McCallaa81e162009-12-01 22:10:20 +00003392 if (!isa<TypeDecl>(DC)) {
3393 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3394 << DC << SS.getRange();
3395 return true;
John McCall129e2df2009-11-30 22:42:35 +00003396 }
3397 }
3398
John McCallaa81e162009-12-01 22:10:20 +00003399 // The record definition is complete, now look up the member.
3400 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00003401
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003402 if (!R.empty())
3403 return false;
3404
3405 // We didn't find anything with the given name, so try to correct
3406 // for typos.
3407 DeclarationName Name = R.getLookupName();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003408 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00003409 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003410 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3411 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3412 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003413 << FixItHint::CreateReplacement(R.getNameLoc(),
3414 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003415 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3416 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3417 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003418 return false;
3419 } else {
3420 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003421 R.setLookupName(Name);
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003422 }
3423
John McCall129e2df2009-11-30 22:42:35 +00003424 return false;
3425}
3426
John McCall60d7b3a2010-08-24 06:29:42 +00003427ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003428Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003429 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003430 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003431 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003432 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003433 const TemplateArgumentListInfo *TemplateArgs) {
John McCall2f841ba2009-12-02 03:53:29 +00003434 if (BaseType->isDependentType() ||
3435 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall9ae2f072010-08-23 23:25:46 +00003436 return ActOnDependentMemberExpr(Base, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003437 IsArrow, OpLoc,
3438 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003439 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003440
Abramo Bagnara25777432010-08-11 22:01:17 +00003441 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00003442
John McCallaa81e162009-12-01 22:10:20 +00003443 // Implicit member accesses.
3444 if (!Base) {
3445 QualType RecordTy = BaseType;
3446 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3447 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3448 RecordTy->getAs<RecordType>(),
John McCallad00b772010-06-16 08:42:20 +00003449 OpLoc, SS, TemplateArgs != 0))
John McCallaa81e162009-12-01 22:10:20 +00003450 return ExprError();
3451
3452 // Explicit member accesses.
3453 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00003454 ExprResult Result =
John McCallaa81e162009-12-01 22:10:20 +00003455 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCalld226f652010-08-21 09:40:31 +00003456 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCallaa81e162009-12-01 22:10:20 +00003457
3458 if (Result.isInvalid()) {
3459 Owned(Base);
3460 return ExprError();
3461 }
3462
3463 if (Result.get())
3464 return move(Result);
Sebastian Redlf3e63372010-05-07 09:25:11 +00003465
3466 // LookupMemberExpr can modify Base, and thus change BaseType
3467 BaseType = Base->getType();
John McCall129e2df2009-11-30 22:42:35 +00003468 }
3469
John McCall9ae2f072010-08-23 23:25:46 +00003470 return BuildMemberReferenceExpr(Base, BaseType,
John McCallc2233c52010-01-15 08:34:02 +00003471 OpLoc, IsArrow, SS, FirstQualifierInScope,
3472 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003473}
3474
John McCall60d7b3a2010-08-24 06:29:42 +00003475ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003476Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCallaa81e162009-12-01 22:10:20 +00003477 SourceLocation OpLoc, bool IsArrow,
3478 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00003479 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00003480 LookupResult &R,
Douglas Gregor06a9f362010-05-01 20:49:11 +00003481 const TemplateArgumentListInfo *TemplateArgs,
3482 bool SuppressQualifierCheck) {
John McCallaa81e162009-12-01 22:10:20 +00003483 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00003484 if (IsArrow) {
3485 assert(BaseType->isPointerType());
3486 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3487 }
John McCall161755a2010-04-06 21:38:20 +00003488 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00003489
John McCall9ae2f072010-08-23 23:25:46 +00003490 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara25777432010-08-11 22:01:17 +00003491 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3492 DeclarationName MemberName = MemberNameInfo.getName();
3493 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall129e2df2009-11-30 22:42:35 +00003494
3495 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00003496 return ExprError();
3497
John McCall129e2df2009-11-30 22:42:35 +00003498 if (R.empty()) {
3499 // Rederive where we looked up.
3500 DeclContext *DC = (SS.isSet()
3501 ? computeDeclContext(SS, false)
3502 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00003503
John McCall129e2df2009-11-30 22:42:35 +00003504 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00003505 << MemberName << DC
3506 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00003507 return ExprError();
3508 }
3509
John McCallc2233c52010-01-15 08:34:02 +00003510 // Diagnose lookups that find only declarations from a non-base
3511 // type. This is possible for either qualified lookups (which may
3512 // have been qualified with an unrelated type) or implicit member
3513 // expressions (which were found with unqualified lookup and thus
3514 // may have come from an enclosing scope). Note that it's okay for
3515 // lookup to find declarations from a non-base type as long as those
3516 // aren't the ones picked by overload resolution.
3517 if ((SS.isSet() || !BaseExpr ||
3518 (isa<CXXThisExpr>(BaseExpr) &&
3519 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00003520 !SuppressQualifierCheck &&
John McCallc2233c52010-01-15 08:34:02 +00003521 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00003522 return ExprError();
3523
3524 // Construct an unresolved result if we in fact got an unresolved
3525 // result.
3526 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallc373d482010-01-27 01:50:18 +00003527 // Suppress any lookup-related diagnostics; we'll do these when we
3528 // pick a member.
3529 R.suppressDiagnostics();
3530
John McCall129e2df2009-11-30 22:42:35 +00003531 UnresolvedMemberExpr *MemExpr
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003532 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00003533 BaseExpr, BaseExprType,
3534 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003535 Qualifier, SS.getRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00003536 MemberNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00003537 TemplateArgs, R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00003538
3539 return Owned(MemExpr);
3540 }
3541
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003542 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00003543 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00003544 NamedDecl *MemberDecl = R.getFoundDecl();
3545
3546 // FIXME: diagnose the presence of template arguments now.
3547
3548 // If the decl being referenced had an error, return an error for this
3549 // sub-expr without emitting another error, in order to avoid cascading
3550 // error cases.
3551 if (MemberDecl->isInvalidDecl())
3552 return ExprError();
3553
John McCallaa81e162009-12-01 22:10:20 +00003554 // Handle the implicit-member-access case.
3555 if (!BaseExpr) {
3556 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00003557 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnara25777432010-08-11 22:01:17 +00003558 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCallaa81e162009-12-01 22:10:20 +00003559
Douglas Gregor828a1972010-01-07 23:12:05 +00003560 SourceLocation Loc = R.getNameLoc();
3561 if (SS.getRange().isValid())
3562 Loc = SS.getRange().getBegin();
3563 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003564 }
3565
John McCall129e2df2009-11-30 22:42:35 +00003566 bool ShouldCheckUse = true;
3567 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3568 // Don't diagnose the use of a virtual member function unless it's
3569 // explicitly qualified.
3570 if (MD->isVirtual() && !SS.isSet())
3571 ShouldCheckUse = false;
3572 }
3573
3574 // Check the use of this member.
3575 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3576 Owned(BaseExpr);
3577 return ExprError();
3578 }
3579
John McCallf6a16482010-12-04 03:47:34 +00003580 // Perform a property load on the base regardless of whether we
3581 // actually need it for the declaration.
3582 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3583 ConvertPropertyForRValue(BaseExpr);
3584
John McCalldfa1edb2010-11-23 20:48:44 +00003585 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3586 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3587 SS, FD, FoundDecl, MemberNameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003588
Francois Pichet87c2e122010-11-21 06:08:52 +00003589 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3590 // We may have found a field within an anonymous union or struct
3591 // (C++ [class.union]).
John McCall5808ce42011-02-03 08:15:49 +00003592 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCallf6a16482010-12-04 03:47:34 +00003593 BaseExpr, OpLoc);
Francois Pichet87c2e122010-11-21 06:08:52 +00003594
John McCall129e2df2009-11-30 22:42:35 +00003595 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3596 MarkDeclarationReferenced(MemberLoc, Var);
3597 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003598 Var, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003599 Var->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00003600 VK_LValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003601 }
3602
John McCallf89e55a2010-11-18 06:31:45 +00003603 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall129e2df2009-11-30 22:42:35 +00003604 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3605 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003606 MemberFn, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003607 MemberFn->getType(),
3608 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3609 OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003610 }
John McCallf89e55a2010-11-18 06:31:45 +00003611 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall129e2df2009-11-30 22:42:35 +00003612
3613 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3614 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3615 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003616 Enum, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003617 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003618 }
3619
3620 Owned(BaseExpr);
3621
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003622 // We found something that we didn't expect. Complain.
John McCall129e2df2009-11-30 22:42:35 +00003623 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnara25777432010-08-11 22:01:17 +00003624 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003625 << MemberName << BaseType << int(IsArrow);
3626 else
3627 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3628 << MemberName << BaseType << int(IsArrow);
John McCall129e2df2009-11-30 22:42:35 +00003629
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003630 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3631 << MemberName;
Douglas Gregor2b147f02010-04-25 21:15:30 +00003632 R.suppressDiagnostics();
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003633 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00003634}
3635
John McCall028d3972010-12-15 16:46:44 +00003636/// Given that normal member access failed on the given expression,
3637/// and given that the expression's type involves builtin-id or
3638/// builtin-Class, decide whether substituting in the redefinition
3639/// types would be profitable. The redefinition type is whatever
3640/// this translation unit tried to typedef to id/Class; we store
3641/// it to the side and then re-use it in places like this.
3642static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3643 const ObjCObjectPointerType *opty
3644 = base->getType()->getAs<ObjCObjectPointerType>();
3645 if (!opty) return false;
3646
3647 const ObjCObjectType *ty = opty->getObjectType();
3648
3649 QualType redef;
3650 if (ty->isObjCId()) {
3651 redef = S.Context.ObjCIdRedefinitionType;
3652 } else if (ty->isObjCClass()) {
3653 redef = S.Context.ObjCClassRedefinitionType;
3654 } else {
3655 return false;
3656 }
3657
3658 // Do the substitution as long as the redefinition type isn't just a
3659 // possibly-qualified pointer to builtin-id or builtin-Class again.
3660 opty = redef->getAs<ObjCObjectPointerType>();
3661 if (opty && !opty->getObjectType()->getInterface() != 0)
3662 return false;
3663
3664 S.ImpCastExprToType(base, redef, CK_BitCast);
3665 return true;
3666}
3667
John McCall129e2df2009-11-30 22:42:35 +00003668/// Look up the given member of the given non-type-dependent
3669/// expression. This can return in one of two ways:
3670/// * If it returns a sentinel null-but-valid result, the caller will
3671/// assume that lookup was performed and the results written into
3672/// the provided structure. It will take over from there.
3673/// * Otherwise, the returned expression will be produced in place of
3674/// an ordinary member expression.
3675///
3676/// The ObjCImpDecl bit is a gross hack that will need to be properly
3677/// fixed for ObjC++.
John McCall60d7b3a2010-08-24 06:29:42 +00003678ExprResult
John McCall129e2df2009-11-30 22:42:35 +00003679Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00003680 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003681 CXXScopeSpec &SS,
John McCalld226f652010-08-21 09:40:31 +00003682 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003683 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003684
Steve Naroff3cc4af82007-12-16 21:42:28 +00003685 // Perform default conversions.
3686 DefaultFunctionArrayConversion(BaseExpr);
John McCall5e3c67b2010-12-15 04:42:30 +00003687 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003688
Steve Naroffdfa6aae2007-07-26 03:11:44 +00003689 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00003690 assert(!BaseType->isDependentType());
3691
3692 DeclarationName MemberName = R.getLookupName();
3693 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003694
John McCall028d3972010-12-15 16:46:44 +00003695 // For later type-checking purposes, turn arrow accesses into dot
3696 // accesses. The only access type we support that doesn't follow
3697 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3698 // and those never use arrows, so this is unaffected.
3699 if (IsArrow) {
3700 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3701 BaseType = Ptr->getPointeeType();
3702 else if (const ObjCObjectPointerType *Ptr
3703 = BaseType->getAs<ObjCObjectPointerType>())
3704 BaseType = Ptr->getPointeeType();
3705 else if (BaseType->isRecordType()) {
3706 // Recover from arrow accesses to records, e.g.:
3707 // struct MyRecord foo;
3708 // foo->bar
3709 // This is actually well-formed in C++ if MyRecord has an
3710 // overloaded operator->, but that should have been dealt with
3711 // by now.
3712 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3713 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3714 << FixItHint::CreateReplacement(OpLoc, ".");
3715 IsArrow = false;
3716 } else {
3717 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3718 << BaseType << BaseExpr->getSourceRange();
3719 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003720 }
3721 }
3722
John McCall028d3972010-12-15 16:46:44 +00003723 // Handle field access to simple records.
3724 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3725 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3726 RTy, OpLoc, SS, HasTemplateArgs))
3727 return ExprError();
3728
3729 // Returning valid-but-null is how we indicate to the caller that
3730 // the lookup result was filled in.
3731 return Owned((Expr*) 0);
David Chisnall0f436562009-08-17 16:35:33 +00003732 }
John McCall129e2df2009-11-30 22:42:35 +00003733
John McCall028d3972010-12-15 16:46:44 +00003734 // Handle ivar access to Objective-C objects.
3735 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003736 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall028d3972010-12-15 16:46:44 +00003737
3738 // There are three cases for the base type:
3739 // - builtin id (qualified or unqualified)
3740 // - builtin Class (qualified or unqualified)
3741 // - an interface
3742 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3743 if (!IDecl) {
3744 // There's an implicit 'isa' ivar on all objects.
3745 // But we only actually find it this way on objects of type 'id',
3746 // apparently.
3747 if (OTy->isObjCId() && Member->isStr("isa"))
3748 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3749 Context.getObjCClassType()));
3750
3751 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3752 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3753 ObjCImpDecl, HasTemplateArgs);
3754 goto fail;
3755 }
3756
3757 ObjCInterfaceDecl *ClassDeclared;
3758 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3759
3760 if (!IV) {
3761 // Attempt to correct for typos in ivar names.
3762 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3763 LookupMemberName);
3764 if (CorrectTypo(Res, 0, 0, IDecl, false,
3765 IsArrow ? CTC_ObjCIvarLookup
3766 : CTC_ObjCPropertyLookup) &&
3767 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3768 Diag(R.getNameLoc(),
3769 diag::err_typecheck_member_reference_ivar_suggest)
3770 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3771 << FixItHint::CreateReplacement(R.getNameLoc(),
3772 IV->getNameAsString());
3773 Diag(IV->getLocation(), diag::note_previous_decl)
3774 << IV->getDeclName();
3775 } else {
3776 Res.clear();
3777 Res.setLookupName(Member);
3778
3779 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3780 << IDecl->getDeclName() << MemberName
3781 << BaseExpr->getSourceRange();
3782 return ExprError();
3783 }
3784 }
3785
3786 // If the decl being referenced had an error, return an error for this
3787 // sub-expr without emitting another error, in order to avoid cascading
3788 // error cases.
3789 if (IV->isInvalidDecl())
3790 return ExprError();
3791
3792 // Check whether we can reference this field.
3793 if (DiagnoseUseOfDecl(IV, MemberLoc))
3794 return ExprError();
3795 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3796 IV->getAccessControl() != ObjCIvarDecl::Package) {
3797 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3798 if (ObjCMethodDecl *MD = getCurMethodDecl())
3799 ClassOfMethodDecl = MD->getClassInterface();
3800 else if (ObjCImpDecl && getCurFunctionDecl()) {
3801 // Case of a c-function declared inside an objc implementation.
3802 // FIXME: For a c-style function nested inside an objc implementation
3803 // class, there is no implementation context available, so we pass
3804 // down the context as argument to this routine. Ideally, this context
3805 // need be passed down in the AST node and somehow calculated from the
3806 // AST for a function decl.
3807 if (ObjCImplementationDecl *IMPD =
3808 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3809 ClassOfMethodDecl = IMPD->getClassInterface();
3810 else if (ObjCCategoryImplDecl* CatImplClass =
3811 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3812 ClassOfMethodDecl = CatImplClass->getClassInterface();
3813 }
3814
3815 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3816 if (ClassDeclared != IDecl ||
3817 ClassOfMethodDecl != ClassDeclared)
3818 Diag(MemberLoc, diag::error_private_ivar_access)
3819 << IV->getDeclName();
3820 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3821 // @protected
3822 Diag(MemberLoc, diag::error_protected_ivar_access)
3823 << IV->getDeclName();
3824 }
3825
3826 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3827 MemberLoc, BaseExpr,
3828 IsArrow));
3829 }
3830
3831 // Objective-C property access.
3832 const ObjCObjectPointerType *OPT;
3833 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3834 // This actually uses the base as an r-value.
3835 DefaultLvalueConversion(BaseExpr);
3836 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3837
3838 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3839
3840 const ObjCObjectType *OT = OPT->getObjectType();
3841
3842 // id, with and without qualifiers.
3843 if (OT->isObjCId()) {
3844 // Check protocols on qualified interfaces.
3845 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3846 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3847 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3848 // Check the use of this declaration
3849 if (DiagnoseUseOfDecl(PD, MemberLoc))
3850 return ExprError();
3851
3852 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3853 VK_LValue,
3854 OK_ObjCProperty,
3855 MemberLoc,
3856 BaseExpr));
3857 }
3858
3859 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3860 // Check the use of this method.
3861 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3862 return ExprError();
3863 Selector SetterSel =
3864 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3865 PP.getSelectorTable(), Member);
3866 ObjCMethodDecl *SMD = 0;
3867 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3868 SetterSel, Context))
3869 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3870 QualType PType = OMD->getSendResultType();
3871
3872 ExprValueKind VK = VK_LValue;
3873 if (!getLangOptions().CPlusPlus &&
3874 IsCForbiddenLValueType(Context, PType))
3875 VK = VK_RValue;
3876 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3877
3878 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3879 VK, OK,
3880 MemberLoc, BaseExpr));
3881 }
3882 }
3883
3884 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3885 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3886 ObjCImpDecl, HasTemplateArgs);
3887
3888 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3889 << MemberName << BaseType);
3890 }
3891
3892 // 'Class', unqualified only.
3893 if (OT->isObjCClass()) {
3894 // Only works in a method declaration (??!).
3895 ObjCMethodDecl *MD = getCurMethodDecl();
3896 if (!MD) {
3897 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3898 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3899 ObjCImpDecl, HasTemplateArgs);
3900
3901 goto fail;
3902 }
3903
3904 // Also must look for a getter name which uses property syntax.
3905 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003906 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3907 ObjCMethodDecl *Getter;
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003908 if ((Getter = IFace->lookupClassMethod(Sel))) {
3909 // Check the use of this method.
3910 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3911 return ExprError();
John McCall028d3972010-12-15 16:46:44 +00003912 } else
Fariborz Jahanian74b27562010-12-03 23:37:08 +00003913 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003914 // If we found a getter then this may be a valid dot-reference, we
3915 // will look for the matching setter, in case it is needed.
3916 Selector SetterSel =
John McCall028d3972010-12-15 16:46:44 +00003917 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3918 PP.getSelectorTable(), Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003919 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3920 if (!Setter) {
3921 // If this reference is in an @implementation, also check for 'private'
3922 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00003923 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003924 }
3925 // Look through local category implementations associated with the class.
3926 if (!Setter)
3927 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003928
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003929 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3930 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003931
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003932 if (Getter || Setter) {
3933 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003934
John McCall09431682010-11-18 19:01:18 +00003935 ExprValueKind VK = VK_LValue;
3936 if (Getter) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003937 PType = Getter->getSendResultType();
John McCall09431682010-11-18 19:01:18 +00003938 if (!getLangOptions().CPlusPlus &&
3939 IsCForbiddenLValueType(Context, PType))
3940 VK = VK_RValue;
3941 } else {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003942 // Get the expression type from Setter's incoming parameter.
3943 PType = (*(Setter->param_end() -1))->getType();
John McCall09431682010-11-18 19:01:18 +00003944 }
3945 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3946
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003947 // FIXME: we must check that the setter has property type.
John McCall12f78a62010-12-02 01:19:52 +00003948 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3949 PType, VK, OK,
3950 MemberLoc, BaseExpr));
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003951 }
John McCall028d3972010-12-15 16:46:44 +00003952
3953 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3954 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3955 ObjCImpDecl, HasTemplateArgs);
3956
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003957 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall028d3972010-12-15 16:46:44 +00003958 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00003959 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003960
John McCall028d3972010-12-15 16:46:44 +00003961 // Normal property access.
3962 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3963 SourceLocation(), QualType(), false);
Steve Naroff14108da2009-07-10 23:34:53 +00003964 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003965
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003966 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00003967 if (BaseType->isExtVectorType()) {
John McCall5e3c67b2010-12-15 04:42:30 +00003968 // FIXME: this expr should store IsArrow.
Anders Carlsson8f28f992009-08-26 18:25:21 +00003969 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall5e3c67b2010-12-15 04:42:30 +00003970 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall09431682010-11-18 19:01:18 +00003971 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3972 Member, MemberLoc);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003973 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003974 return ExprError();
John McCall09431682010-11-18 19:01:18 +00003975
3976 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3977 *Member, MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003978 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003979
John McCall028d3972010-12-15 16:46:44 +00003980 // Adjust builtin-sel to the appropriate redefinition type if that's
3981 // not just a pointer to builtin-sel again.
3982 if (IsArrow &&
3983 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
3984 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
3985 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
3986 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3987 ObjCImpDecl, HasTemplateArgs);
3988 }
3989
3990 // Failure cases.
3991 fail:
3992
3993 // There's a possible road to recovery for function types.
3994 const FunctionType *Fun = 0;
3995
3996 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
3997 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
3998 // fall out, handled below.
3999
4000 // Recover from dot accesses to pointers, e.g.:
4001 // type *foo;
4002 // foo.bar
4003 // This is actually well-formed in two cases:
4004 // - 'type' is an Objective C type
4005 // - 'bar' is a pseudo-destructor name which happens to refer to
4006 // the appropriate pointer type
Argyrios Kyrtzidisdf8dc5d2011-01-25 23:16:36 +00004007 } else if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
John McCall028d3972010-12-15 16:46:44 +00004008 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
4009 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4010 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
4011 << FixItHint::CreateReplacement(OpLoc, "->");
4012
4013 // Recurse as an -> access.
4014 IsArrow = true;
4015 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4016 ObjCImpDecl, HasTemplateArgs);
4017 }
4018 } else {
4019 Fun = BaseType->getAs<FunctionType>();
4020 }
4021
4022 // If the user is trying to apply -> or . to a function pointer
4023 // type, it's probably because they forgot parentheses to call that
4024 // function. Suggest the addition of those parentheses, build the
4025 // call, and continue on.
4026 if (Fun || BaseType == Context.OverloadTy) {
4027 bool TryCall;
4028 if (BaseType == Context.OverloadTy) {
4029 TryCall = true;
4030 } else {
4031 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4032 TryCall = (FPT->getNumArgs() == 0);
4033 } else {
4034 TryCall = true;
4035 }
4036
4037 if (TryCall) {
4038 QualType ResultTy = Fun->getResultType();
4039 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4040 (IsArrow && ResultTy->isPointerType() &&
4041 ResultTy->getAs<PointerType>()->getPointeeType()->isRecordType());
4042 }
4043 }
4044
4045
4046 if (TryCall) {
4047 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
4048 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
4049 << QualType(Fun, 0)
4050 << FixItHint::CreateInsertion(Loc, "()");
4051
4052 ExprResult NewBase
4053 = ActOnCallExpr(0, BaseExpr, Loc, MultiExprArg(*this, 0, 0), Loc);
4054 if (NewBase.isInvalid())
4055 return ExprError();
4056 BaseExpr = NewBase.takeAs<Expr>();
4057
4058
4059 DefaultFunctionArrayConversion(BaseExpr);
4060 BaseType = BaseExpr->getType();
4061
4062 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4063 ObjCImpDecl, HasTemplateArgs);
4064 }
4065 }
4066
Douglas Gregor214f31a2009-03-27 06:00:30 +00004067 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
4068 << BaseType << BaseExpr->getSourceRange();
4069
Douglas Gregor214f31a2009-03-27 06:00:30 +00004070 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00004071}
4072
John McCall129e2df2009-11-30 22:42:35 +00004073/// The main callback when the parser finds something like
4074/// expression . [nested-name-specifier] identifier
4075/// expression -> [nested-name-specifier] identifier
4076/// where 'identifier' encompasses a fairly broad spectrum of
4077/// possibilities, including destructor and operator references.
4078///
4079/// \param OpKind either tok::arrow or tok::period
4080/// \param HasTrailingLParen whether the next token is '(', which
4081/// is used to diagnose mis-uses of special members that can
4082/// only be called
4083/// \param ObjCImpDecl the current ObjC @implementation decl;
4084/// this is an ugly hack around the fact that ObjC @implementations
4085/// aren't properly put in the context chain
John McCall60d7b3a2010-08-24 06:29:42 +00004086ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall5e3c67b2010-12-15 04:42:30 +00004087 SourceLocation OpLoc,
4088 tok::TokenKind OpKind,
4089 CXXScopeSpec &SS,
4090 UnqualifiedId &Id,
4091 Decl *ObjCImpDecl,
4092 bool HasTrailingLParen) {
John McCall129e2df2009-11-30 22:42:35 +00004093 if (SS.isSet() && SS.isInvalid())
4094 return ExprError();
4095
Francois Pichetdbee3412011-01-18 05:04:39 +00004096 // Warn about the explicit constructor calls Microsoft extension.
4097 if (getLangOptions().Microsoft &&
4098 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4099 Diag(Id.getSourceRange().getBegin(),
4100 diag::ext_ms_explicit_constructor_call);
4101
John McCall129e2df2009-11-30 22:42:35 +00004102 TemplateArgumentListInfo TemplateArgsBuffer;
4103
4104 // Decompose the name into its component parts.
Abramo Bagnara25777432010-08-11 22:01:17 +00004105 DeclarationNameInfo NameInfo;
John McCall129e2df2009-11-30 22:42:35 +00004106 const TemplateArgumentListInfo *TemplateArgs;
4107 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00004108 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004109
Abramo Bagnara25777432010-08-11 22:01:17 +00004110 DeclarationName Name = NameInfo.getName();
John McCall129e2df2009-11-30 22:42:35 +00004111 bool IsArrow = (OpKind == tok::arrow);
4112
4113 NamedDecl *FirstQualifierInScope
4114 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4115 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4116
4117 // This is a postfix expression, so get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004118 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004119 if (Result.isInvalid()) return ExprError();
4120 Base = Result.take();
John McCall129e2df2009-11-30 22:42:35 +00004121
Douglas Gregor01e56ae2010-04-12 20:54:26 +00004122 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4123 isDependentScopeSpecifier(SS)) {
John McCall9ae2f072010-08-23 23:25:46 +00004124 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00004125 IsArrow, OpLoc,
4126 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00004127 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004128 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00004129 LookupResult R(*this, NameInfo, LookupMemberName);
John McCallad00b772010-06-16 08:42:20 +00004130 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
4131 SS, ObjCImpDecl, TemplateArgs != 0);
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004132
John McCallad00b772010-06-16 08:42:20 +00004133 if (Result.isInvalid()) {
4134 Owned(Base);
4135 return ExprError();
4136 }
John McCall129e2df2009-11-30 22:42:35 +00004137
John McCallad00b772010-06-16 08:42:20 +00004138 if (Result.get()) {
4139 // The only way a reference to a destructor can be used is to
4140 // immediately call it, which falls into this case. If the
4141 // next token is not a '(', produce a diagnostic and build the
4142 // call now.
4143 if (!HasTrailingLParen &&
4144 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCall9ae2f072010-08-23 23:25:46 +00004145 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall129e2df2009-11-30 22:42:35 +00004146
John McCallad00b772010-06-16 08:42:20 +00004147 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00004148 }
4149
John McCall9ae2f072010-08-23 23:25:46 +00004150 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00004151 OpLoc, IsArrow, SS, FirstQualifierInScope,
4152 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004153 }
4154
4155 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00004156}
4157
John McCall60d7b3a2010-08-24 06:29:42 +00004158ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00004159 FunctionDecl *FD,
4160 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00004161 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004162 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00004163 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00004164 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004165 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00004166 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004167 return ExprError();
4168 }
4169
4170 if (Param->hasUninstantiatedDefaultArg()) {
4171 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00004172
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004173 // Instantiate the expression.
4174 MultiLevelTemplateArgumentList ArgList
4175 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00004176
Nico Weber08e41a62010-11-29 18:19:25 +00004177 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004178 = ArgList.getInnermost();
4179 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4180 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004181
Nico Weber08e41a62010-11-29 18:19:25 +00004182 ExprResult Result;
4183 {
4184 // C++ [dcl.fct.default]p5:
4185 // The names in the [default argument] expression are bound, and
4186 // the semantic constraints are checked, at the point where the
4187 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00004188 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00004189 Result = SubstExpr(UninstExpr, ArgList);
4190 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004191 if (Result.isInvalid())
4192 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004193
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004194 // Check the expression as an initializer for the parameter.
4195 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004196 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004197 InitializationKind Kind
4198 = InitializationKind::CreateCopy(Param->getLocation(),
4199 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4200 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00004201
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004202 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4203 Result = InitSeq.Perform(*this, Entity, Kind,
4204 MultiExprArg(*this, &ResultE, 1));
4205 if (Result.isInvalid())
4206 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004207
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004208 // Build the default argument expression.
4209 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4210 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004211 }
4212
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004213 // If the default expression creates temporaries, we need to
4214 // push them to the current stack of expression temporaries so they'll
4215 // be properly destroyed.
4216 // FIXME: We should really be rebuilding the default argument with new
4217 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00004218 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4219 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4220 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4221 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4222 ExprTemporaries.push_back(Temporary);
4223 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004224
4225 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00004226 // Just mark all of the declarations in this potentially-evaluated expression
4227 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004228 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00004229 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004230}
4231
Douglas Gregor88a35142008-12-22 05:46:06 +00004232/// ConvertArgumentsForCall - Converts the arguments specified in
4233/// Args/NumArgs to the parameter types of the function FDecl with
4234/// function prototype Proto. Call is the call expression itself, and
4235/// Fn is the function expression. For a C++ member function, this
4236/// routine does not attempt to convert the object argument. Returns
4237/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004238bool
4239Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00004240 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00004241 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00004242 Expr **Args, unsigned NumArgs,
4243 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004244 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00004245 // assignment, to the types of the corresponding parameter, ...
4246 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004247 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004248
Douglas Gregor88a35142008-12-22 05:46:06 +00004249 // If too few arguments are available (and we don't have default
4250 // arguments for the remaining parameters), don't make the call.
4251 if (NumArgs < NumArgsInProto) {
4252 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4253 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004254 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00004255 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004256 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00004257 }
4258
4259 // If too many are passed and not variadic, error on the extras and drop
4260 // them.
4261 if (NumArgs > NumArgsInProto) {
4262 if (!Proto->isVariadic()) {
4263 Diag(Args[NumArgsInProto]->getLocStart(),
4264 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004265 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00004266 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00004267 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4268 Args[NumArgs-1]->getLocEnd());
4269 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004270 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004271 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004272 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004273 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004274 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004275 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004276 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4277 if (Fn->getType()->isBlockPointerType())
4278 CallType = VariadicBlock; // Block
4279 else if (isa<MemberExpr>(Fn))
4280 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004281 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004282 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004283 if (Invalid)
4284 return true;
4285 unsigned TotalNumArgs = AllArgs.size();
4286 for (unsigned i = 0; i < TotalNumArgs; ++i)
4287 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004288
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004289 return false;
4290}
Mike Stumpeed9cac2009-02-19 03:04:26 +00004291
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004292bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4293 FunctionDecl *FDecl,
4294 const FunctionProtoType *Proto,
4295 unsigned FirstProtoArg,
4296 Expr **Args, unsigned NumArgs,
4297 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004298 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004299 unsigned NumArgsInProto = Proto->getNumArgs();
4300 unsigned NumArgsToCheck = NumArgs;
4301 bool Invalid = false;
4302 if (NumArgs != NumArgsInProto)
4303 // Use default arguments for missing arguments
4304 NumArgsToCheck = NumArgsInProto;
4305 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00004306 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004307 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004308 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004309
Douglas Gregor88a35142008-12-22 05:46:06 +00004310 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004311 if (ArgIx < NumArgs) {
4312 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004313
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004314 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4315 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004316 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004317 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004318 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004319
Douglas Gregora188ff22009-12-22 16:09:06 +00004320 // Pass the argument
4321 ParmVarDecl *Param = 0;
4322 if (FDecl && i < FDecl->getNumParams())
4323 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00004324
Douglas Gregora188ff22009-12-22 16:09:06 +00004325 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004326 Param? InitializedEntity::InitializeParameter(Context, Param)
4327 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCall60d7b3a2010-08-24 06:29:42 +00004328 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00004329 SourceLocation(),
4330 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00004331 if (ArgE.isInvalid())
4332 return true;
4333
4334 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004335 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00004336 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004337
John McCall60d7b3a2010-08-24 06:29:42 +00004338 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004339 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004340 if (ArgExpr.isInvalid())
4341 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004342
Anders Carlsson56c5e332009-08-25 03:49:14 +00004343 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004344 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004345 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004346 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004347
Douglas Gregor88a35142008-12-22 05:46:06 +00004348 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004349 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004350 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner40378332010-05-16 04:01:30 +00004351 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004352 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00004353 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004354 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004355 }
4356 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004357 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00004358}
4359
Steve Narofff69936d2007-09-16 03:34:24 +00004360/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00004361/// This provides the location of the left/right parens and a list of comma
4362/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00004363ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004364Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00004365 MultiExprArg args, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00004366 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00004367
4368 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004369 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00004370 if (Result.isInvalid()) return ExprError();
4371 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00004372
John McCall9ae2f072010-08-23 23:25:46 +00004373 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004374
Douglas Gregor88a35142008-12-22 05:46:06 +00004375 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00004376 // If this is a pseudo-destructor expression, build the call immediately.
4377 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4378 if (NumArgs > 0) {
4379 // Pseudo-destructor calls should not have any arguments.
4380 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00004381 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00004382 SourceRange(Args[0]->getLocStart(),
4383 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00004384
Douglas Gregora71d8192009-09-04 17:36:40 +00004385 NumArgs = 0;
4386 }
Mike Stump1eb44332009-09-09 15:08:12 +00004387
Douglas Gregora71d8192009-09-04 17:36:40 +00004388 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00004389 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00004390 }
Mike Stump1eb44332009-09-09 15:08:12 +00004391
Douglas Gregor17330012009-02-04 15:01:18 +00004392 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004393 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00004394 // FIXME: Will need to cache the results of name lookup (including ADL) in
4395 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00004396 bool Dependent = false;
4397 if (Fn->isTypeDependent())
4398 Dependent = true;
4399 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4400 Dependent = true;
4401
4402 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00004403 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +00004404 Context.DependentTy, VK_RValue,
4405 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00004406
4407 // Determine whether this is a call to an object (C++ [over.call.object]).
4408 if (Fn->getType()->isRecordType())
4409 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004410 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00004411
John McCall129e2df2009-11-30 22:42:35 +00004412 Expr *NakedFn = Fn->IgnoreParens();
4413
4414 // Determine whether this is a call to an unresolved member function.
4415 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4416 // If lookup was unresolved but not dependent (i.e. didn't find
4417 // an unresolved using declaration), it has to be an overloaded
4418 // function set, which means it must contain either multiple
4419 // declarations (all methods or method templates) or a single
4420 // method template.
4421 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor2b147f02010-04-25 21:15:30 +00004422 isa<FunctionTemplateDecl>(
4423 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00004424 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00004425
John McCallaa81e162009-12-01 22:10:20 +00004426 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004427 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00004428 }
4429
Douglas Gregorfa047642009-02-04 00:32:51 +00004430 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00004431 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00004432 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00004433 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00004434 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004435 RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00004436 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004437
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004438 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00004439 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCall2de56d12010-08-25 11:45:40 +00004440 if (BO->getOpcode() == BO_PtrMemD ||
4441 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00004442 if (const FunctionProtoType *FPT
4443 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004444 QualType ResultTy = FPT->getCallResultType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00004445 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004446
Douglas Gregorfdc13a02011-02-04 12:57:49 +00004447 // Check that the object type isn't more qualified than the
4448 // member function we're calling.
4449 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4450 Qualifiers ObjectQuals
4451 = BO->getOpcode() == BO_PtrMemD
4452 ? BO->getLHS()->getType().getQualifiers()
4453 : BO->getLHS()->getType()->getAs<PointerType>()
4454 ->getPointeeType().getQualifiers();
4455
4456 Qualifiers Difference = ObjectQuals - FuncQuals;
4457 Difference.removeObjCGCAttr();
4458 Difference.removeAddressSpace();
4459 if (Difference) {
4460 std::string QualsString = Difference.getAsString();
4461 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4462 << BO->getType().getUnqualifiedType()
4463 << QualsString
4464 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4465 }
4466
John McCall9ae2f072010-08-23 23:25:46 +00004467 CXXMemberCallExpr *TheCall
Abramo Bagnara6c572f12010-12-03 21:39:42 +00004468 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCallf89e55a2010-11-18 06:31:45 +00004469 NumArgs, ResultTy, VK,
John McCall9ae2f072010-08-23 23:25:46 +00004470 RParenLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004471
4472 if (CheckCallReturnType(FPT->getResultType(),
4473 BO->getRHS()->getSourceRange().getBegin(),
John McCall9ae2f072010-08-23 23:25:46 +00004474 TheCall, 0))
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004475 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00004476
John McCall9ae2f072010-08-23 23:25:46 +00004477 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004478 RParenLoc))
4479 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004480
John McCall9ae2f072010-08-23 23:25:46 +00004481 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004482 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004483 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004484 diag::err_typecheck_call_not_function)
4485 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004486 }
4487 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004488 }
4489
Douglas Gregorfa047642009-02-04 00:32:51 +00004490 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004491 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004492 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004493
Eli Friedmanefa42f72009-12-26 03:35:45 +00004494 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00004495 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4496 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4497 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4498 RParenLoc);
4499 }
4500
John McCall3b4294e2009-12-16 12:17:52 +00004501 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00004502 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4503 if (UnOp->getOpcode() == UO_AddrOf)
4504 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4505
John McCall3b4294e2009-12-16 12:17:52 +00004506 if (isa<DeclRefExpr>(NakedFn))
4507 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4508
John McCallaa81e162009-12-01 22:10:20 +00004509 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
4510}
4511
John McCall3b4294e2009-12-16 12:17:52 +00004512/// BuildResolvedCallExpr - Build a call to a resolved expression,
4513/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00004514/// unary-convert to an expression of function-pointer or
4515/// block-pointer type.
4516///
4517/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00004518ExprResult
John McCallaa81e162009-12-01 22:10:20 +00004519Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4520 SourceLocation LParenLoc,
4521 Expr **Args, unsigned NumArgs,
4522 SourceLocation RParenLoc) {
4523 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4524
Chris Lattner04421082008-04-08 04:40:51 +00004525 // Promote the function operand.
4526 UsualUnaryConversions(Fn);
4527
Chris Lattner925e60d2007-12-28 05:29:59 +00004528 // Make the call expr early, before semantic checks. This guarantees cleanup
4529 // of arguments and function on error.
John McCall9ae2f072010-08-23 23:25:46 +00004530 CallExpr *TheCall = new (Context) CallExpr(Context, Fn,
4531 Args, NumArgs,
4532 Context.BoolTy,
John McCallf89e55a2010-11-18 06:31:45 +00004533 VK_RValue,
John McCall9ae2f072010-08-23 23:25:46 +00004534 RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00004535
Steve Naroffdd972f22008-09-05 22:11:13 +00004536 const FunctionType *FuncT;
4537 if (!Fn->getType()->isBlockPointerType()) {
4538 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4539 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00004540 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00004541 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00004542 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4543 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00004544 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00004545 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00004546 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00004547 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00004548 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004549 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00004550 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4551 << Fn->getType() << Fn->getSourceRange());
4552
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004553 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004554 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00004555 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004556 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004557 return ExprError();
4558
Chris Lattner925e60d2007-12-28 05:29:59 +00004559 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004560 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004561 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004562
Douglas Gregor72564e72009-02-26 23:50:07 +00004563 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00004564 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00004565 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004566 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004567 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004568 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004569
Douglas Gregor74734d52009-04-02 15:37:10 +00004570 if (FDecl) {
4571 // Check if we have too few/too many template arguments, based
4572 // on our knowledge of the function definition.
4573 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004574 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004575 const FunctionProtoType *Proto
4576 = Def->getType()->getAs<FunctionProtoType>();
4577 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004578 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4579 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004580 }
Douglas Gregor46542412010-10-25 20:39:23 +00004581
4582 // If the function we're calling isn't a function prototype, but we have
4583 // a function prototype from a prior declaratiom, use that prototype.
4584 if (!FDecl->hasPrototype())
4585 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004586 }
4587
Steve Naroffb291ab62007-08-28 23:30:39 +00004588 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004589 for (unsigned i = 0; i != NumArgs; i++) {
4590 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004591
4592 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004593 InitializedEntity Entity
4594 = InitializedEntity::InitializeParameter(Context,
4595 Proto->getArgType(i));
4596 ExprResult ArgE = PerformCopyInitialization(Entity,
4597 SourceLocation(),
4598 Owned(Arg));
4599 if (ArgE.isInvalid())
4600 return true;
4601
4602 Arg = ArgE.takeAs<Expr>();
4603
4604 } else {
4605 DefaultArgumentPromotion(Arg);
Douglas Gregor46542412010-10-25 20:39:23 +00004606 }
4607
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004608 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4609 Arg->getType(),
4610 PDiag(diag::err_call_incomplete_argument)
4611 << Arg->getSourceRange()))
4612 return ExprError();
4613
Chris Lattner925e60d2007-12-28 05:29:59 +00004614 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004615 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004616 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004617
Douglas Gregor88a35142008-12-22 05:46:06 +00004618 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4619 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004620 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4621 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004622
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004623 // Check for sentinels
4624 if (NDecl)
4625 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004626
Chris Lattner59907c42007-08-10 20:18:51 +00004627 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004628 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00004629 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00004630 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004631
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004632 if (unsigned BuiltinID = FDecl->getBuiltinID())
4633 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004634 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00004635 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00004636 return ExprError();
4637 }
Chris Lattner59907c42007-08-10 20:18:51 +00004638
John McCall9ae2f072010-08-23 23:25:46 +00004639 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004640}
4641
John McCall60d7b3a2010-08-24 06:29:42 +00004642ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004643Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004644 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004645 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004646 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004647 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004648
4649 TypeSourceInfo *TInfo;
4650 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4651 if (!TInfo)
4652 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4653
John McCall9ae2f072010-08-23 23:25:46 +00004654 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004655}
4656
John McCall60d7b3a2010-08-24 06:29:42 +00004657ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004658Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00004659 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004660 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004661
Eli Friedman6223c222008-05-20 05:22:08 +00004662 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004663 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4664 PDiag(diag::err_illegal_decl_array_incomplete_type)
4665 << SourceRange(LParenLoc,
4666 literalExpr->getSourceRange().getEnd())))
4667 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004668 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004669 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4670 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004671 } else if (!literalType->isDependentType() &&
4672 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004673 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00004674 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00004675 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004676 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004677
Douglas Gregor99a2e602009-12-16 01:38:02 +00004678 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004679 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004680 InitializationKind Kind
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004681 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004682 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00004683 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00004684 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00004685 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00004686 &literalType);
4687 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004688 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004689 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004690
Chris Lattner371f2582008-12-04 23:50:19 +00004691 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004692 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00004693 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004694 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004695 }
Eli Friedman08544622009-12-22 02:35:53 +00004696
John McCallf89e55a2010-11-18 06:31:45 +00004697 // In C, compound literals are l-values for some reason.
4698 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4699
John McCall1d7d8d62010-01-19 22:33:45 +00004700 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCallf89e55a2010-11-18 06:31:45 +00004701 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004702}
4703
John McCall60d7b3a2010-08-24 06:29:42 +00004704ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004705Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004706 SourceLocation RBraceLoc) {
4707 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00004708 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00004709
Steve Naroff08d92e42007-09-15 18:49:24 +00004710 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004711 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004712
Ted Kremenek709210f2010-04-13 23:39:13 +00004713 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4714 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004715 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004716 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004717}
4718
John McCallf3ea8cf2010-11-14 08:17:51 +00004719/// Prepares for a scalar cast, performing all the necessary stages
4720/// except the final cast and returning the kind required.
4721static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4722 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4723 // Also, callers should have filtered out the invalid cases with
4724 // pointers. Everything else should be possible.
4725
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004726 QualType SrcTy = Src->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00004727 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004728 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004729
John McCalldaa8e4e2010-11-15 09:13:47 +00004730 switch (SrcTy->getScalarTypeKind()) {
4731 case Type::STK_MemberPointer:
4732 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004733
John McCalldaa8e4e2010-11-15 09:13:47 +00004734 case Type::STK_Pointer:
4735 switch (DestTy->getScalarTypeKind()) {
4736 case Type::STK_Pointer:
4737 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00004738 CK_AnyPointerToObjCPointerCast :
4739 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004740 case Type::STK_Bool:
4741 return CK_PointerToBoolean;
4742 case Type::STK_Integral:
4743 return CK_PointerToIntegral;
4744 case Type::STK_Floating:
4745 case Type::STK_FloatingComplex:
4746 case Type::STK_IntegralComplex:
4747 case Type::STK_MemberPointer:
4748 llvm_unreachable("illegal cast from pointer");
4749 }
4750 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004751
John McCalldaa8e4e2010-11-15 09:13:47 +00004752 case Type::STK_Bool: // casting from bool is like casting from an integer
4753 case Type::STK_Integral:
4754 switch (DestTy->getScalarTypeKind()) {
4755 case Type::STK_Pointer:
John McCallf3ea8cf2010-11-14 08:17:51 +00004756 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004757 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004758 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004759 case Type::STK_Bool:
4760 return CK_IntegralToBoolean;
4761 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004762 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004763 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004764 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004765 case Type::STK_IntegralComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004766 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCall8786da72010-12-14 17:51:41 +00004767 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004768 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004769 case Type::STK_FloatingComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004770 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004771 CK_IntegralToFloating);
4772 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004773 case Type::STK_MemberPointer:
4774 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004775 }
4776 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004777
John McCalldaa8e4e2010-11-15 09:13:47 +00004778 case Type::STK_Floating:
4779 switch (DestTy->getScalarTypeKind()) {
4780 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004781 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004782 case Type::STK_Bool:
4783 return CK_FloatingToBoolean;
4784 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004785 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004786 case Type::STK_FloatingComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004787 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCall8786da72010-12-14 17:51:41 +00004788 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004789 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004790 case Type::STK_IntegralComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004791 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004792 CK_FloatingToIntegral);
4793 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004794 case Type::STK_Pointer:
4795 llvm_unreachable("valid float->pointer cast?");
4796 case Type::STK_MemberPointer:
4797 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004798 }
4799 break;
4800
John McCalldaa8e4e2010-11-15 09:13:47 +00004801 case Type::STK_FloatingComplex:
4802 switch (DestTy->getScalarTypeKind()) {
4803 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004804 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004805 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004806 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004807 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004808 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00004809 if (S.Context.hasSameType(ET, DestTy))
4810 return CK_FloatingComplexToReal;
4811 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4812 return CK_FloatingCast;
4813 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004814 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004815 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004816 case Type::STK_Integral:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004817 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004818 CK_FloatingComplexToReal);
4819 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004820 case Type::STK_Pointer:
4821 llvm_unreachable("valid complex float->pointer cast?");
4822 case Type::STK_MemberPointer:
4823 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004824 }
4825 break;
4826
John McCalldaa8e4e2010-11-15 09:13:47 +00004827 case Type::STK_IntegralComplex:
4828 switch (DestTy->getScalarTypeKind()) {
4829 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004830 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004831 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004832 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004833 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004834 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00004835 if (S.Context.hasSameType(ET, DestTy))
4836 return CK_IntegralComplexToReal;
4837 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4838 return CK_IntegralCast;
4839 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004840 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004841 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004842 case Type::STK_Floating:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004843 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004844 CK_IntegralComplexToReal);
4845 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004846 case Type::STK_Pointer:
4847 llvm_unreachable("valid complex int->pointer cast?");
4848 case Type::STK_MemberPointer:
4849 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004850 }
4851 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00004852 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004853
John McCallf3ea8cf2010-11-14 08:17:51 +00004854 llvm_unreachable("Unhandled scalar cast");
4855 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00004856}
4857
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004858/// CheckCastTypes - Check type constraints for casting between types.
John McCallf89e55a2010-11-18 06:31:45 +00004859bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4860 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4861 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004862 if (getLangOptions().CPlusPlus)
Douglas Gregor40749ee2010-11-03 00:35:38 +00004863 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4864 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00004865 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004866 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004867
John McCallf89e55a2010-11-18 06:31:45 +00004868 // We only support r-value casts in C.
4869 VK = VK_RValue;
4870
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004871 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4872 // type needs to be scalar.
4873 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00004874 // We don't necessarily do lvalue-to-rvalue conversions on this.
4875 IgnoredValueConversions(castExpr);
4876
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004877 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00004878 Kind = CK_ToVoid;
Anders Carlssonebeaf202009-10-16 02:35:04 +00004879 return false;
4880 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004881
John McCallf6a16482010-12-04 03:47:34 +00004882 DefaultFunctionArrayLvalueConversion(castExpr);
4883
Eli Friedman8d438082010-07-17 20:43:49 +00004884 if (RequireCompleteType(TyR.getBegin(), castType,
4885 diag::err_typecheck_cast_to_incomplete))
4886 return true;
4887
Anders Carlssonebeaf202009-10-16 02:35:04 +00004888 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00004889 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004890 (castType->isStructureType() || castType->isUnionType())) {
4891 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004892 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004893 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4894 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004895 Kind = CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00004896 return false;
4897 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004898
Anders Carlssonc3516322009-10-16 02:48:28 +00004899 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004900 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00004901 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004902 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004903 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004904 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004905 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00004906 castExpr->getType()) &&
4907 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004908 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4909 << castExpr->getSourceRange();
4910 break;
4911 }
4912 }
4913 if (Field == FieldEnd)
4914 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4915 << castExpr->getType() << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004916 Kind = CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00004917 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004918 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004919
Anders Carlssonc3516322009-10-16 02:48:28 +00004920 // Reject any other conversions to non-scalar types.
4921 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
4922 << castType << castExpr->getSourceRange();
4923 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004924
John McCallf3ea8cf2010-11-14 08:17:51 +00004925 // The type we're casting to is known to be a scalar or vector.
4926
4927 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004928 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00004929 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004930 return Diag(castExpr->getLocStart(),
4931 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00004932 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00004933 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004934
4935 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00004936 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004937
Anders Carlssonc3516322009-10-16 02:48:28 +00004938 if (castType->isVectorType())
4939 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
4940 if (castExpr->getType()->isVectorType())
4941 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
4942
John McCallf3ea8cf2010-11-14 08:17:51 +00004943 // The source and target types are both scalars, i.e.
4944 // - arithmetic types (fundamental, enum, and complex)
4945 // - all kinds of pointers
4946 // Note that member pointers were filtered out with C++, above.
4947
Anders Carlsson16a89042009-10-16 05:23:41 +00004948 if (isa<ObjCSelectorExpr>(castExpr))
4949 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004950
John McCallf3ea8cf2010-11-14 08:17:51 +00004951 // If either type is a pointer, the other type has to be either an
4952 // integer or a pointer.
Anders Carlssonc3516322009-10-16 02:48:28 +00004953 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00004954 QualType castExprType = castExpr->getType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00004955 if (!castExprType->isIntegralType(Context) &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004956 castExprType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00004957 return Diag(castExpr->getLocStart(),
4958 diag::err_cast_pointer_from_non_pointer_int)
4959 << castExprType << castExpr->getSourceRange();
4960 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00004961 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00004962 return Diag(castExpr->getLocStart(),
4963 diag::err_cast_pointer_to_non_pointer_int)
4964 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004965 }
Anders Carlsson82debc72009-10-18 18:12:03 +00004966
John McCallf3ea8cf2010-11-14 08:17:51 +00004967 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCallb7f4ffe2010-08-12 21:44:57 +00004968
John McCallf3ea8cf2010-11-14 08:17:51 +00004969 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00004970 CheckCastAlign(castExpr, castType, TyR);
4971
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004972 return false;
4973}
4974
Anders Carlssonc3516322009-10-16 02:48:28 +00004975bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004976 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004977 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004978
Anders Carlssona64db8f2007-11-27 05:51:55 +00004979 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004980 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004981 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004982 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004983 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004984 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004985 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004986 } else
4987 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004988 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004989 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004990
John McCall2de56d12010-08-25 11:45:40 +00004991 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004992 return false;
4993}
4994
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004995bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCall2de56d12010-08-25 11:45:40 +00004996 CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004997 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004998
Anders Carlsson16a89042009-10-16 05:23:41 +00004999 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005000
Nate Begeman9b10da62009-06-27 22:05:55 +00005001 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5002 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00005003 if (SrcTy->isVectorType()) {
5004 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
5005 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5006 << DestTy << SrcTy << R;
John McCall2de56d12010-08-25 11:45:40 +00005007 Kind = CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00005008 return false;
5009 }
5010
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005011 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00005012 // conversion will take place first from scalar to elt type, and then
5013 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005014 if (SrcTy->isPointerType())
5015 return Diag(R.getBegin(),
5016 diag::err_invalid_conversion_between_vector_and_scalar)
5017 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00005018
5019 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5020 ImpCastExprToType(CastExpr, DestElemTy,
John McCallf3ea8cf2010-11-14 08:17:51 +00005021 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005022
John McCall2de56d12010-08-25 11:45:40 +00005023 Kind = CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00005024 return false;
5025}
5026
John McCall60d7b3a2010-08-24 06:29:42 +00005027ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005028Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005029 SourceLocation RParenLoc, Expr *castExpr) {
5030 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005031 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00005032
John McCall9d125032010-01-15 18:39:57 +00005033 TypeSourceInfo *castTInfo;
5034 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5035 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00005036 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00005037
Nate Begeman2ef13e52009-08-10 23:49:36 +00005038 // If the Expr being casted is a ParenListExpr, handle it specially.
5039 if (isa<ParenListExpr>(castExpr))
John McCall9ae2f072010-08-23 23:25:46 +00005040 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCall42f56b52010-01-18 19:35:47 +00005041 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00005042
John McCall9ae2f072010-08-23 23:25:46 +00005043 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00005044}
5045
John McCall60d7b3a2010-08-24 06:29:42 +00005046ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00005047Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005048 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005049 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00005050 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00005051 CXXCastPath BasePath;
John McCallb042fdf2010-01-15 18:56:44 +00005052 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCallf89e55a2010-11-18 06:31:45 +00005053 Kind, VK, BasePath))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005054 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00005055
John McCallf871d0c2010-08-07 06:22:56 +00005056 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +00005057 Ty->getType().getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +00005058 VK, Kind, castExpr, &BasePath, Ty,
John McCallf871d0c2010-08-07 06:22:56 +00005059 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005060}
5061
Nate Begeman2ef13e52009-08-10 23:49:36 +00005062/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5063/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005064ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005065Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005066 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5067 if (!E)
5068 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00005069
John McCall60d7b3a2010-08-24 06:29:42 +00005070 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00005071
Nate Begeman2ef13e52009-08-10 23:49:36 +00005072 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00005073 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5074 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00005075
John McCall9ae2f072010-08-23 23:25:46 +00005076 if (Result.isInvalid()) return ExprError();
5077
5078 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005079}
5080
John McCall60d7b3a2010-08-24 06:29:42 +00005081ExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00005082Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00005083 SourceLocation RParenLoc, Expr *Op,
John McCall42f56b52010-01-18 19:35:47 +00005084 TypeSourceInfo *TInfo) {
John McCall9ae2f072010-08-23 23:25:46 +00005085 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCall42f56b52010-01-18 19:35:47 +00005086 QualType Ty = TInfo->getType();
John Thompson8bb59a82010-06-30 22:55:51 +00005087 bool isAltiVecLiteral = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005088
John Thompson8bb59a82010-06-30 22:55:51 +00005089 // Check for an altivec literal,
5090 // i.e. all the elements are integer constants.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005091 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5092 if (PE->getNumExprs() == 0) {
5093 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5094 return ExprError();
5095 }
John Thompson8bb59a82010-06-30 22:55:51 +00005096 if (PE->getNumExprs() == 1) {
5097 if (!PE->getExpr(0)->getType()->isVectorType())
5098 isAltiVecLiteral = true;
5099 }
5100 else
5101 isAltiVecLiteral = true;
5102 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00005103
John Thompson8bb59a82010-06-30 22:55:51 +00005104 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
5105 // then handle it as such.
5106 if (isAltiVecLiteral) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005107 llvm::SmallVector<Expr *, 8> initExprs;
5108 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5109 initExprs.push_back(PE->getExpr(i));
5110
5111 // FIXME: This means that pretty-printing the final AST will produce curly
5112 // braces instead of the original commas.
Ted Kremenek709210f2010-04-13 23:39:13 +00005113 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5114 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00005115 initExprs.size(), RParenLoc);
5116 E->setType(Ty);
John McCall9ae2f072010-08-23 23:25:46 +00005117 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005118 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005119 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00005120 // sequence of BinOp comma operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005121 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCall9ae2f072010-08-23 23:25:46 +00005122 if (Result.isInvalid()) return ExprError();
5123 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005124 }
5125}
5126
John McCall60d7b3a2010-08-24 06:29:42 +00005127ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00005128 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005129 MultiExprArg Val,
John McCallb3d87482010-08-24 05:47:05 +00005130 ParsedType TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005131 unsigned nexprs = Val.size();
5132 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005133 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5134 Expr *expr;
5135 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5136 expr = new (Context) ParenExpr(L, R, exprs[0]);
5137 else
5138 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005139 return Owned(expr);
5140}
5141
Sebastian Redl28507842009-02-26 14:39:58 +00005142/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5143/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00005144/// C99 6.5.15
5145QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCallf89e55a2010-11-18 06:31:45 +00005146 Expr *&SAVE, ExprValueKind &VK,
John McCall09431682010-11-18 19:01:18 +00005147 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00005148 SourceLocation QuestionLoc) {
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005149 // If both LHS and RHS are overloaded functions, try to resolve them.
5150 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
5151 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
5152 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
5153 if (LHSResult.isInvalid())
5154 return QualType();
5155
5156 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
5157 if (RHSResult.isInvalid())
5158 return QualType();
5159
5160 LHS = LHSResult.take();
5161 RHS = RHSResult.take();
5162 }
5163
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005164 // C++ is sufficiently different to merit its own checker.
5165 if (getLangOptions().CPlusPlus)
John McCall09431682010-11-18 19:01:18 +00005166 return CXXCheckConditionalOperands(Cond, LHS, RHS, SAVE,
5167 VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00005168
5169 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005170 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005171
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005172 UsualUnaryConversions(Cond);
Fariborz Jahanian1fb019b2010-09-18 19:38:38 +00005173 if (SAVE) {
5174 SAVE = LHS = Cond;
5175 }
5176 else
5177 UsualUnaryConversions(LHS);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005178 UsualUnaryConversions(RHS);
5179 QualType CondTy = Cond->getType();
5180 QualType LHSTy = LHS->getType();
5181 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005182
Reid Spencer5f016e22007-07-11 17:01:13 +00005183 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005184 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begeman6155d732010-09-20 22:41:17 +00005185 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5186 // Throw an error if its not either.
5187 if (getLangOptions().OpenCL) {
5188 if (!CondTy->isVectorType()) {
5189 Diag(Cond->getLocStart(),
5190 diag::err_typecheck_cond_expect_scalar_or_vector)
5191 << CondTy;
5192 return QualType();
5193 }
5194 }
5195 else {
5196 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5197 << CondTy;
5198 return QualType();
5199 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005200 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005201
Chris Lattner70d67a92008-01-06 22:42:25 +00005202 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005203 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5204 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00005205
Nate Begeman6155d732010-09-20 22:41:17 +00005206 // OpenCL: If the condition is a vector, and both operands are scalar,
5207 // attempt to implicity convert them to the vector type to act like the
5208 // built in select.
5209 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5210 // Both operands should be of scalar type.
5211 if (!LHSTy->isScalarType()) {
5212 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5213 << CondTy;
5214 return QualType();
5215 }
5216 if (!RHSTy->isScalarType()) {
5217 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5218 << CondTy;
5219 return QualType();
5220 }
5221 // Implicity convert these scalars to the type of the condition.
5222 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5223 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5224 }
5225
Chris Lattner70d67a92008-01-06 22:42:25 +00005226 // If both operands have arithmetic type, do the usual arithmetic conversions
5227 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005228 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5229 UsualArithmeticConversions(LHS, RHS);
5230 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005231 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005232
Chris Lattner70d67a92008-01-06 22:42:25 +00005233 // If both operands are the same structure or union type, the result is that
5234 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005235 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5236 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005237 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005238 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005239 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005240 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005241 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005242 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005243
Chris Lattner70d67a92008-01-06 22:42:25 +00005244 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005245 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005246 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5247 if (!LHSTy->isVoidType())
5248 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5249 << RHS->getSourceRange();
5250 if (!RHSTy->isVoidType())
5251 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5252 << LHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005253 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5254 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00005255 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00005256 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00005257 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5258 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005259 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005260 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005261 // promote the null to a pointer.
John McCalldaa8e4e2010-11-15 09:13:47 +00005262 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005263 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005264 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005265 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005266 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005267 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005268 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005269 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005270
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005271 // All objective-c pointer type analysis is done here.
5272 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5273 QuestionLoc);
5274 if (!compositeType.isNull())
5275 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005276
5277
Steve Naroff7154a772009-07-01 14:36:47 +00005278 // Handle block pointer types.
5279 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5280 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5281 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5282 QualType destType = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005283 ImpCastExprToType(LHS, destType, CK_BitCast);
5284 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005285 return destType;
5286 }
5287 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005288 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00005289 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005290 }
Steve Naroff7154a772009-07-01 14:36:47 +00005291 // We have 2 block pointer types.
5292 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5293 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005294 return LHSTy;
5295 }
Steve Naroff7154a772009-07-01 14:36:47 +00005296 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00005297 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5298 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005299
Steve Naroff7154a772009-07-01 14:36:47 +00005300 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5301 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00005302 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005303 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005304 // In this situation, we assume void* type. No especially good
5305 // reason, but this is what gcc does, and we do have to pick
5306 // to get a consistent AST.
5307 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005308 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5309 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00005310 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005311 }
Steve Naroff7154a772009-07-01 14:36:47 +00005312 // The block pointer types are compatible.
John McCall2de56d12010-08-25 11:45:40 +00005313 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5314 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00005315 return LHSTy;
5316 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005317
Steve Naroff7154a772009-07-01 14:36:47 +00005318 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5319 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5320 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00005321 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5322 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00005323
5324 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5325 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5326 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00005327 QualType destPointee
5328 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005329 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005330 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005331 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005332 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005333 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005334 return destType;
5335 }
5336 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00005337 QualType destPointee
5338 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005339 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005340 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005341 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005342 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005343 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005344 return destType;
5345 }
5346
5347 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5348 // Two identical pointer types are always compatible.
5349 return LHSTy;
5350 }
5351 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5352 rhptee.getUnqualifiedType())) {
5353 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5354 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5355 // In this situation, we assume void* type. No especially good
5356 // reason, but this is what gcc does, and we do have to pick
5357 // to get a consistent AST.
5358 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005359 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5360 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005361 return incompatTy;
5362 }
5363 // The pointer types are compatible.
5364 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5365 // differently qualified versions of compatible types, the result type is
5366 // a pointer to an appropriately qualified version of the *composite*
5367 // type.
5368 // FIXME: Need to calculate the composite type.
5369 // FIXME: Need to add qualifiers
John McCall2de56d12010-08-25 11:45:40 +00005370 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5371 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005372 return LHSTy;
5373 }
Mike Stump1eb44332009-09-09 15:08:12 +00005374
John McCall404cd162010-11-13 01:35:44 +00005375 // GCC compatibility: soften pointer/integer mismatch. Note that
5376 // null pointers have been filtered out by this point.
Steve Naroff7154a772009-07-01 14:36:47 +00005377 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5378 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5379 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005380 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005381 return RHSTy;
5382 }
5383 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5384 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5385 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005386 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005387 return LHSTy;
5388 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005389
Chris Lattner70d67a92008-01-06 22:42:25 +00005390 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005391 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5392 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005393 return QualType();
5394}
5395
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005396/// FindCompositeObjCPointerType - Helper method to find composite type of
5397/// two objective-c pointer types of the two input expressions.
5398QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5399 SourceLocation QuestionLoc) {
5400 QualType LHSTy = LHS->getType();
5401 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005402
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005403 // Handle things like Class and struct objc_class*. Here we case the result
5404 // to the pseudo-builtin, because that will be implicitly cast back to the
5405 // redefinition type if an attempt is made to access its fields.
5406 if (LHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005407 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005408 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005409 return LHSTy;
5410 }
5411 if (RHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005412 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005413 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005414 return RHSTy;
5415 }
5416 // And the same for struct objc_object* / id
5417 if (LHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005418 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005419 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005420 return LHSTy;
5421 }
5422 if (RHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005423 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005424 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005425 return RHSTy;
5426 }
5427 // And the same for struct objc_selector* / SEL
5428 if (Context.isObjCSelType(LHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00005429 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005430 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005431 return LHSTy;
5432 }
5433 if (Context.isObjCSelType(RHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00005434 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005435 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005436 return RHSTy;
5437 }
5438 // Check constraints for Objective-C object pointers types.
5439 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005440
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005441 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5442 // Two identical object pointer types are always compatible.
5443 return LHSTy;
5444 }
5445 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5446 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5447 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005448
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005449 // If both operands are interfaces and either operand can be
5450 // assigned to the other, use that type as the composite
5451 // type. This allows
5452 // xxx ? (A*) a : (B*) b
5453 // where B is a subclass of A.
5454 //
5455 // Additionally, as for assignment, if either type is 'id'
5456 // allow silent coercion. Finally, if the types are
5457 // incompatible then make sure to use 'id' as the composite
5458 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005459
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005460 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5461 // It could return the composite type.
5462 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5463 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5464 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5465 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5466 } else if ((LHSTy->isObjCQualifiedIdType() ||
5467 RHSTy->isObjCQualifiedIdType()) &&
5468 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5469 // Need to handle "id<xx>" explicitly.
5470 // GCC allows qualified id and any Objective-C type to devolve to
5471 // id. Currently localizing to here until clear this should be
5472 // part of ObjCQualifiedIdTypesAreCompatible.
5473 compositeType = Context.getObjCIdType();
5474 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5475 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005476 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005477 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5478 ;
5479 else {
5480 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5481 << LHSTy << RHSTy
5482 << LHS->getSourceRange() << RHS->getSourceRange();
5483 QualType incompatTy = Context.getObjCIdType();
John McCall2de56d12010-08-25 11:45:40 +00005484 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5485 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005486 return incompatTy;
5487 }
5488 // The object pointer types are compatible.
John McCall2de56d12010-08-25 11:45:40 +00005489 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5490 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005491 return compositeType;
5492 }
5493 // Check Objective-C object pointer types and 'void *'
5494 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5495 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5496 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5497 QualType destPointee
5498 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5499 QualType destType = Context.getPointerType(destPointee);
5500 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005501 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005502 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005503 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005504 return destType;
5505 }
5506 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5507 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5508 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5509 QualType destPointee
5510 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5511 QualType destType = Context.getPointerType(destPointee);
5512 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005513 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005514 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005515 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005516 return destType;
5517 }
5518 return QualType();
5519}
5520
Steve Narofff69936d2007-09-16 03:34:24 +00005521/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005522/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005523ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005524 SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +00005525 Expr *CondExpr, Expr *LHSExpr,
5526 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005527 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5528 // was the condition.
5529 bool isLHSNull = LHSExpr == 0;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005530 Expr *SAVEExpr = 0;
5531 if (isLHSNull) {
5532 LHSExpr = SAVEExpr = CondExpr;
5533 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005534
John McCallf89e55a2010-11-18 06:31:45 +00005535 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005536 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian1fb019b2010-09-18 19:38:38 +00005537 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCall09431682010-11-18 19:01:18 +00005538 SAVEExpr, VK, OK, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00005539 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005540 return ExprError();
5541
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00005542 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005543 LHSExpr, ColonLoc,
5544 RHSExpr, SAVEExpr,
John McCall09431682010-11-18 19:01:18 +00005545 result, VK, OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005546}
5547
John McCalle4be87e2011-01-31 23:13:11 +00005548// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005549// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005550// routine is it effectively iqnores the qualifiers on the top level pointee.
5551// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5552// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005553static Sema::AssignConvertType
5554checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5555 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5556 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005557
Reid Spencer5f016e22007-07-11 17:01:13 +00005558 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005559 const Type *lhptee, *rhptee;
5560 Qualifiers lhq, rhq;
5561 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5562 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005563
John McCalle4be87e2011-01-31 23:13:11 +00005564 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005565
5566 // C99 6.5.16.1p1: This following citation is common to constraints
5567 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5568 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005569 Qualifiers lq;
5570
5571 if (!lhq.compatiblyIncludes(rhq)) {
5572 // Treat address-space mismatches as fatal. TODO: address subspaces
5573 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5574 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5575
5576 // For GCC compatibility, other qualifier mismatches are treated
5577 // as still compatible in C.
5578 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5579 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005580
Mike Stumpeed9cac2009-02-19 03:04:26 +00005581 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5582 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005583 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005584 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005585 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005586 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005587
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005588 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005589 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005590 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005591 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005592
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005593 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005594 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005595 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005596
5597 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005598 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005599 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005600 }
John McCall86c05f32011-02-01 00:10:29 +00005601
Mike Stumpeed9cac2009-02-19 03:04:26 +00005602 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005603 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005604 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5605 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005606 // Check if the pointee types are compatible ignoring the sign.
5607 // We explicitly check for char so that we catch "char" vs
5608 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005609 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005610 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005611 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005612 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005613
Chris Lattner6a2b9262009-10-17 20:33:28 +00005614 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005615 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005616 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005617 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005618
John McCall86c05f32011-02-01 00:10:29 +00005619 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005620 // Types are compatible ignoring the sign. Qualifier incompatibility
5621 // takes priority over sign incompatibility because the sign
5622 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005623 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005624 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005625
John McCalle4be87e2011-01-31 23:13:11 +00005626 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005627 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005628
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005629 // If we are a multi-level pointer, it's possible that our issue is simply
5630 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5631 // the eventual target type is the same and the pointers have the same
5632 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005633 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005634 do {
John McCall86c05f32011-02-01 00:10:29 +00005635 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5636 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005637 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005638
John McCall86c05f32011-02-01 00:10:29 +00005639 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005640 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005641 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005642
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005643 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005644 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005645 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005646 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005647}
5648
John McCalle4be87e2011-01-31 23:13:11 +00005649/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005650/// block pointer types are compatible or whether a block and normal pointer
5651/// are compatible. It is more restrict than comparing two function pointer
5652// types.
John McCalle4be87e2011-01-31 23:13:11 +00005653static Sema::AssignConvertType
5654checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5655 QualType rhsType) {
5656 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5657 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5658
Steve Naroff1c7d0672008-09-04 15:10:53 +00005659 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005660
Steve Naroff1c7d0672008-09-04 15:10:53 +00005661 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00005662 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5663 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005664
John McCalle4be87e2011-01-31 23:13:11 +00005665 // In C++, the types have to match exactly.
5666 if (S.getLangOptions().CPlusPlus)
5667 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005668
John McCalle4be87e2011-01-31 23:13:11 +00005669 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005670
Steve Naroff1c7d0672008-09-04 15:10:53 +00005671 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005672 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5673 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005674
John McCalle4be87e2011-01-31 23:13:11 +00005675 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5676 return Sema::IncompatibleBlockPointer;
5677
Steve Naroff1c7d0672008-09-04 15:10:53 +00005678 return ConvTy;
5679}
5680
John McCalle4be87e2011-01-31 23:13:11 +00005681/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005682/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005683static Sema::AssignConvertType
5684checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5685 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5686 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5687
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005688 if (lhsType->isObjCBuiltinType()) {
5689 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005690 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5691 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005692 return Sema::IncompatiblePointer;
5693 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005694 }
5695 if (rhsType->isObjCBuiltinType()) {
5696 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005697 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5698 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005699 return Sema::IncompatiblePointer;
5700 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005701 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005702 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005703 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005704 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005705 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005706
John McCalle4be87e2011-01-31 23:13:11 +00005707 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5708 return Sema::CompatiblePointerDiscardsQualifiers;
5709
5710 if (S.Context.typesAreCompatible(lhsType, rhsType))
5711 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005712 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005713 return Sema::IncompatibleObjCQualifiedId;
5714 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005715}
5716
John McCall1c23e912010-11-16 02:32:08 +00005717Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005718Sema::CheckAssignmentConstraints(SourceLocation Loc,
5719 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00005720 // Fake up an opaque expression. We don't actually care about what
5721 // cast operations are required, so if CheckAssignmentConstraints
5722 // adds casts to this they'll be wasted, but fortunately that doesn't
5723 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00005724 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John McCall1c23e912010-11-16 02:32:08 +00005725 Expr *rhsPtr = &rhs;
5726 CastKind K = CK_Invalid;
5727
5728 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5729}
5730
Mike Stumpeed9cac2009-02-19 03:04:26 +00005731/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5732/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005733/// pointers. Here are some objectionable examples that GCC considers warnings:
5734///
5735/// int a, *pint;
5736/// short *pshort;
5737/// struct foo *pfoo;
5738///
5739/// pint = pshort; // warning: assignment from incompatible pointer type
5740/// a = pint; // warning: assignment makes integer from pointer without a cast
5741/// pint = a; // warning: assignment makes pointer from integer without a cast
5742/// pint = pfoo; // warning: assignment from incompatible pointer type
5743///
5744/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005745/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005746///
John McCalldaa8e4e2010-11-15 09:13:47 +00005747/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005748Sema::AssignConvertType
John McCall1c23e912010-11-16 02:32:08 +00005749Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00005750 CastKind &Kind) {
John McCall1c23e912010-11-16 02:32:08 +00005751 QualType rhsType = rhs->getType();
5752
Chris Lattnerfc144e22008-01-04 23:18:45 +00005753 // Get canonical types. We're not formatting these types, just comparing
5754 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005755 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5756 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005757
John McCallb6cfa242011-01-31 22:28:28 +00005758 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00005759 if (lhsType == rhsType) {
5760 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005761 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005762 }
5763
Douglas Gregor9d293df2008-10-28 00:22:11 +00005764 // If the left-hand side is a reference type, then we are in a
5765 // (rare!) case where we've allowed the use of references in C,
5766 // e.g., as a parameter type in a built-in function. In this case,
5767 // just make sure that the type referenced is compatible with the
5768 // right-hand side type. The caller is responsible for adjusting
5769 // lhsType so that the resulting expression does not have reference
5770 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005771 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005772 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5773 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005774 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005775 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005776 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005777 }
John McCallb6cfa242011-01-31 22:28:28 +00005778
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005779 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5780 // to the same ExtVector type.
5781 if (lhsType->isExtVectorType()) {
5782 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005783 return Incompatible;
5784 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005785 // CK_VectorSplat does T -> vector T, so first cast to the
5786 // element type.
5787 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5788 if (elType != rhsType) {
5789 Kind = PrepareScalarCast(*this, rhs, elType);
5790 ImpCastExprToType(rhs, elType, Kind);
5791 }
5792 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005793 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005794 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005795 }
Mike Stump1eb44332009-09-09 15:08:12 +00005796
John McCallb6cfa242011-01-31 22:28:28 +00005797 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005798 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00005799 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005800 // Allow assignments of an AltiVec vector type to an equivalent GCC
5801 // vector type and vice versa
5802 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5803 Kind = CK_BitCast;
5804 return Compatible;
5805 }
5806
Douglas Gregor255210e2010-08-06 10:14:59 +00005807 // If we are allowing lax vector conversions, and LHS and RHS are both
5808 // vectors, the total size only needs to be the same. This is a bitcast;
5809 // no bits are changed but the result type is different.
5810 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005811 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005812 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005813 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005814 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005815 }
5816 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005817 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005818
John McCallb6cfa242011-01-31 22:28:28 +00005819 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00005820 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005821 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00005822 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005823 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005824 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005825
John McCallb6cfa242011-01-31 22:28:28 +00005826 // Conversions to normal pointers.
5827 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5828 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00005829 if (isa<PointerType>(rhsType)) {
5830 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00005831 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005832 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005833
John McCallb6cfa242011-01-31 22:28:28 +00005834 // int -> T*
5835 if (rhsType->isIntegerType()) {
5836 Kind = CK_IntegralToPointer; // FIXME: null?
5837 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005838 }
John McCallb6cfa242011-01-31 22:28:28 +00005839
5840 // C pointers are not compatible with ObjC object pointers,
5841 // with two exceptions:
5842 if (isa<ObjCObjectPointerType>(rhsType)) {
5843 // - conversions to void*
5844 if (lhsPointer->getPointeeType()->isVoidType()) {
5845 Kind = CK_AnyPointerToObjCPointerCast;
5846 return Compatible;
5847 }
5848
5849 // - conversions from 'Class' to the redefinition type
5850 if (rhsType->isObjCClassType() &&
5851 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005852 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005853 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005854 }
Steve Naroffb4406862008-09-29 18:10:17 +00005855
John McCallb6cfa242011-01-31 22:28:28 +00005856 Kind = CK_BitCast;
5857 return IncompatiblePointer;
5858 }
5859
5860 // U^ -> void*
5861 if (rhsType->getAs<BlockPointerType>()) {
5862 if (lhsPointer->getPointeeType()->isVoidType()) {
5863 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005864 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005865 }
Steve Naroffb4406862008-09-29 18:10:17 +00005866 }
John McCallb6cfa242011-01-31 22:28:28 +00005867
Steve Naroff1c7d0672008-09-04 15:10:53 +00005868 return Incompatible;
5869 }
5870
John McCallb6cfa242011-01-31 22:28:28 +00005871 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00005872 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005873 // U^ -> T^
5874 if (rhsType->isBlockPointerType()) {
5875 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00005876 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00005877 }
5878
5879 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00005880 if (rhsType->isIntegerType()) {
5881 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005882 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005883 }
5884
John McCallb6cfa242011-01-31 22:28:28 +00005885 // id -> T^
5886 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5887 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005888 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005889 }
Steve Naroffb4406862008-09-29 18:10:17 +00005890
John McCallb6cfa242011-01-31 22:28:28 +00005891 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00005892 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005893 if (RHSPT->getPointeeType()->isVoidType()) {
5894 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005895 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005896 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005897
Chris Lattnerfc144e22008-01-04 23:18:45 +00005898 return Incompatible;
5899 }
5900
John McCallb6cfa242011-01-31 22:28:28 +00005901 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00005902 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005903 // A* -> B*
5904 if (rhsType->isObjCObjectPointerType()) {
5905 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00005906 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00005907 }
5908
5909 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00005910 if (rhsType->isIntegerType()) {
5911 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005912 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005913 }
5914
John McCallb6cfa242011-01-31 22:28:28 +00005915 // In general, C pointers are not compatible with ObjC object pointers,
5916 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00005917 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005918 // - conversions from 'void*'
5919 if (rhsType->isVoidPointerType()) {
5920 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005921 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005922 }
5923
5924 // - conversions to 'Class' from its redefinition type
5925 if (lhsType->isObjCClassType() &&
5926 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
5927 Kind = CK_BitCast;
5928 return Compatible;
5929 }
5930
5931 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005932 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005933 }
John McCallb6cfa242011-01-31 22:28:28 +00005934
5935 // T^ -> A*
5936 if (rhsType->isBlockPointerType()) {
5937 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005938 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005939 }
5940
Steve Naroff14108da2009-07-10 23:34:53 +00005941 return Incompatible;
5942 }
John McCallb6cfa242011-01-31 22:28:28 +00005943
5944 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00005945 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005946 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00005947 if (lhsType == Context.BoolTy) {
5948 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005949 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005950 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005951
John McCallb6cfa242011-01-31 22:28:28 +00005952 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00005953 if (lhsType->isIntegerType()) {
5954 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005955 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005956 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005957
Chris Lattnerfc144e22008-01-04 23:18:45 +00005958 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005959 }
John McCallb6cfa242011-01-31 22:28:28 +00005960
5961 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00005962 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005963 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00005964 if (lhsType == Context.BoolTy) {
5965 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005966 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005967 }
Steve Naroff14108da2009-07-10 23:34:53 +00005968
John McCallb6cfa242011-01-31 22:28:28 +00005969 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00005970 if (lhsType->isIntegerType()) {
5971 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005972 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005973 }
5974
Steve Naroff14108da2009-07-10 23:34:53 +00005975 return Incompatible;
5976 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005977
John McCallb6cfa242011-01-31 22:28:28 +00005978 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00005979 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005980 if (Context.typesAreCompatible(lhsType, rhsType)) {
5981 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005982 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005983 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005984 }
John McCallb6cfa242011-01-31 22:28:28 +00005985
Reid Spencer5f016e22007-07-11 17:01:13 +00005986 return Incompatible;
5987}
5988
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005989/// \brief Constructs a transparent union from an expression that is
5990/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00005991static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005992 QualType UnionType, FieldDecl *Field) {
5993 // Build an initializer list that designates the appropriate member
5994 // of the transparent union.
Ted Kremenek709210f2010-04-13 23:39:13 +00005995 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005996 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005997 SourceLocation());
5998 Initializer->setType(UnionType);
5999 Initializer->setInitializedFieldInUnion(Field);
6000
6001 // Build a compound literal constructing a value of the transparent
6002 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00006003 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall1d7d8d62010-01-19 22:33:45 +00006004 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCallf89e55a2010-11-18 06:31:45 +00006005 VK_RValue, Initializer, false);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006006}
6007
6008Sema::AssignConvertType
6009Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
6010 QualType FromType = rExpr->getType();
6011
Mike Stump1eb44332009-09-09 15:08:12 +00006012 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006013 // transparent_union GCC extension.
6014 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006015 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006016 return Incompatible;
6017
6018 // The field to initialize within the transparent union.
6019 RecordDecl *UD = UT->getDecl();
6020 FieldDecl *InitField = 0;
6021 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006022 for (RecordDecl::field_iterator it = UD->field_begin(),
6023 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006024 it != itend; ++it) {
6025 if (it->getType()->isPointerType()) {
6026 // If the transparent union contains a pointer type, we allow:
6027 // 1) void pointer
6028 // 2) null pointer constant
6029 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00006030 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCall2de56d12010-08-25 11:45:40 +00006031 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006032 InitField = *it;
6033 break;
6034 }
Mike Stump1eb44332009-09-09 15:08:12 +00006035
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006036 if (rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006037 Expr::NPC_ValueDependentIsNull)) {
John McCall404cd162010-11-13 01:35:44 +00006038 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006039 InitField = *it;
6040 break;
6041 }
6042 }
6043
John McCall1c23e912010-11-16 02:32:08 +00006044 Expr *rhs = rExpr;
John McCalldaa8e4e2010-11-15 09:13:47 +00006045 CastKind Kind = CK_Invalid;
John McCall1c23e912010-11-16 02:32:08 +00006046 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006047 == Compatible) {
John McCall1c23e912010-11-16 02:32:08 +00006048 ImpCastExprToType(rhs, it->getType(), Kind);
6049 rExpr = rhs;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006050 InitField = *it;
6051 break;
6052 }
6053 }
6054
6055 if (!InitField)
6056 return Incompatible;
6057
6058 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
6059 return Compatible;
6060}
6061
Chris Lattner5cf216b2008-01-04 18:04:52 +00006062Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00006063Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00006064 if (getLangOptions().CPlusPlus) {
6065 if (!lhsType->isRecordType()) {
6066 // C++ 5.17p3: If the left operand is not of class type, the
6067 // expression is implicitly converted (C++ 4) to the
6068 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00006069 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00006070 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00006071 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00006072 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00006073 }
6074
6075 // FIXME: Currently, we fall through and treat C++ classes like C
6076 // structures.
John McCallf6a16482010-12-04 03:47:34 +00006077 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00006078
Steve Naroff529a4ad2007-11-27 17:58:44 +00006079 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6080 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00006081 if ((lhsType->isPointerType() ||
6082 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00006083 lhsType->isBlockPointerType())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006084 && rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006085 Expr::NPC_ValueDependentIsNull)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006086 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00006087 return Compatible;
6088 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006089
Chris Lattner943140e2007-10-16 02:55:40 +00006090 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00006091 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00006092 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00006093 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00006094 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00006095 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00006096 if (!lhsType->isReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00006097 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00006098
John McCalldaa8e4e2010-11-15 09:13:47 +00006099 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006100 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00006101 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006102
Steve Narofff1120de2007-08-24 22:33:52 +00006103 // C99 6.5.16.1p2: The value of the right operand is converted to the
6104 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006105 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6106 // so that we can use references in built-in functions even in C.
6107 // The getNonReferenceType() call makes sure that the resulting expression
6108 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006109 if (result != Incompatible && rExpr->getType() != lhsType)
John McCalldaa8e4e2010-11-15 09:13:47 +00006110 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006111 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006112}
6113
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006114QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006115 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00006116 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006117 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00006118 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006119}
6120
Chris Lattner7ef655a2010-01-12 21:23:57 +00006121QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00006122 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006123 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00006124 QualType lhsType =
6125 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
6126 QualType rhsType =
6127 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006128
Nate Begemanbe2341d2008-07-14 18:02:46 +00006129 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006130 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00006131 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006132
Nate Begemanbe2341d2008-07-14 18:02:46 +00006133 // Handle the case of a vector & extvector type of the same size and element
6134 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006135 if (getLangOptions().LaxVectorConversions) {
John McCall183700f2009-09-21 23:43:11 +00006136 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth629f9e42010-08-30 07:36:24 +00006137 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006138 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006139 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregor26bcf672010-05-19 03:21:00 +00006140 if (lhsType->isExtVectorType()) {
John McCall2de56d12010-08-25 11:45:40 +00006141 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006142 return lhsType;
6143 }
6144
John McCall2de56d12010-08-25 11:45:40 +00006145 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006146 return rhsType;
Eric Christophere84f9eb2010-08-26 00:42:16 +00006147 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6148 // If we are allowing lax vector conversions, and LHS and RHS are both
6149 // vectors, the total size only needs to be the same. This is a
6150 // bitcast; no bits are changed but the result type is different.
6151 ImpCastExprToType(rex, lhsType, CK_BitCast);
6152 return lhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006153 }
Eric Christophere84f9eb2010-08-26 00:42:16 +00006154 }
Chandler Carruth629f9e42010-08-30 07:36:24 +00006155 }
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006156 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006157
Douglas Gregor255210e2010-08-06 10:14:59 +00006158 // Handle the case of equivalent AltiVec and GCC vector types
6159 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6160 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCall2de56d12010-08-25 11:45:40 +00006161 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00006162 return rhsType;
6163 }
6164
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006165 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6166 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6167 bool swapped = false;
6168 if (rhsType->isExtVectorType()) {
6169 swapped = true;
6170 std::swap(rex, lex);
6171 std::swap(rhsType, lhsType);
6172 }
Mike Stump1eb44332009-09-09 15:08:12 +00006173
Nate Begemandde25982009-06-28 19:12:57 +00006174 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00006175 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006176 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00006177 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006178 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6179 if (order > 0)
6180 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
6181 if (order >= 0) {
6182 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006183 if (swapped) std::swap(rex, lex);
6184 return lhsType;
6185 }
6186 }
6187 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6188 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006189 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6190 if (order > 0)
6191 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
6192 if (order >= 0) {
6193 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006194 if (swapped) std::swap(rex, lex);
6195 return lhsType;
6196 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006197 }
6198 }
Mike Stump1eb44332009-09-09 15:08:12 +00006199
Nate Begemandde25982009-06-28 19:12:57 +00006200 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006201 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00006202 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006203 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006204 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006205}
6206
Chris Lattner7ef655a2010-01-12 21:23:57 +00006207QualType Sema::CheckMultiplyDivideOperands(
6208 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00006209 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006210 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006211
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006212 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006213
Chris Lattner7ef655a2010-01-12 21:23:57 +00006214 if (!lex->getType()->isArithmeticType() ||
6215 !rex->getType()->isArithmeticType())
6216 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006217
Chris Lattner7ef655a2010-01-12 21:23:57 +00006218 // Check for division by zero.
6219 if (isDiv &&
6220 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006221 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattnercb329c52010-01-12 21:30:55 +00006222 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006223
Chris Lattner7ef655a2010-01-12 21:23:57 +00006224 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006225}
6226
Chris Lattner7ef655a2010-01-12 21:23:57 +00006227QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00006228 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00006229 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006230 if (lex->getType()->hasIntegerRepresentation() &&
6231 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar523aa602009-01-05 22:55:36 +00006232 return CheckVectorOperands(Loc, lex, rex);
6233 return InvalidOperands(Loc, lex, rex);
6234 }
Steve Naroff90045e82007-07-13 23:32:42 +00006235
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006236 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006237
Chris Lattner7ef655a2010-01-12 21:23:57 +00006238 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6239 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006240
Chris Lattner7ef655a2010-01-12 21:23:57 +00006241 // Check for remainder by zero.
6242 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattnercb329c52010-01-12 21:30:55 +00006243 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
6244 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006245
Chris Lattner7ef655a2010-01-12 21:23:57 +00006246 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006247}
6248
Chris Lattner7ef655a2010-01-12 21:23:57 +00006249QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00006250 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006251 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6252 QualType compType = CheckVectorOperands(Loc, lex, rex);
6253 if (CompLHSTy) *CompLHSTy = compType;
6254 return compType;
6255 }
Steve Naroff49b45262007-07-13 16:58:59 +00006256
Eli Friedmanab3a8522009-03-28 01:22:36 +00006257 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006258
Reid Spencer5f016e22007-07-11 17:01:13 +00006259 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00006260 if (lex->getType()->isArithmeticType() &&
6261 rex->getType()->isArithmeticType()) {
6262 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006263 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006264 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006265
Eli Friedmand72d16e2008-05-18 18:08:51 +00006266 // Put any potential pointer into PExp
6267 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006268 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006269 std::swap(PExp, IExp);
6270
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006271 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006272
Eli Friedmand72d16e2008-05-18 18:08:51 +00006273 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00006274 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00006275
Chris Lattnerb5f15622009-04-24 23:50:08 +00006276 // Check for arithmetic on pointers to incomplete types.
6277 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006278 if (getLangOptions().CPlusPlus) {
6279 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006280 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006281 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006282 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006283
6284 // GNU extension: arithmetic on pointer to void
6285 Diag(Loc, diag::ext_gnu_void_ptr)
6286 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00006287 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006288 if (getLangOptions().CPlusPlus) {
6289 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6290 << lex->getType() << lex->getSourceRange();
6291 return QualType();
6292 }
6293
6294 // GNU extension: arithmetic on pointer to function
6295 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6296 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00006297 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00006298 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00006299 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00006300 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00006301 PExp->getType()->isObjCObjectPointerType()) &&
6302 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00006303 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6304 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006305 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00006306 return QualType();
6307 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00006308 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006309 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006310 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6311 << PointeeTy << PExp->getSourceRange();
6312 return QualType();
6313 }
Mike Stump1eb44332009-09-09 15:08:12 +00006314
Eli Friedmanab3a8522009-03-28 01:22:36 +00006315 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00006316 QualType LHSTy = Context.isPromotableBitField(lex);
6317 if (LHSTy.isNull()) {
6318 LHSTy = lex->getType();
6319 if (LHSTy->isPromotableIntegerType())
6320 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00006321 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00006322 *CompLHSTy = LHSTy;
6323 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00006324 return PExp->getType();
6325 }
6326 }
6327
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006328 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006329}
6330
Chris Lattnereca7be62008-04-07 05:30:13 +00006331// C99 6.5.6
6332QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006333 SourceLocation Loc, QualType* CompLHSTy) {
6334 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6335 QualType compType = CheckVectorOperands(Loc, lex, rex);
6336 if (CompLHSTy) *CompLHSTy = compType;
6337 return compType;
6338 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006339
Eli Friedmanab3a8522009-03-28 01:22:36 +00006340 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006341
Chris Lattner6e4ab612007-12-09 21:53:25 +00006342 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006343
Chris Lattner6e4ab612007-12-09 21:53:25 +00006344 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00006345 if (lex->getType()->isArithmeticType()
6346 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006347 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006348 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006349 }
Mike Stump1eb44332009-09-09 15:08:12 +00006350
Chris Lattner6e4ab612007-12-09 21:53:25 +00006351 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006352 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00006353 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006354
Douglas Gregore7450f52009-03-24 19:52:54 +00006355 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00006356
Douglas Gregore7450f52009-03-24 19:52:54 +00006357 bool ComplainAboutVoid = false;
6358 Expr *ComplainAboutFunc = 0;
6359 if (lpointee->isVoidType()) {
6360 if (getLangOptions().CPlusPlus) {
6361 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6362 << lex->getSourceRange() << rex->getSourceRange();
6363 return QualType();
6364 }
6365
6366 // GNU C extension: arithmetic on pointer to void
6367 ComplainAboutVoid = true;
6368 } else if (lpointee->isFunctionType()) {
6369 if (getLangOptions().CPlusPlus) {
6370 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00006371 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006372 return QualType();
6373 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006374
6375 // GNU C extension: arithmetic on pointer to function
6376 ComplainAboutFunc = lex;
6377 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006378 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00006379 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00006380 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006381 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00006382 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006383
Chris Lattnerb5f15622009-04-24 23:50:08 +00006384 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006385 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006386 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6387 << lpointee << lex->getSourceRange();
6388 return QualType();
6389 }
Mike Stump1eb44332009-09-09 15:08:12 +00006390
Chris Lattner6e4ab612007-12-09 21:53:25 +00006391 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00006392 if (rex->getType()->isIntegerType()) {
6393 if (ComplainAboutVoid)
6394 Diag(Loc, diag::ext_gnu_void_ptr)
6395 << lex->getSourceRange() << rex->getSourceRange();
6396 if (ComplainAboutFunc)
6397 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00006398 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00006399 << ComplainAboutFunc->getSourceRange();
6400
Eli Friedmanab3a8522009-03-28 01:22:36 +00006401 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006402 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006403 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006404
Chris Lattner6e4ab612007-12-09 21:53:25 +00006405 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006406 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006407 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006408
Douglas Gregore7450f52009-03-24 19:52:54 +00006409 // RHS must be a completely-type object type.
6410 // Handle the GNU void* extension.
6411 if (rpointee->isVoidType()) {
6412 if (getLangOptions().CPlusPlus) {
6413 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6414 << lex->getSourceRange() << rex->getSourceRange();
6415 return QualType();
6416 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006417
Douglas Gregore7450f52009-03-24 19:52:54 +00006418 ComplainAboutVoid = true;
6419 } else if (rpointee->isFunctionType()) {
6420 if (getLangOptions().CPlusPlus) {
6421 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00006422 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006423 return QualType();
6424 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006425
6426 // GNU extension: arithmetic on pointer to function
6427 if (!ComplainAboutFunc)
6428 ComplainAboutFunc = rex;
6429 } else if (!rpointee->isDependentType() &&
6430 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00006431 PDiag(diag::err_typecheck_sub_ptr_object)
6432 << rex->getSourceRange()
6433 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00006434 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006435
Eli Friedman88d936b2009-05-16 13:54:38 +00006436 if (getLangOptions().CPlusPlus) {
6437 // Pointee types must be the same: C++ [expr.add]
6438 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6439 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6440 << lex->getType() << rex->getType()
6441 << lex->getSourceRange() << rex->getSourceRange();
6442 return QualType();
6443 }
6444 } else {
6445 // Pointee types must be compatible C99 6.5.6p3
6446 if (!Context.typesAreCompatible(
6447 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6448 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6449 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6450 << lex->getType() << rex->getType()
6451 << lex->getSourceRange() << rex->getSourceRange();
6452 return QualType();
6453 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006454 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006455
Douglas Gregore7450f52009-03-24 19:52:54 +00006456 if (ComplainAboutVoid)
6457 Diag(Loc, diag::ext_gnu_void_ptr)
6458 << lex->getSourceRange() << rex->getSourceRange();
6459 if (ComplainAboutFunc)
6460 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00006461 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00006462 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006463
6464 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006465 return Context.getPointerDiffType();
6466 }
6467 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006468
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006469 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006470}
6471
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006472static bool isScopedEnumerationType(QualType T) {
6473 if (const EnumType *ET = dyn_cast<EnumType>(T))
6474 return ET->getDecl()->isScoped();
6475 return false;
6476}
6477
Chris Lattnereca7be62008-04-07 05:30:13 +00006478// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006479QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00006480 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00006481 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregorf6094622010-07-23 15:58:24 +00006482 if (!lex->getType()->hasIntegerRepresentation() ||
6483 !rex->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006484 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006485
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006486 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6487 // hasIntegerRepresentation() above instead of this.
6488 if (isScopedEnumerationType(lex->getType()) ||
6489 isScopedEnumerationType(rex->getType())) {
6490 return InvalidOperands(Loc, lex, rex);
6491 }
6492
Nate Begeman2207d792009-10-25 02:26:48 +00006493 // Vector shifts promote their scalar inputs to vector type.
6494 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6495 return CheckVectorOperands(Loc, lex, rex);
6496
Chris Lattnerca5eede2007-12-12 05:47:28 +00006497 // Shifts don't perform usual arithmetic conversions, they just do integer
6498 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006499
John McCall1bc80af2010-12-16 19:28:59 +00006500 // For the LHS, do usual unary conversions, but then reset them away
6501 // if this is a compound assignment.
6502 Expr *old_lex = lex;
6503 UsualUnaryConversions(lex);
6504 QualType LHSTy = lex->getType();
6505 if (isCompAssign) lex = old_lex;
6506
6507 // The RHS is simpler.
Chris Lattnerca5eede2007-12-12 05:47:28 +00006508 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006509
Ryan Flynnd0439682009-08-07 16:20:20 +00006510 // Sanity-check shift operands
6511 llvm::APSInt Right;
6512 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00006513 if (!rex->isValueDependent() &&
6514 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00006515 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00006516 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6517 else {
6518 llvm::APInt LeftBits(Right.getBitWidth(),
6519 Context.getTypeSize(lex->getType()));
6520 if (Right.uge(LeftBits))
6521 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6522 }
6523 }
6524
Chris Lattnerca5eede2007-12-12 05:47:28 +00006525 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00006526 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006527}
6528
Chandler Carruth99919472010-07-10 12:30:03 +00006529static bool IsWithinTemplateSpecialization(Decl *D) {
6530 if (DeclContext *DC = D->getDeclContext()) {
6531 if (isa<ClassTemplateSpecializationDecl>(DC))
6532 return true;
6533 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6534 return FD->isFunctionTemplateSpecialization();
6535 }
6536 return false;
6537}
6538
Douglas Gregor0c6db942009-05-04 06:07:12 +00006539// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006540QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00006541 unsigned OpaqueOpc, bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00006542 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006543
Chris Lattner02dd4b12009-12-05 05:40:13 +00006544 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00006545 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006546 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006547
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006548 QualType lType = lex->getType();
6549 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006550
Douglas Gregor8eee1192010-06-22 22:12:46 +00006551 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006552 !(lType->isBlockPointerType() && isRelational) &&
6553 !lex->getLocStart().isMacroID() &&
6554 !rex->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006555 // For non-floating point types, check for self-comparisons of the form
6556 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6557 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006558 //
6559 // NOTE: Don't warn about comparison expressions resulting from macro
6560 // expansion. Also don't warn about comparisons which are only self
6561 // comparisons within a template specialization. The warnings should catch
6562 // obvious cases in the definition of the template anyways. The idea is to
6563 // warn when the typed comparison operator will always evaluate to the same
6564 // result.
John McCallf6a16482010-12-04 03:47:34 +00006565 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6566 Expr *RHSStripped = rex->IgnoreParenImpCasts();
Chandler Carruth99919472010-07-10 12:30:03 +00006567 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006568 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006569 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006570 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006571 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6572 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006573 << (Opc == BO_EQ
6574 || Opc == BO_LE
6575 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00006576 } else if (lType->isArrayType() && rType->isArrayType() &&
6577 !DRL->getDecl()->getType()->isReferenceType() &&
6578 !DRR->getDecl()->getType()->isReferenceType()) {
6579 // what is it always going to eval to?
6580 char always_evals_to;
6581 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006582 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006583 always_evals_to = 0; // false
6584 break;
John McCall2de56d12010-08-25 11:45:40 +00006585 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006586 always_evals_to = 1; // true
6587 break;
6588 default:
6589 // best we can say is 'a constant'
6590 always_evals_to = 2; // e.g. array1 <= array2
6591 break;
6592 }
6593 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6594 << 1 // array
6595 << always_evals_to);
6596 }
6597 }
Chandler Carruth99919472010-07-10 12:30:03 +00006598 }
Mike Stump1eb44332009-09-09 15:08:12 +00006599
Chris Lattner55660a72009-03-08 19:39:53 +00006600 if (isa<CastExpr>(LHSStripped))
6601 LHSStripped = LHSStripped->IgnoreParenCasts();
6602 if (isa<CastExpr>(RHSStripped))
6603 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006604
Chris Lattner55660a72009-03-08 19:39:53 +00006605 // Warn about comparisons against a string constant (unless the other
6606 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006607 Expr *literalString = 0;
6608 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006609 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006610 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006611 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00006612 literalString = lex;
6613 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006614 } else if ((isa<StringLiteral>(RHSStripped) ||
6615 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006616 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006617 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00006618 literalString = rex;
6619 literalStringStripped = RHSStripped;
6620 }
6621
6622 if (literalString) {
6623 std::string resultComparison;
6624 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006625 case BO_LT: resultComparison = ") < 0"; break;
6626 case BO_GT: resultComparison = ") > 0"; break;
6627 case BO_LE: resultComparison = ") <= 0"; break;
6628 case BO_GE: resultComparison = ") >= 0"; break;
6629 case BO_EQ: resultComparison = ") == 0"; break;
6630 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00006631 default: assert(false && "Invalid comparison operator");
6632 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006633
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006634 DiagRuntimeBehavior(Loc,
6635 PDiag(diag::warn_stringcompare)
6636 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006637 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006638 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006639 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006640
Douglas Gregord64fdd02010-06-08 19:50:34 +00006641 // C99 6.5.8p3 / C99 6.5.9p4
6642 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6643 UsualArithmeticConversions(lex, rex);
6644 else {
6645 UsualUnaryConversions(lex);
6646 UsualUnaryConversions(rex);
6647 }
6648
6649 lType = lex->getType();
6650 rType = rex->getType();
6651
Douglas Gregor447b69e2008-11-19 03:25:36 +00006652 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00006653 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00006654
Chris Lattnera5937dd2007-08-26 01:18:55 +00006655 if (isRelational) {
6656 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006657 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006658 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006659 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006660 if (lType->hasFloatingRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006661 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006662
Chris Lattnera5937dd2007-08-26 01:18:55 +00006663 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006664 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006665 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006666
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006667 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006668 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006669 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006670 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006671
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006672 // All of the following pointer-related warnings are GCC extensions, except
6673 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00006674 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006675 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006676 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00006677 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006678 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006679
Douglas Gregor0c6db942009-05-04 06:07:12 +00006680 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006681 if (LCanPointeeTy == RCanPointeeTy)
6682 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006683 if (!isRelational &&
6684 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6685 // Valid unless comparison between non-null pointer and function pointer
6686 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006687 // In a SFINAE context, we treat this as a hard error to maintain
6688 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006689 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6690 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006691 Diag(Loc,
6692 isSFINAEContext()?
6693 diag::err_typecheck_comparison_of_fptr_to_void
6694 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006695 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006696
6697 if (isSFINAEContext())
6698 return QualType();
6699
John McCall2de56d12010-08-25 11:45:40 +00006700 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006701 return ResultTy;
6702 }
6703 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006704
Douglas Gregor0c6db942009-05-04 06:07:12 +00006705 // C++ [expr.rel]p2:
6706 // [...] Pointer conversions (4.10) and qualification
6707 // conversions (4.4) are performed on pointer operands (or on
6708 // a pointer operand and a null pointer constant) to bring
6709 // them to their composite pointer type. [...]
6710 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00006711 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00006712 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006713 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006714 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006715 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006716 if (T.isNull()) {
6717 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6718 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6719 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006720 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006721 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006722 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006723 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006724 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00006725 }
6726
John McCall2de56d12010-08-25 11:45:40 +00006727 ImpCastExprToType(lex, T, CK_BitCast);
6728 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006729 return ResultTy;
6730 }
Eli Friedman3075e762009-08-23 00:27:47 +00006731 // C99 6.5.9p2 and C99 6.5.8p2
6732 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6733 RCanPointeeTy.getUnqualifiedType())) {
6734 // Valid unless a relational comparison of function pointers
6735 if (isRelational && LCanPointeeTy->isFunctionType()) {
6736 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6737 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6738 }
6739 } else if (!isRelational &&
6740 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6741 // Valid unless comparison between non-null pointer and function pointer
6742 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6743 && !LHSIsNull && !RHSIsNull) {
6744 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6745 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6746 }
6747 } else {
6748 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006749 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00006750 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006751 }
Eli Friedman3075e762009-08-23 00:27:47 +00006752 if (LCanPointeeTy != RCanPointeeTy)
John McCall2de56d12010-08-25 11:45:40 +00006753 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006754 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00006755 }
Mike Stump1eb44332009-09-09 15:08:12 +00006756
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006757 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006758 // Comparison of nullptr_t with itself.
6759 if (lType->isNullPtrType() && rType->isNullPtrType())
6760 return ResultTy;
6761
Mike Stump1eb44332009-09-09 15:08:12 +00006762 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00006763 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00006764 if (RHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006765 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00006766 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregor443c2122010-08-07 13:36:37 +00006767 ImpCastExprToType(rex, lType,
6768 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006769 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006770 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006771 return ResultTy;
6772 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006773 if (LHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006774 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00006775 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregor443c2122010-08-07 13:36:37 +00006776 ImpCastExprToType(lex, rType,
6777 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006778 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006779 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006780 return ResultTy;
6781 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006782
6783 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00006784 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00006785 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6786 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006787 // In addition, pointers to members can be compared, or a pointer to
6788 // member and a null pointer constant. Pointer to member conversions
6789 // (4.11) and qualification conversions (4.4) are performed to bring
6790 // them to a common type. If one operand is a null pointer constant,
6791 // the common type is the type of the other operand. Otherwise, the
6792 // common type is a pointer to member type similar (4.4) to the type
6793 // of one of the operands, with a cv-qualification signature (4.4)
6794 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00006795 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006796 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006797 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006798 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00006799 if (T.isNull()) {
6800 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006801 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00006802 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006803 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006804 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006805 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006806 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006807 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00006808 }
Mike Stump1eb44332009-09-09 15:08:12 +00006809
John McCall2de56d12010-08-25 11:45:40 +00006810 ImpCastExprToType(lex, T, CK_BitCast);
6811 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00006812 return ResultTy;
6813 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006814 }
Mike Stump1eb44332009-09-09 15:08:12 +00006815
Steve Naroff1c7d0672008-09-04 15:10:53 +00006816 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00006817 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006818 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6819 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006820
Steve Naroff1c7d0672008-09-04 15:10:53 +00006821 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00006822 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006823 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00006824 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00006825 }
John McCall2de56d12010-08-25 11:45:40 +00006826 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006827 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006828 }
Steve Naroff59f53942008-09-28 01:11:11 +00006829 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00006830 if (!isRelational
6831 && ((lType->isBlockPointerType() && rType->isPointerType())
6832 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00006833 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006834 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006835 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00006836 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006837 ->getPointeeType()->isVoidType())))
6838 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6839 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00006840 }
John McCall2de56d12010-08-25 11:45:40 +00006841 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006842 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00006843 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00006844
Steve Naroff14108da2009-07-10 23:34:53 +00006845 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00006846 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006847 const PointerType *LPT = lType->getAs<PointerType>();
6848 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006849 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00006850 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006851 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00006852 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006853
Steve Naroffa8069f12008-11-17 19:49:16 +00006854 if (!LPtrToVoid && !RPtrToVoid &&
6855 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006856 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00006857 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00006858 }
John McCall2de56d12010-08-25 11:45:40 +00006859 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006860 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00006861 }
Steve Naroff14108da2009-07-10 23:34:53 +00006862 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006863 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00006864 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6865 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00006866 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006867 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00006868 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00006869 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006870 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6871 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006872 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006873 bool isError = false;
6874 if ((LHSIsNull && lType->isIntegerType()) ||
6875 (RHSIsNull && rType->isIntegerType())) {
6876 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006877 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006878 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006879 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006880 else if (getLangOptions().CPlusPlus) {
6881 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6882 isError = true;
6883 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006884 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00006885
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006886 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006887 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00006888 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006889 if (isError)
6890 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00006891 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006892
6893 if (lType->isIntegerType())
John McCall404cd162010-11-13 01:35:44 +00006894 ImpCastExprToType(lex, rType,
6895 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006896 else
John McCall404cd162010-11-13 01:35:44 +00006897 ImpCastExprToType(rex, lType,
6898 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006899 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006900 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006901
Steve Naroff39218df2008-09-04 16:56:14 +00006902 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00006903 if (!isRelational && RHSIsNull
6904 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCall404cd162010-11-13 01:35:44 +00006905 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006906 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006907 }
Mike Stumpaf199f32009-05-07 18:43:07 +00006908 if (!isRelational && LHSIsNull
6909 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCall404cd162010-11-13 01:35:44 +00006910 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006911 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006912 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006913 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006914}
6915
Nate Begemanbe2341d2008-07-14 18:02:46 +00006916/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00006917/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006918/// like a scalar comparison, a vector comparison produces a vector of integer
6919/// types.
6920QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006921 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006922 bool isRelational) {
6923 // Check to make sure we're operating on vectors of the same type and width,
6924 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006925 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00006926 if (vType.isNull())
6927 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006928
Anton Yartsevaa4fe052010-11-18 03:19:30 +00006929 // If AltiVec, the comparison results in a numeric type, i.e.
6930 // bool for C++, int for C
6931 if (getLangOptions().AltiVec)
6932 return (getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy);
6933
Nate Begemanbe2341d2008-07-14 18:02:46 +00006934 QualType lType = lex->getType();
6935 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006936
Nate Begemanbe2341d2008-07-14 18:02:46 +00006937 // For non-floating point types, check for self-comparisons of the form
6938 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6939 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006940 if (!lType->hasFloatingRepresentation()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006941 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
6942 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
6943 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregord64fdd02010-06-08 19:50:34 +00006944 DiagRuntimeBehavior(Loc,
6945 PDiag(diag::warn_comparison_always)
6946 << 0 // self-
6947 << 2 // "a constant"
6948 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00006949 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006950
Nate Begemanbe2341d2008-07-14 18:02:46 +00006951 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006952 if (!isRelational && lType->hasFloatingRepresentation()) {
6953 assert (rType->hasFloatingRepresentation());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006954 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00006955 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006956
Nate Begemanbe2341d2008-07-14 18:02:46 +00006957 // Return the type for the comparison, which is the same as vector type for
6958 // integer vectors, or an integer type of identical size and number of
6959 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00006960 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00006961 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006962
John McCall183700f2009-09-21 23:43:11 +00006963 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00006964 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00006965 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006966 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00006967 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00006968 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6969
Mike Stumpeed9cac2009-02-19 03:04:26 +00006970 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00006971 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00006972 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6973}
6974
Reid Spencer5f016e22007-07-11 17:01:13 +00006975inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00006976 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006977 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6978 if (lex->getType()->hasIntegerRepresentation() &&
6979 rex->getType()->hasIntegerRepresentation())
6980 return CheckVectorOperands(Loc, lex, rex);
6981
6982 return InvalidOperands(Loc, lex, rex);
6983 }
Steve Naroff90045e82007-07-13 23:32:42 +00006984
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006985 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006986
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006987 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
6988 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006989 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006990 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006991}
6992
6993inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner90a8f272010-07-13 19:41:32 +00006994 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
6995
6996 // Diagnose cases where the user write a logical and/or but probably meant a
6997 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6998 // is a constant.
6999 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman787b0942010-07-27 19:14:53 +00007000 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattner23ef3e42010-07-15 00:26:43 +00007001 // Don't warn in macros.
Chris Lattnerb7690b42010-07-24 01:10:11 +00007002 !Loc.isMacroID()) {
7003 // If the RHS can be constant folded, and if it constant folds to something
7004 // that isn't 0 or 1 (which indicate a potential logical operation that
7005 // happened to fold to true/false) then warn.
7006 Expr::EvalResult Result;
7007 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
7008 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7009 Diag(Loc, diag::warn_logical_instead_of_bitwise)
7010 << rex->getSourceRange()
John McCall2de56d12010-08-25 11:45:40 +00007011 << (Opc == BO_LAnd ? "&&" : "||")
7012 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattnerb7690b42010-07-24 01:10:11 +00007013 }
7014 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007015
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007016 if (!Context.getLangOptions().CPlusPlus) {
7017 UsualUnaryConversions(lex);
7018 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007019
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007020 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
7021 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007022
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007023 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007024 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007025
John McCall75f7c0f2010-06-04 00:29:51 +00007026 // The following is safe because we only use this method for
7027 // non-overloadable operands.
7028
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007029 // C++ [expr.log.and]p1
7030 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007031 // The operands are both contextually converted to type bool.
7032 if (PerformContextuallyConvertToBool(lex) ||
7033 PerformContextuallyConvertToBool(rex))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007034 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007035
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007036 // C++ [expr.log.and]p2
7037 // C++ [expr.log.or]p2
7038 // The result is a bool.
7039 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007040}
7041
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007042/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7043/// is a read-only property; return true if so. A readonly property expression
7044/// depends on various declarations and thus must be treated specially.
7045///
Mike Stump1eb44332009-09-09 15:08:12 +00007046static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007047 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7048 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00007049 if (PropExpr->isImplicitProperty()) return false;
7050
7051 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7052 QualType BaseType = PropExpr->isSuperReceiver() ?
7053 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007054 PropExpr->getBase()->getType();
7055
John McCall12f78a62010-12-02 01:19:52 +00007056 if (const ObjCObjectPointerType *OPT =
7057 BaseType->getAsObjCInterfacePointerType())
7058 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7059 if (S.isPropertyReadonly(PDecl, IFace))
7060 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007061 }
7062 return false;
7063}
7064
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007065/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7066/// emit an error and return true. If so, return false.
7067static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007068 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007069 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007070 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007071 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7072 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007073 if (IsLV == Expr::MLV_Valid)
7074 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007075
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007076 unsigned Diag = 0;
7077 bool NeedType = false;
7078 switch (IsLV) { // C99 6.5.16p2
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007079 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007080 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007081 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7082 NeedType = true;
7083 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007084 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007085 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7086 NeedType = true;
7087 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007088 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007089 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7090 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007091 case Expr::MLV_Valid:
7092 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007093 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007094 case Expr::MLV_MemberFunction:
7095 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007096 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7097 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007098 case Expr::MLV_IncompleteType:
7099 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007100 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007101 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00007102 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00007103 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007104 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7105 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00007106 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007107 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7108 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007109 case Expr::MLV_ReadonlyProperty:
7110 Diag = diag::error_readonly_property_assignment;
7111 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007112 case Expr::MLV_NoSetterProperty:
7113 Diag = diag::error_nosetter_property_assignment;
7114 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007115 case Expr::MLV_SubObjCPropertySetting:
7116 Diag = diag::error_no_subobject_property_setting;
7117 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007118 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007119
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007120 SourceRange Assign;
7121 if (Loc != OrigLoc)
7122 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007123 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007124 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007125 else
Mike Stump1eb44332009-09-09 15:08:12 +00007126 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007127 return true;
7128}
7129
7130
7131
7132// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007133QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
7134 SourceLocation Loc,
7135 QualType CompoundType) {
7136 // Verify that LHS is a modifiable lvalue, and emit error if not.
7137 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007138 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007139
7140 QualType LHSType = LHS->getType();
7141 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007142 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007143 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007144 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007145 // Simple assignment "x = y".
John McCallf6a16482010-12-04 03:47:34 +00007146 if (LHS->getObjectKind() == OK_ObjCProperty)
7147 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007148 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007149 // Special case of NSObject attributes on c-style pointer types.
7150 if (ConvTy == IncompatiblePointer &&
7151 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007152 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007153 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007154 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007155 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007156
John McCallf89e55a2010-11-18 06:31:45 +00007157 if (ConvTy == Compatible &&
7158 getLangOptions().ObjCNonFragileABI &&
7159 LHSType->isObjCObjectType())
7160 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7161 << LHSType;
7162
Chris Lattner2c156472008-08-21 18:04:13 +00007163 // If the RHS is a unary plus or minus, check to see if they = and + are
7164 // right next to each other. If so, the user may have typo'd "x =+ 4"
7165 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007166 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00007167 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7168 RHSCheck = ICE->getSubExpr();
7169 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007170 if ((UO->getOpcode() == UO_Plus ||
7171 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007172 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007173 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00007174 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7175 // And there is a space or other character before the subexpr of the
7176 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00007177 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7178 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007179 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007180 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007181 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007182 }
Chris Lattner2c156472008-08-21 18:04:13 +00007183 }
7184 } else {
7185 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007186 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007187 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007188
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007189 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00007190 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007191 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007192
Chris Lattner8b5dec32010-07-07 06:14:23 +00007193
7194 // Check to see if the destination operand is a dereferenced null pointer. If
7195 // so, and if not volatile-qualified, this is undefined behavior that the
7196 // optimizer will delete, so warn about it. People sometimes try to use this
7197 // to get a deterministic trap and are surprised by clang's behavior. This
7198 // only handles the pattern "*null = whatever", which is a very syntactic
7199 // check.
7200 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCall2de56d12010-08-25 11:45:40 +00007201 if (UO->getOpcode() == UO_Deref &&
Chris Lattner8b5dec32010-07-07 06:14:23 +00007202 UO->getSubExpr()->IgnoreParenCasts()->
7203 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7204 !UO->getType().isVolatileQualified()) {
7205 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
7206 << UO->getSubExpr()->getSourceRange();
7207 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
7208 }
7209
Reid Spencer5f016e22007-07-11 17:01:13 +00007210 // C99 6.5.16p3: The type of an assignment expression is the type of the
7211 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007212 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007213 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7214 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007215 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007216 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00007217 return (getLangOptions().CPlusPlus
7218 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007219}
7220
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007221// C99 6.5.17
John McCallf6a16482010-12-04 03:47:34 +00007222static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall09431682010-11-18 19:01:18 +00007223 SourceLocation Loc) {
7224 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00007225
John McCall09431682010-11-18 19:01:18 +00007226 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007227 if (LHSResult.isInvalid())
7228 return QualType();
7229
John McCall09431682010-11-18 19:01:18 +00007230 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007231 if (RHSResult.isInvalid())
7232 return QualType();
7233 RHS = RHSResult.take();
7234
John McCallcf2e5062010-10-12 07:14:40 +00007235 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7236 // operands, but not unary promotions.
7237 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007238
John McCallf6a16482010-12-04 03:47:34 +00007239 // So we treat the LHS as a ignored value, and in C++ we allow the
7240 // containing site to determine what should be done with the RHS.
7241 S.IgnoredValueConversions(LHS);
7242
7243 if (!S.getLangOptions().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007244 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCallcf2e5062010-10-12 07:14:40 +00007245 if (!RHS->getType()->isVoidType())
John McCall09431682010-11-18 19:01:18 +00007246 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007247 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007248
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007249 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007250}
7251
Steve Naroff49b45262007-07-13 16:58:59 +00007252/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7253/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007254static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7255 ExprValueKind &VK,
7256 SourceLocation OpLoc,
7257 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007258 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007259 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007260
Chris Lattner3528d352008-11-21 07:05:48 +00007261 QualType ResType = Op->getType();
7262 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007263
John McCall09431682010-11-18 19:01:18 +00007264 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007265 // Decrement of bool is not allowed.
7266 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00007267 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007268 return QualType();
7269 }
7270 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007271 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007272 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007273 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007274 } else if (ResType->isAnyPointerType()) {
7275 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00007276
Chris Lattner3528d352008-11-21 07:05:48 +00007277 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00007278 if (PointeeTy->isVoidType()) {
John McCall09431682010-11-18 19:01:18 +00007279 if (S.getLangOptions().CPlusPlus) {
7280 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00007281 << Op->getSourceRange();
7282 return QualType();
7283 }
7284
7285 // Pointer to void is a GNU extension in C.
John McCall09431682010-11-18 19:01:18 +00007286 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00007287 } else if (PointeeTy->isFunctionType()) {
John McCall09431682010-11-18 19:01:18 +00007288 if (S.getLangOptions().CPlusPlus) {
7289 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00007290 << Op->getType() << Op->getSourceRange();
7291 return QualType();
7292 }
7293
John McCall09431682010-11-18 19:01:18 +00007294 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00007295 << ResType << Op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007296 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7297 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00007298 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00007299 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007300 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007301 // Diagnose bad cases where we step over interface counts.
John McCall09431682010-11-18 19:01:18 +00007302 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7303 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007304 << PointeeTy << Op->getSourceRange();
7305 return QualType();
7306 }
Eli Friedman5b088a12010-01-03 00:20:48 +00007307 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007308 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007309 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007310 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007311 } else if (ResType->isPlaceholderType()) {
John McCall09431682010-11-18 19:01:18 +00007312 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007313 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007314 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7315 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00007316 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7317 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007318 } else {
John McCall09431682010-11-18 19:01:18 +00007319 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00007320 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007321 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007322 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007323 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007324 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007325 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007326 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007327 // In C++, a prefix increment is the same type as the operand. Otherwise
7328 // (in C or with postfix), the increment is the unqualified type of the
7329 // operand.
John McCall09431682010-11-18 19:01:18 +00007330 if (isPrefix && S.getLangOptions().CPlusPlus) {
7331 VK = VK_LValue;
7332 return ResType;
7333 } else {
7334 VK = VK_RValue;
7335 return ResType.getUnqualifiedType();
7336 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007337}
7338
John McCallf6a16482010-12-04 03:47:34 +00007339void Sema::ConvertPropertyForRValue(Expr *&E) {
7340 assert(E->getValueKind() == VK_LValue &&
7341 E->getObjectKind() == OK_ObjCProperty);
7342 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7343
7344 ExprValueKind VK = VK_RValue;
7345 if (PRE->isImplicitProperty()) {
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007346 if (const ObjCMethodDecl *GetterMethod =
7347 PRE->getImplicitPropertyGetter()) {
7348 QualType Result = GetterMethod->getResultType();
7349 VK = Expr::getValueKindForType(Result);
7350 }
7351 else {
7352 Diag(PRE->getLocation(), diag::err_getter_not_found)
7353 << PRE->getBase()->getType();
7354 }
John McCallf6a16482010-12-04 03:47:34 +00007355 }
7356
7357 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7358 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00007359
7360 ExprResult Result = MaybeBindToTemporary(E);
7361 if (!Result.isInvalid())
7362 E = Result.take();
John McCallf6a16482010-12-04 03:47:34 +00007363}
7364
7365void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7366 assert(LHS->getValueKind() == VK_LValue &&
7367 LHS->getObjectKind() == OK_ObjCProperty);
7368 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7369
7370 if (PRE->isImplicitProperty()) {
7371 // If using property-dot syntax notation for assignment, and there is a
7372 // setter, RHS expression is being passed to the setter argument. So,
7373 // type conversion (and comparison) is RHS to setter's argument type.
7374 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7375 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7376 LHSTy = (*P)->getType();
7377
7378 // Otherwise, if the getter returns an l-value, just call that.
7379 } else {
7380 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7381 ExprValueKind VK = Expr::getValueKindForType(Result);
7382 if (VK == VK_LValue) {
7383 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7384 CK_GetObjCProperty, LHS, 0, VK);
7385 return;
John McCall12f78a62010-12-02 01:19:52 +00007386 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007387 }
John McCallf6a16482010-12-04 03:47:34 +00007388 }
7389
7390 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007391 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007392 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007393 Expr *Arg = RHS;
7394 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7395 Owned(Arg));
7396 if (!ArgE.isInvalid())
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007397 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007398 }
7399}
7400
7401
Anders Carlsson369dee42008-02-01 07:15:58 +00007402/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007403/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007404/// where the declaration is needed for type checking. We only need to
7405/// handle cases when the expression references a function designator
7406/// or is an lvalue. Here are some examples:
7407/// - &(x) => x
7408/// - &*****f => f for f a function designator.
7409/// - &s.xx => s
7410/// - &s.zz[1].yy -> s, if zz is an array
7411/// - *(x + 1) -> x, if x is an array
7412/// - &"123"[2] -> 0
7413/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007414static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007415 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007416 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007417 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007418 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007419 // If this is an arrow operator, the address is an offset from
7420 // the base's value, so the object the base refers to is
7421 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007422 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007423 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007424 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007425 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007426 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007427 // FIXME: This code shouldn't be necessary! We should catch the implicit
7428 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007429 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7430 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7431 if (ICE->getSubExpr()->getType()->isArrayType())
7432 return getPrimaryDecl(ICE->getSubExpr());
7433 }
7434 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007435 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007436 case Stmt::UnaryOperatorClass: {
7437 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007438
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007439 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007440 case UO_Real:
7441 case UO_Imag:
7442 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007443 return getPrimaryDecl(UO->getSubExpr());
7444 default:
7445 return 0;
7446 }
7447 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007448 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007449 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007450 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007451 // If the result of an implicit cast is an l-value, we care about
7452 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007453 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007454 default:
7455 return 0;
7456 }
7457}
7458
7459/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007460/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007461/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007462/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007463/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007464/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007465/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00007466static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7467 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00007468 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007469 return S.Context.DependentTy;
7470 if (OrigOp->getType() == S.Context.OverloadTy)
7471 return S.Context.OverloadTy;
John McCall9c72c602010-08-27 09:08:28 +00007472
John McCall09431682010-11-18 19:01:18 +00007473 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007474 if (PR.isInvalid()) return QualType();
7475 OrigOp = PR.take();
7476
John McCall9c72c602010-08-27 09:08:28 +00007477 // Make sure to ignore parentheses in subsequent checks
7478 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007479
John McCall09431682010-11-18 19:01:18 +00007480 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007481 // Implement C99-only parts of addressof rules.
7482 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007483 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007484 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7485 // (assuming the deref expression is valid).
7486 return uOp->getSubExpr()->getType();
7487 }
7488 // Technically, there should be a check for array subscript
7489 // expressions here, but the result of one is always an lvalue anyway.
7490 }
John McCall5808ce42011-02-03 08:15:49 +00007491 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007492 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007493
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007494 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007495 bool sfinae = S.isSFINAEContext();
7496 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7497 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007498 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007499 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007500 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007501 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007502 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007503 } else if (lval == Expr::LV_MemberFunction) {
7504 // If it's an instance method, make a member pointer.
7505 // The expression must have exactly the form &A::foo.
7506
7507 // If the underlying expression isn't a decl ref, give up.
7508 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007509 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007510 << OrigOp->getSourceRange();
7511 return QualType();
7512 }
7513 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7514 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7515
7516 // The id-expression was parenthesized.
7517 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00007518 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007519 << OrigOp->getSourceRange();
7520
7521 // The method was named without a qualifier.
7522 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007523 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007524 << op->getSourceRange();
7525 }
7526
John McCall09431682010-11-18 19:01:18 +00007527 return S.Context.getMemberPointerType(op->getType(),
7528 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007529 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007530 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007531 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007532 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00007533 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00007534 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00007535 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007536 return QualType();
7537 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007538 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007539 // The operand cannot be a bit-field
John McCall09431682010-11-18 19:01:18 +00007540 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman23d58ce2009-04-20 08:23:18 +00007541 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00007542 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007543 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007544 // The operand cannot be an element of a vector
John McCall09431682010-11-18 19:01:18 +00007545 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00007546 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007547 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007548 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007549 // cannot take address of a property expression.
John McCall09431682010-11-18 19:01:18 +00007550 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007551 << "property expression" << op->getSourceRange();
7552 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007553 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007554 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007555 // with the register storage-class specifier.
7556 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007557 // in C++ it is not error to take address of a register
7558 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007559 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007560 !S.getLangOptions().CPlusPlus) {
7561 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007562 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007563 return QualType();
7564 }
John McCallba135432009-11-21 08:51:07 +00007565 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007566 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007567 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007568 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007569 // Could be a pointer to member, though, if there is an explicit
7570 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007571 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007572 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007573 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007574 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007575 S.Diag(OpLoc,
7576 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007577 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007578 return QualType();
7579 }
Mike Stump1eb44332009-09-09 15:08:12 +00007580
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007581 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7582 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007583 return S.Context.getMemberPointerType(op->getType(),
7584 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007585 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007586 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00007587 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00007588 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007589 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007590
Eli Friedman441cf102009-05-16 23:27:50 +00007591 if (lval == Expr::LV_IncompleteVoidType) {
7592 // Taking the address of a void variable is technically illegal, but we
7593 // allow it in cases which are otherwise valid.
7594 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007595 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007596 }
7597
Reid Spencer5f016e22007-07-11 17:01:13 +00007598 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007599 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007600 return S.Context.getObjCObjectPointerType(op->getType());
7601 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007602}
7603
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007604/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007605static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7606 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007607 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007608 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007609
John McCall09431682010-11-18 19:01:18 +00007610 S.UsualUnaryConversions(Op);
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007611 QualType OpTy = Op->getType();
7612 QualType Result;
7613
7614 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7615 // is an incomplete type or void. It would be possible to warn about
7616 // dereferencing a void pointer, but it's completely well-defined, and such a
7617 // warning is unlikely to catch any mistakes.
7618 if (const PointerType *PT = OpTy->getAs<PointerType>())
7619 Result = PT->getPointeeType();
7620 else if (const ObjCObjectPointerType *OPT =
7621 OpTy->getAs<ObjCObjectPointerType>())
7622 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007623 else {
John McCall09431682010-11-18 19:01:18 +00007624 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007625 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007626 if (PR.take() != Op)
7627 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007628 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007629
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007630 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007631 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007632 << OpTy << Op->getSourceRange();
7633 return QualType();
7634 }
John McCall09431682010-11-18 19:01:18 +00007635
7636 // Dereferences are usually l-values...
7637 VK = VK_LValue;
7638
7639 // ...except that certain expressions are never l-values in C.
7640 if (!S.getLangOptions().CPlusPlus &&
7641 IsCForbiddenLValueType(S.Context, Result))
7642 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007643
7644 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007645}
7646
John McCall2de56d12010-08-25 11:45:40 +00007647static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007648 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007649 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007650 switch (Kind) {
7651 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007652 case tok::periodstar: Opc = BO_PtrMemD; break;
7653 case tok::arrowstar: Opc = BO_PtrMemI; break;
7654 case tok::star: Opc = BO_Mul; break;
7655 case tok::slash: Opc = BO_Div; break;
7656 case tok::percent: Opc = BO_Rem; break;
7657 case tok::plus: Opc = BO_Add; break;
7658 case tok::minus: Opc = BO_Sub; break;
7659 case tok::lessless: Opc = BO_Shl; break;
7660 case tok::greatergreater: Opc = BO_Shr; break;
7661 case tok::lessequal: Opc = BO_LE; break;
7662 case tok::less: Opc = BO_LT; break;
7663 case tok::greaterequal: Opc = BO_GE; break;
7664 case tok::greater: Opc = BO_GT; break;
7665 case tok::exclaimequal: Opc = BO_NE; break;
7666 case tok::equalequal: Opc = BO_EQ; break;
7667 case tok::amp: Opc = BO_And; break;
7668 case tok::caret: Opc = BO_Xor; break;
7669 case tok::pipe: Opc = BO_Or; break;
7670 case tok::ampamp: Opc = BO_LAnd; break;
7671 case tok::pipepipe: Opc = BO_LOr; break;
7672 case tok::equal: Opc = BO_Assign; break;
7673 case tok::starequal: Opc = BO_MulAssign; break;
7674 case tok::slashequal: Opc = BO_DivAssign; break;
7675 case tok::percentequal: Opc = BO_RemAssign; break;
7676 case tok::plusequal: Opc = BO_AddAssign; break;
7677 case tok::minusequal: Opc = BO_SubAssign; break;
7678 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7679 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7680 case tok::ampequal: Opc = BO_AndAssign; break;
7681 case tok::caretequal: Opc = BO_XorAssign; break;
7682 case tok::pipeequal: Opc = BO_OrAssign; break;
7683 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007684 }
7685 return Opc;
7686}
7687
John McCall2de56d12010-08-25 11:45:40 +00007688static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007689 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007690 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007691 switch (Kind) {
7692 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007693 case tok::plusplus: Opc = UO_PreInc; break;
7694 case tok::minusminus: Opc = UO_PreDec; break;
7695 case tok::amp: Opc = UO_AddrOf; break;
7696 case tok::star: Opc = UO_Deref; break;
7697 case tok::plus: Opc = UO_Plus; break;
7698 case tok::minus: Opc = UO_Minus; break;
7699 case tok::tilde: Opc = UO_Not; break;
7700 case tok::exclaim: Opc = UO_LNot; break;
7701 case tok::kw___real: Opc = UO_Real; break;
7702 case tok::kw___imag: Opc = UO_Imag; break;
7703 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007704 }
7705 return Opc;
7706}
7707
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007708/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7709/// This warning is only emitted for builtin assignment operations. It is also
7710/// suppressed in the event of macro expansions.
7711static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7712 SourceLocation OpLoc) {
7713 if (!S.ActiveTemplateInstantiations.empty())
7714 return;
7715 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7716 return;
7717 lhs = lhs->IgnoreParenImpCasts();
7718 rhs = rhs->IgnoreParenImpCasts();
7719 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7720 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7721 if (!LeftDeclRef || !RightDeclRef ||
7722 LeftDeclRef->getLocation().isMacroID() ||
7723 RightDeclRef->getLocation().isMacroID())
7724 return;
7725 const ValueDecl *LeftDecl =
7726 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7727 const ValueDecl *RightDecl =
7728 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7729 if (LeftDecl != RightDecl)
7730 return;
7731 if (LeftDecl->getType().isVolatileQualified())
7732 return;
7733 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7734 if (RefTy->getPointeeType().isVolatileQualified())
7735 return;
7736
7737 S.Diag(OpLoc, diag::warn_self_assignment)
7738 << LeftDeclRef->getType()
7739 << lhs->getSourceRange() << rhs->getSourceRange();
7740}
7741
Douglas Gregoreaebc752008-11-06 23:29:22 +00007742/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7743/// operator @p Opc at location @c TokLoc. This routine only supports
7744/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00007745ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007746 BinaryOperatorKind Opc,
John McCall2de56d12010-08-25 11:45:40 +00007747 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00007748 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00007749 // The following two variables are used for compound assignment operators
7750 QualType CompLHSTy; // Type of LHS after promotions for computation
7751 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00007752 ExprValueKind VK = VK_RValue;
7753 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00007754
7755 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007756 case BO_Assign:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007757 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00007758 if (getLangOptions().CPlusPlus &&
7759 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall09431682010-11-18 19:01:18 +00007760 VK = lhs->getValueKind();
7761 OK = lhs->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007762 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007763 if (!ResultTy.isNull())
7764 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007765 break;
John McCall2de56d12010-08-25 11:45:40 +00007766 case BO_PtrMemD:
7767 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00007768 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007769 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00007770 break;
John McCall2de56d12010-08-25 11:45:40 +00007771 case BO_Mul:
7772 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007773 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00007774 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007775 break;
John McCall2de56d12010-08-25 11:45:40 +00007776 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007777 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7778 break;
John McCall2de56d12010-08-25 11:45:40 +00007779 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007780 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7781 break;
John McCall2de56d12010-08-25 11:45:40 +00007782 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007783 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7784 break;
John McCall2de56d12010-08-25 11:45:40 +00007785 case BO_Shl:
7786 case BO_Shr:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007787 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
7788 break;
John McCall2de56d12010-08-25 11:45:40 +00007789 case BO_LE:
7790 case BO_LT:
7791 case BO_GE:
7792 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00007793 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007794 break;
John McCall2de56d12010-08-25 11:45:40 +00007795 case BO_EQ:
7796 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00007797 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007798 break;
John McCall2de56d12010-08-25 11:45:40 +00007799 case BO_And:
7800 case BO_Xor:
7801 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007802 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7803 break;
John McCall2de56d12010-08-25 11:45:40 +00007804 case BO_LAnd:
7805 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00007806 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007807 break;
John McCall2de56d12010-08-25 11:45:40 +00007808 case BO_MulAssign:
7809 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007810 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00007811 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007812 CompLHSTy = CompResultTy;
7813 if (!CompResultTy.isNull())
7814 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007815 break;
John McCall2de56d12010-08-25 11:45:40 +00007816 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007817 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7818 CompLHSTy = CompResultTy;
7819 if (!CompResultTy.isNull())
7820 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007821 break;
John McCall2de56d12010-08-25 11:45:40 +00007822 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007823 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7824 if (!CompResultTy.isNull())
7825 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007826 break;
John McCall2de56d12010-08-25 11:45:40 +00007827 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007828 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7829 if (!CompResultTy.isNull())
7830 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007831 break;
John McCall2de56d12010-08-25 11:45:40 +00007832 case BO_ShlAssign:
7833 case BO_ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007834 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
7835 CompLHSTy = CompResultTy;
7836 if (!CompResultTy.isNull())
7837 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007838 break;
John McCall2de56d12010-08-25 11:45:40 +00007839 case BO_AndAssign:
7840 case BO_XorAssign:
7841 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007842 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7843 CompLHSTy = CompResultTy;
7844 if (!CompResultTy.isNull())
7845 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007846 break;
John McCall2de56d12010-08-25 11:45:40 +00007847 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00007848 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCallf89e55a2010-11-18 06:31:45 +00007849 if (getLangOptions().CPlusPlus) {
7850 VK = rhs->getValueKind();
7851 OK = rhs->getObjectKind();
7852 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00007853 break;
7854 }
7855 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007856 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00007857 if (CompResultTy.isNull())
John McCallf89e55a2010-11-18 06:31:45 +00007858 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
7859 VK, OK, OpLoc));
7860
John McCallf6a16482010-12-04 03:47:34 +00007861 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00007862 VK = VK_LValue;
7863 OK = lhs->getObjectKind();
7864 }
7865 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
7866 VK, OK, CompLHSTy,
7867 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00007868}
7869
Sebastian Redlaee3c932009-10-27 12:10:02 +00007870/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
7871/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007872static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7873 const PartialDiagnostic &PD,
Douglas Gregor55b38842010-04-14 16:09:52 +00007874 const PartialDiagnostic &FirstNote,
7875 SourceRange FirstParenRange,
7876 const PartialDiagnostic &SecondNote,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007877 SourceRange SecondParenRange) {
Douglas Gregor55b38842010-04-14 16:09:52 +00007878 Self.Diag(Loc, PD);
7879
7880 if (!FirstNote.getDiagID())
7881 return;
7882
7883 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
7884 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7885 // We can't display the parentheses, so just return.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007886 return;
7887 }
7888
Douglas Gregor55b38842010-04-14 16:09:52 +00007889 Self.Diag(Loc, FirstNote)
7890 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregor849b2432010-03-31 17:46:05 +00007891 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007892
Douglas Gregor55b38842010-04-14 16:09:52 +00007893 if (!SecondNote.getDiagID())
Douglas Gregor827feec2010-01-08 00:20:23 +00007894 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007895
Douglas Gregor827feec2010-01-08 00:20:23 +00007896 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
7897 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7898 // We can't display the parentheses, so just dig the
7899 // warning/error and return.
Douglas Gregor55b38842010-04-14 16:09:52 +00007900 Self.Diag(Loc, SecondNote);
Douglas Gregor827feec2010-01-08 00:20:23 +00007901 return;
7902 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007903
Douglas Gregor55b38842010-04-14 16:09:52 +00007904 Self.Diag(Loc, SecondNote)
Douglas Gregor849b2432010-03-31 17:46:05 +00007905 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
7906 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007907}
7908
Sebastian Redlaee3c932009-10-27 12:10:02 +00007909/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7910/// operators are mixed in a way that suggests that the programmer forgot that
7911/// comparison operators have higher precedence. The most typical example of
7912/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00007913static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007914 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00007915 typedef BinaryOperator BinOp;
7916 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7917 rhsopc = static_cast<BinOp::Opcode>(-1);
7918 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007919 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00007920 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007921 rhsopc = BO->getOpcode();
7922
7923 // Subs are not binary operators.
7924 if (lhsopc == -1 && rhsopc == -1)
7925 return;
7926
7927 // Bitwise operations are sometimes used as eager logical ops.
7928 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00007929 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7930 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007931 return;
7932
Sebastian Redlaee3c932009-10-27 12:10:02 +00007933 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007934 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007935 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00007936 << SourceRange(lhs->getLocStart(), OpLoc)
7937 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007938 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00007939 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00007940 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
7941 Self.PDiag(diag::note_precedence_bitwise_silence)
7942 << BinOp::getOpcodeStr(lhsopc),
7943 lhs->getSourceRange());
Sebastian Redlaee3c932009-10-27 12:10:02 +00007944 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007945 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007946 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00007947 << SourceRange(OpLoc, rhs->getLocEnd())
7948 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007949 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00007950 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00007951 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
7952 Self.PDiag(diag::note_precedence_bitwise_silence)
7953 << BinOp::getOpcodeStr(rhsopc),
7954 rhs->getSourceRange());
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007955}
7956
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007957/// \brief It accepts a '&&' expr that is inside a '||' one.
7958/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7959/// in parentheses.
7960static void
7961EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
7962 Expr *E) {
7963 assert(isa<BinaryOperator>(E) &&
7964 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
7965 SuggestParentheses(Self, OpLoc,
7966 Self.PDiag(diag::warn_logical_and_in_logical_or)
7967 << E->getSourceRange(),
7968 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
7969 E->getSourceRange(),
7970 Self.PDiag(0), SourceRange());
7971}
7972
7973/// \brief Returns true if the given expression can be evaluated as a constant
7974/// 'true'.
7975static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7976 bool Res;
7977 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7978}
7979
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007980/// \brief Returns true if the given expression can be evaluated as a constant
7981/// 'false'.
7982static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7983 bool Res;
7984 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7985}
7986
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007987/// \brief Look for '&&' in the left hand of a '||' expr.
7988static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007989 Expr *OrLHS, Expr *OrRHS) {
7990 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007991 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007992 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7993 if (EvaluatesAsFalse(S, OrRHS))
7994 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007995 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7996 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7997 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7998 } else if (Bop->getOpcode() == BO_LOr) {
7999 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8000 // If it's "a || b && 1 || c" we didn't warn earlier for
8001 // "a || b && 1", but warn now.
8002 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8003 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8004 }
8005 }
8006 }
8007}
8008
8009/// \brief Look for '&&' in the right hand of a '||' expr.
8010static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008011 Expr *OrLHS, Expr *OrRHS) {
8012 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008013 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008014 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8015 if (EvaluatesAsFalse(S, OrLHS))
8016 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008017 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8018 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8019 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008020 }
8021 }
8022}
8023
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008024/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008025/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008026static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008027 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008028 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008029 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008030 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8031
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008032 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8033 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008034 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008035 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8036 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008037 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008038}
8039
Reid Spencer5f016e22007-07-11 17:01:13 +00008040// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008041ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008042 tok::TokenKind Kind,
8043 Expr *lhs, Expr *rhs) {
8044 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00008045 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8046 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008047
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008048 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8049 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8050
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008051 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8052}
8053
John McCall60d7b3a2010-08-24 06:29:42 +00008054ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008055 BinaryOperatorKind Opc,
8056 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00008057 if (getLangOptions().CPlusPlus) {
8058 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008059
John McCall01b2e4e2010-12-06 05:26:58 +00008060 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8061 UseBuiltinOperator = false;
8062 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8063 UseBuiltinOperator = true;
8064 } else {
8065 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8066 !rhs->getType()->isOverloadableType();
8067 }
8068
8069 if (!UseBuiltinOperator) {
8070 // Find all of the overloaded operators visible from this
8071 // point. We perform both an operator-name lookup from the local
8072 // scope and an argument-dependent lookup based on the types of
8073 // the arguments.
8074 UnresolvedSet<16> Functions;
8075 OverloadedOperatorKind OverOp
8076 = BinaryOperator::getOverloadedOperator(Opc);
8077 if (S && OverOp != OO_None)
8078 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8079 Functions);
8080
8081 // Build the (potentially-overloaded, potentially-dependent)
8082 // binary operation.
8083 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8084 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008085 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008086
Douglas Gregoreaebc752008-11-06 23:29:22 +00008087 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008088 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00008089}
8090
John McCall60d7b3a2010-08-24 06:29:42 +00008091ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008092 UnaryOperatorKind Opc,
John McCall2cd11fe2010-10-12 02:09:17 +00008093 Expr *Input) {
John McCallf89e55a2010-11-18 06:31:45 +00008094 ExprValueKind VK = VK_RValue;
8095 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008096 QualType resultType;
8097 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008098 case UO_PreInc:
8099 case UO_PreDec:
8100 case UO_PostInc:
8101 case UO_PostDec:
John McCall09431682010-11-18 19:01:18 +00008102 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008103 Opc == UO_PreInc ||
8104 Opc == UO_PostInc,
8105 Opc == UO_PreInc ||
8106 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008107 break;
John McCall2de56d12010-08-25 11:45:40 +00008108 case UO_AddrOf:
John McCall09431682010-11-18 19:01:18 +00008109 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008110 break;
John McCall2de56d12010-08-25 11:45:40 +00008111 case UO_Deref:
Douglas Gregora873dfc2010-02-03 00:27:59 +00008112 DefaultFunctionArrayLvalueConversion(Input);
John McCall09431682010-11-18 19:01:18 +00008113 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008114 break;
John McCall2de56d12010-08-25 11:45:40 +00008115 case UO_Plus:
8116 case UO_Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00008117 UsualUnaryConversions(Input);
8118 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008119 if (resultType->isDependentType())
8120 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008121 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8122 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008123 break;
8124 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8125 resultType->isEnumeralType())
8126 break;
8127 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008128 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008129 resultType->isPointerType())
8130 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008131 else if (resultType->isPlaceholderType()) {
8132 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8133 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008134 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008135 }
Douglas Gregor74253732008-11-19 15:42:04 +00008136
Sebastian Redl0eb23302009-01-19 00:08:26 +00008137 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8138 << resultType << Input->getSourceRange());
John McCall2de56d12010-08-25 11:45:40 +00008139 case UO_Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00008140 UsualUnaryConversions(Input);
8141 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008142 if (resultType->isDependentType())
8143 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008144 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8145 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8146 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008147 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00008148 << resultType << Input->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008149 else if (resultType->hasIntegerRepresentation())
8150 break;
8151 else if (resultType->isPlaceholderType()) {
8152 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8153 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008154 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008155 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008156 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8157 << resultType << Input->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008158 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008159 break;
John McCall2de56d12010-08-25 11:45:40 +00008160 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008161 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregora873dfc2010-02-03 00:27:59 +00008162 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00008163 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008164 if (resultType->isDependentType())
8165 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008166 if (resultType->isScalarType()) { // C99 6.5.3.3p1
8167 // ok, fallthrough
8168 } else if (resultType->isPlaceholderType()) {
8169 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8170 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008171 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008172 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008173 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8174 << resultType << Input->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008175 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008176
Reid Spencer5f016e22007-07-11 17:01:13 +00008177 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008178 // In C++, it's bool. C++ 5.3.1p8
8179 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00008180 break;
John McCall2de56d12010-08-25 11:45:40 +00008181 case UO_Real:
8182 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008183 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008184 // _Real and _Imag map ordinary l-values into ordinary l-values.
8185 if (Input->getValueKind() != VK_RValue &&
8186 Input->getObjectKind() == OK_Ordinary)
8187 VK = Input->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00008188 break;
John McCall2de56d12010-08-25 11:45:40 +00008189 case UO_Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00008190 resultType = Input->getType();
John McCallf89e55a2010-11-18 06:31:45 +00008191 VK = Input->getValueKind();
8192 OK = Input->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008193 break;
8194 }
8195 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008196 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008197
John McCallf89e55a2010-11-18 06:31:45 +00008198 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
8199 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008200}
8201
John McCall60d7b3a2010-08-24 06:29:42 +00008202ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008203 UnaryOperatorKind Opc,
8204 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00008205 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00008206 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008207 // Find all of the overloaded operators visible from this
8208 // point. We perform both an operator-name lookup from the local
8209 // scope and an argument-dependent lookup based on the types of
8210 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008211 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008212 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008213 if (S && OverOp != OO_None)
8214 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8215 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008216
John McCall9ae2f072010-08-23 23:25:46 +00008217 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008218 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008219
John McCall9ae2f072010-08-23 23:25:46 +00008220 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008221}
8222
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008223// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008224ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008225 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008226 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008227}
8228
Steve Naroff1b273c42007-09-16 14:56:35 +00008229/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
John McCall60d7b3a2010-08-24 06:29:42 +00008230ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008231 SourceLocation LabLoc,
8232 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00008233 // Look up the record for this label identifier.
John McCall781472f2010-08-25 08:40:02 +00008234 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00008235
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00008236 // If we haven't seen this label yet, create a forward reference. It
8237 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00008238 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00008239 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008240
Argyrios Kyrtzidis355a9fe2010-09-19 21:21:25 +00008241 LabelDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008242 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00008243 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
8244 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008245}
8246
John McCall60d7b3a2010-08-24 06:29:42 +00008247ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008248Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008249 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008250 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8251 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8252
Douglas Gregordd8f5692010-03-10 04:54:39 +00008253 bool isFileScope
8254 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008255 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008256 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008257
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008258 // FIXME: there are a variety of strange constraints to enforce here, for
8259 // example, it is not possible to goto into a stmt expression apparently.
8260 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008261
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008262 // If there are sub stmts in the compound stmt, take the type of the last one
8263 // as the type of the stmtexpr.
8264 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008265 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008266 if (!Compound->body_empty()) {
8267 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008268 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008269 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008270 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8271 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008272 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008273 }
8274 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008275 // Do function/array conversion on the last expression, but not
8276 // lvalue-to-rvalue. However, initialize an unqualified type.
8277 DefaultFunctionArrayConversion(LastExpr);
8278 Ty = LastExpr->getType().getUnqualifiedType();
8279
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008280 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8281 ExprResult Res = PerformCopyInitialization(
8282 InitializedEntity::InitializeResult(LPLoc,
8283 Ty,
8284 false),
8285 SourceLocation(),
8286 Owned(LastExpr));
8287 if (Res.isInvalid())
8288 return ExprError();
8289 if ((LastExpr = Res.takeAs<Expr>())) {
8290 if (!LastLabelStmt)
8291 Compound->setLastStmt(LastExpr);
8292 else
8293 LastLabelStmt->setSubStmt(LastExpr);
8294 StmtExprMayBindToTemp = true;
8295 }
8296 }
8297 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008298 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008299
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008300 // FIXME: Check that expression type is complete/non-abstract; statement
8301 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008302 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8303 if (StmtExprMayBindToTemp)
8304 return MaybeBindToTemporary(ResStmtExpr);
8305 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008306}
Steve Naroffd34e9152007-08-01 22:05:33 +00008307
John McCall60d7b3a2010-08-24 06:29:42 +00008308ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008309 TypeSourceInfo *TInfo,
8310 OffsetOfComponent *CompPtr,
8311 unsigned NumComponents,
8312 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008313 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008314 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008315 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008316
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008317 // We must have at least one component that refers to the type, and the first
8318 // one is known to be a field designator. Verify that the ArgTy represents
8319 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008320 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008321 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8322 << ArgTy << TypeRange);
8323
8324 // Type must be complete per C99 7.17p3 because a declaring a variable
8325 // with an incomplete type would be ill-formed.
8326 if (!Dependent
8327 && RequireCompleteType(BuiltinLoc, ArgTy,
8328 PDiag(diag::err_offsetof_incomplete_type)
8329 << TypeRange))
8330 return ExprError();
8331
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008332 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8333 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008334 // FIXME: This diagnostic isn't actually visible because the location is in
8335 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008336 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008337 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8338 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008339
8340 bool DidWarnAboutNonPOD = false;
8341 QualType CurrentType = ArgTy;
8342 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8343 llvm::SmallVector<OffsetOfNode, 4> Comps;
8344 llvm::SmallVector<Expr*, 4> Exprs;
8345 for (unsigned i = 0; i != NumComponents; ++i) {
8346 const OffsetOfComponent &OC = CompPtr[i];
8347 if (OC.isBrackets) {
8348 // Offset of an array sub-field. TODO: Should we allow vector elements?
8349 if (!CurrentType->isDependentType()) {
8350 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8351 if(!AT)
8352 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8353 << CurrentType);
8354 CurrentType = AT->getElementType();
8355 } else
8356 CurrentType = Context.DependentTy;
8357
8358 // The expression must be an integral expression.
8359 // FIXME: An integral constant expression?
8360 Expr *Idx = static_cast<Expr*>(OC.U.E);
8361 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8362 !Idx->getType()->isIntegerType())
8363 return ExprError(Diag(Idx->getLocStart(),
8364 diag::err_typecheck_subscript_not_integer)
8365 << Idx->getSourceRange());
8366
8367 // Record this array index.
8368 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8369 Exprs.push_back(Idx);
8370 continue;
8371 }
8372
8373 // Offset of a field.
8374 if (CurrentType->isDependentType()) {
8375 // We have the offset of a field, but we can't look into the dependent
8376 // type. Just record the identifier of the field.
8377 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8378 CurrentType = Context.DependentTy;
8379 continue;
8380 }
8381
8382 // We need to have a complete type to look into.
8383 if (RequireCompleteType(OC.LocStart, CurrentType,
8384 diag::err_offsetof_incomplete_type))
8385 return ExprError();
8386
8387 // Look for the designated field.
8388 const RecordType *RC = CurrentType->getAs<RecordType>();
8389 if (!RC)
8390 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8391 << CurrentType);
8392 RecordDecl *RD = RC->getDecl();
8393
8394 // C++ [lib.support.types]p5:
8395 // The macro offsetof accepts a restricted set of type arguments in this
8396 // International Standard. type shall be a POD structure or a POD union
8397 // (clause 9).
8398 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8399 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8400 DiagRuntimeBehavior(BuiltinLoc,
8401 PDiag(diag::warn_offsetof_non_pod_type)
8402 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8403 << CurrentType))
8404 DidWarnAboutNonPOD = true;
8405 }
8406
8407 // Look for the field.
8408 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8409 LookupQualifiedName(R, RD);
8410 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008411 IndirectFieldDecl *IndirectMemberDecl = 0;
8412 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008413 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008414 MemberDecl = IndirectMemberDecl->getAnonField();
8415 }
8416
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008417 if (!MemberDecl)
8418 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8419 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8420 OC.LocEnd));
8421
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008422 // C99 7.17p3:
8423 // (If the specified member is a bit-field, the behavior is undefined.)
8424 //
8425 // We diagnose this as an error.
8426 if (MemberDecl->getBitWidth()) {
8427 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8428 << MemberDecl->getDeclName()
8429 << SourceRange(BuiltinLoc, RParenLoc);
8430 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8431 return ExprError();
8432 }
Eli Friedman19410a72010-08-05 10:11:36 +00008433
8434 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008435 if (IndirectMemberDecl)
8436 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008437
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008438 // If the member was found in a base class, introduce OffsetOfNodes for
8439 // the base class indirections.
8440 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8441 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008442 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008443 CXXBasePath &Path = Paths.front();
8444 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8445 B != BEnd; ++B)
8446 Comps.push_back(OffsetOfNode(B->Base));
8447 }
Eli Friedman19410a72010-08-05 10:11:36 +00008448
Francois Pichet87c2e122010-11-21 06:08:52 +00008449 if (IndirectMemberDecl) {
8450 for (IndirectFieldDecl::chain_iterator FI =
8451 IndirectMemberDecl->chain_begin(),
8452 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8453 assert(isa<FieldDecl>(*FI));
8454 Comps.push_back(OffsetOfNode(OC.LocStart,
8455 cast<FieldDecl>(*FI), OC.LocEnd));
8456 }
8457 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008458 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008459
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008460 CurrentType = MemberDecl->getType().getNonReferenceType();
8461 }
8462
8463 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8464 TInfo, Comps.data(), Comps.size(),
8465 Exprs.data(), Exprs.size(), RParenLoc));
8466}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008467
John McCall60d7b3a2010-08-24 06:29:42 +00008468ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008469 SourceLocation BuiltinLoc,
8470 SourceLocation TypeLoc,
8471 ParsedType argty,
8472 OffsetOfComponent *CompPtr,
8473 unsigned NumComponents,
8474 SourceLocation RPLoc) {
8475
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008476 TypeSourceInfo *ArgTInfo;
8477 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8478 if (ArgTy.isNull())
8479 return ExprError();
8480
Eli Friedman5a15dc12010-08-05 10:15:45 +00008481 if (!ArgTInfo)
8482 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8483
8484 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8485 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008486}
8487
8488
John McCall60d7b3a2010-08-24 06:29:42 +00008489ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008490 Expr *CondExpr,
8491 Expr *LHSExpr, Expr *RHSExpr,
8492 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008493 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8494
John McCallf89e55a2010-11-18 06:31:45 +00008495 ExprValueKind VK = VK_RValue;
8496 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008497 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008498 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008499 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008500 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008501 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008502 } else {
8503 // The conditional expression is required to be a constant expression.
8504 llvm::APSInt condEval(32);
8505 SourceLocation ExpLoc;
8506 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008507 return ExprError(Diag(ExpLoc,
8508 diag::err_typecheck_choose_expr_requires_constant)
8509 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008510
Sebastian Redl28507842009-02-26 14:39:58 +00008511 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008512 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8513
8514 resType = ActiveExpr->getType();
8515 ValueDependent = ActiveExpr->isValueDependent();
8516 VK = ActiveExpr->getValueKind();
8517 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008518 }
8519
Sebastian Redlf53597f2009-03-15 17:47:39 +00008520 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008521 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008522 resType->isDependentType(),
8523 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008524}
8525
Steve Naroff4eb206b2008-09-03 18:15:37 +00008526//===----------------------------------------------------------------------===//
8527// Clang Extensions.
8528//===----------------------------------------------------------------------===//
8529
8530/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00008531void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008532 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8533 PushBlockScope(BlockScope, Block);
8534 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008535 if (BlockScope)
8536 PushDeclContext(BlockScope, Block);
8537 else
8538 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00008539}
8540
Mike Stump98eb8a72009-02-04 22:31:32 +00008541void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008542 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008543 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008544 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008545
John McCallbf1a0282010-06-04 23:28:52 +00008546 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008547 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008548
John McCall711c52b2011-01-05 12:14:39 +00008549 // GetTypeForDeclarator always produces a function type for a block
8550 // literal signature. Furthermore, it is always a FunctionProtoType
8551 // unless the function was written with a typedef.
8552 assert(T->isFunctionType() &&
8553 "GetTypeForDeclarator made a non-function block signature");
8554
8555 // Look for an explicit signature in that function type.
8556 FunctionProtoTypeLoc ExplicitSignature;
8557
8558 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8559 if (isa<FunctionProtoTypeLoc>(tmp)) {
8560 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8561
8562 // Check whether that explicit signature was synthesized by
8563 // GetTypeForDeclarator. If so, don't save that as part of the
8564 // written signature.
8565 if (ExplicitSignature.getLParenLoc() ==
8566 ExplicitSignature.getRParenLoc()) {
8567 // This would be much cheaper if we stored TypeLocs instead of
8568 // TypeSourceInfos.
8569 TypeLoc Result = ExplicitSignature.getResultLoc();
8570 unsigned Size = Result.getFullDataSize();
8571 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8572 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8573
8574 ExplicitSignature = FunctionProtoTypeLoc();
8575 }
John McCall82dc0092010-06-04 11:21:44 +00008576 }
Mike Stump1eb44332009-09-09 15:08:12 +00008577
John McCall711c52b2011-01-05 12:14:39 +00008578 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8579 CurBlock->FunctionType = T;
8580
8581 const FunctionType *Fn = T->getAs<FunctionType>();
8582 QualType RetTy = Fn->getResultType();
8583 bool isVariadic =
8584 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8585
John McCallc71a4912010-06-04 19:02:56 +00008586 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008587
John McCall82dc0092010-06-04 11:21:44 +00008588 // Don't allow returning a objc interface by value.
8589 if (RetTy->isObjCObjectType()) {
8590 Diag(ParamInfo.getSourceRange().getBegin(),
8591 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8592 return;
8593 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008594
John McCall82dc0092010-06-04 11:21:44 +00008595 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008596 // return type. TODO: what should we do with declarators like:
8597 // ^ * { ... }
8598 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00008599 if (RetTy != Context.DependentTy)
8600 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008601
John McCall82dc0092010-06-04 11:21:44 +00008602 // Push block parameters from the declarator if we had them.
John McCallc71a4912010-06-04 19:02:56 +00008603 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008604 if (ExplicitSignature) {
8605 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8606 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008607 if (Param->getIdentifier() == 0 &&
8608 !Param->isImplicit() &&
8609 !Param->isInvalidDecl() &&
8610 !getLangOptions().CPlusPlus)
8611 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008612 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008613 }
John McCall82dc0092010-06-04 11:21:44 +00008614
8615 // Fake up parameter variables if we have a typedef, like
8616 // ^ fntype { ... }
8617 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8618 for (FunctionProtoType::arg_type_iterator
8619 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8620 ParmVarDecl *Param =
8621 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8622 ParamInfo.getSourceRange().getBegin(),
8623 *I);
John McCallc71a4912010-06-04 19:02:56 +00008624 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008625 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008626 }
John McCall82dc0092010-06-04 11:21:44 +00008627
John McCallc71a4912010-06-04 19:02:56 +00008628 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008629 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00008630 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00008631 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8632 CurBlock->TheDecl->param_end(),
8633 /*CheckParameterNames=*/false);
8634 }
8635
John McCall82dc0092010-06-04 11:21:44 +00008636 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008637 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008638
John McCallc71a4912010-06-04 19:02:56 +00008639 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008640 Diag(ParamInfo.getAttributes()->getLoc(),
8641 diag::warn_attribute_sentinel_not_variadic) << 1;
8642 // FIXME: remove the attribute.
8643 }
8644
8645 // Put the parameter variables in scope. We can bail out immediately
8646 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008647 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008648 return;
8649
Steve Naroff090276f2008-10-10 01:28:17 +00008650 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008651 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8652 (*AI)->setOwningFunction(CurBlock->TheDecl);
8653
Steve Naroff090276f2008-10-10 01:28:17 +00008654 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008655 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008656 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008657
Steve Naroff090276f2008-10-10 01:28:17 +00008658 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008659 }
John McCall7a9813c2010-01-22 00:28:27 +00008660 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008661}
8662
8663/// ActOnBlockError - If there is an error parsing a block, this callback
8664/// is invoked to pop the information about the block from the action impl.
8665void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00008666 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008667 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008668 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008669}
8670
8671/// ActOnBlockStmtExpr - This is called when the body of a block statement
8672/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008673ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
John McCall9ae2f072010-08-23 23:25:46 +00008674 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008675 // If blocks are disabled, emit an error.
8676 if (!LangOpts.Blocks)
8677 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008678
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008679 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008680
Steve Naroff090276f2008-10-10 01:28:17 +00008681 PopDeclContext();
8682
Steve Naroff4eb206b2008-09-03 18:15:37 +00008683 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008684 if (!BSI->ReturnType.isNull())
8685 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008686
Mike Stump56925862009-07-28 22:04:01 +00008687 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008688 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008689
John McCall469a1eb2011-02-02 13:00:07 +00008690 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00008691 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8692 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00008693
John McCallc71a4912010-06-04 19:02:56 +00008694 // If the user wrote a function type in some form, try to use that.
8695 if (!BSI->FunctionType.isNull()) {
8696 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8697
8698 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8699 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8700
8701 // Turn protoless block types into nullary block types.
8702 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00008703 FunctionProtoType::ExtProtoInfo EPI;
8704 EPI.ExtInfo = Ext;
8705 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008706
8707 // Otherwise, if we don't need to change anything about the function type,
8708 // preserve its sugar structure.
8709 } else if (FTy->getResultType() == RetTy &&
8710 (!NoReturn || FTy->getNoReturnAttr())) {
8711 BlockTy = BSI->FunctionType;
8712
8713 // Otherwise, make the minimal modifications to the function type.
8714 } else {
8715 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00008716 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8717 EPI.TypeQuals = 0; // FIXME: silently?
8718 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00008719 BlockTy = Context.getFunctionType(RetTy,
8720 FPT->arg_type_begin(),
8721 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00008722 EPI);
John McCallc71a4912010-06-04 19:02:56 +00008723 }
8724
8725 // If we don't have a function type, just build one from nothing.
8726 } else {
John McCalle23cf432010-12-14 08:05:40 +00008727 FunctionProtoType::ExtProtoInfo EPI;
8728 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
8729 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008730 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008731
John McCallc71a4912010-06-04 19:02:56 +00008732 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8733 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00008734 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008735
Chris Lattner17a78302009-04-19 05:28:12 +00008736 // If needed, diagnose invalid gotos and switches in the block.
John McCall781472f2010-08-25 08:40:02 +00008737 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00008738 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00008739
John McCall9ae2f072010-08-23 23:25:46 +00008740 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Mike Stumpa3899eb2010-01-19 23:08:01 +00008741
8742 bool Good = true;
8743 // Check goto/label use.
8744 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
8745 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
8746 LabelStmt *L = I->second;
8747
8748 // Verify that we have no forward references left. If so, there was a goto
8749 // or address of a label taken, but no definition of it.
Argyrios Kyrtzidis355a9fe2010-09-19 21:21:25 +00008750 if (L->getSubStmt() != 0) {
8751 if (!L->isUsed())
8752 Diag(L->getIdentLoc(), diag::warn_unused_label) << L->getName();
Mike Stumpa3899eb2010-01-19 23:08:01 +00008753 continue;
Argyrios Kyrtzidis355a9fe2010-09-19 21:21:25 +00008754 }
Mike Stumpa3899eb2010-01-19 23:08:01 +00008755
8756 // Emit error.
8757 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
8758 Good = false;
8759 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008760 if (!Good) {
8761 PopFunctionOrBlockScope();
Mike Stumpa3899eb2010-01-19 23:08:01 +00008762 return ExprError();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008763 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008764
John McCall469a1eb2011-02-02 13:00:07 +00008765 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCalle0054f62010-08-25 05:56:39 +00008766
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00008767 // Issue any analysis-based warnings.
Ted Kremenekd064fdc2010-03-23 00:13:23 +00008768 const sema::AnalysisBasedWarnings::Policy &WP =
8769 AnalysisWarnings.getDefaultPolicy();
John McCalle0054f62010-08-25 05:56:39 +00008770 AnalysisWarnings.IssueWarnings(WP, Result);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00008771
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008772 PopFunctionOrBlockScope();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008773 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00008774}
8775
John McCall60d7b3a2010-08-24 06:29:42 +00008776ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00008777 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008778 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008779 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008780 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00008781 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008782}
8783
John McCall60d7b3a2010-08-24 06:29:42 +00008784ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00008785 Expr *E, TypeSourceInfo *TInfo,
8786 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008787 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00008788
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008789 // Get the va_list type
8790 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008791 if (VaListType->isArrayType()) {
8792 // Deal with implicit array decay; for example, on x86-64,
8793 // va_list is an array, but it's supposed to decay to
8794 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008795 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00008796 // Make sure the input expression also decays appropriately.
8797 UsualUnaryConversions(E);
8798 } else {
8799 // Otherwise, the va_list argument must be an l-value because
8800 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00008801 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00008802 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00008803 return ExprError();
8804 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008805
Douglas Gregordd027302009-05-19 23:10:31 +00008806 if (!E->isTypeDependent() &&
8807 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00008808 return ExprError(Diag(E->getLocStart(),
8809 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008810 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00008811 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008812
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008813 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008814 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008815
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008816 QualType T = TInfo->getType().getNonLValueExprType(Context);
8817 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008818}
8819
John McCall60d7b3a2010-08-24 06:29:42 +00008820ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008821 // The type of __null will be int or long, depending on the size of
8822 // pointers on the target.
8823 QualType Ty;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008824 unsigned pw = Context.Target.getPointerWidth(0);
8825 if (pw == Context.Target.getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008826 Ty = Context.IntTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008827 else if (pw == Context.Target.getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008828 Ty = Context.LongTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008829 else if (pw == Context.Target.getLongLongWidth())
8830 Ty = Context.LongLongTy;
8831 else {
8832 assert(!"I don't know size of pointer!");
8833 Ty = Context.IntTy;
8834 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008835
Sebastian Redlf53597f2009-03-15 17:47:39 +00008836 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008837}
8838
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008839static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00008840 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008841 if (!SemaRef.getLangOptions().ObjC1)
8842 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008843
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008844 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8845 if (!PT)
8846 return;
8847
8848 // Check if the destination is of type 'id'.
8849 if (!PT->isObjCIdType()) {
8850 // Check if the destination is the 'NSString' interface.
8851 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8852 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8853 return;
8854 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008855
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008856 // Strip off any parens and casts.
8857 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8858 if (!SL || SL->isWide())
8859 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008860
Douglas Gregor849b2432010-03-31 17:46:05 +00008861 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008862}
8863
Chris Lattner5cf216b2008-01-04 18:04:52 +00008864bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8865 SourceLocation Loc,
8866 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00008867 Expr *SrcExpr, AssignmentAction Action,
8868 bool *Complained) {
8869 if (Complained)
8870 *Complained = false;
8871
Chris Lattner5cf216b2008-01-04 18:04:52 +00008872 // Decode the result (notice that AST's are still created for extensions).
8873 bool isInvalid = false;
8874 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00008875 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008876
Chris Lattner5cf216b2008-01-04 18:04:52 +00008877 switch (ConvTy) {
8878 default: assert(0 && "Unknown conversion type");
8879 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008880 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00008881 DiagKind = diag::ext_typecheck_convert_pointer_int;
8882 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008883 case IntToPointer:
8884 DiagKind = diag::ext_typecheck_convert_int_pointer;
8885 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008886 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00008887 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00008888 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
8889 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00008890 case IncompatiblePointerSign:
8891 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8892 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008893 case FunctionVoidPointer:
8894 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8895 break;
John McCall86c05f32011-02-01 00:10:29 +00008896 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00008897 // Perform array-to-pointer decay if necessary.
8898 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8899
John McCall86c05f32011-02-01 00:10:29 +00008900 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8901 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8902 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8903 DiagKind = diag::err_typecheck_incompatible_address_space;
8904 break;
8905 }
8906
8907 llvm_unreachable("unknown error case for discarding qualifiers!");
8908 // fallthrough
8909 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00008910 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00008911 // If the qualifiers lost were because we were applying the
8912 // (deprecated) C++ conversion from a string literal to a char*
8913 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8914 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00008915 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00008916 // bit of refactoring (so that the second argument is an
8917 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00008918 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00008919 // C++ semantics.
8920 if (getLangOptions().CPlusPlus &&
8921 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8922 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008923 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8924 break;
Sean Huntc9132b62009-11-08 07:46:34 +00008925 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00008926 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00008927 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008928 case IntToBlockPointer:
8929 DiagKind = diag::err_int_to_block_pointer;
8930 break;
8931 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00008932 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008933 break;
Steve Naroff39579072008-10-14 22:18:38 +00008934 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00008935 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00008936 // it can give a more specific diagnostic.
8937 DiagKind = diag::warn_incompatible_qualified_id;
8938 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00008939 case IncompatibleVectors:
8940 DiagKind = diag::warn_incompatible_vectors;
8941 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008942 case Incompatible:
8943 DiagKind = diag::err_typecheck_convert_incompatible;
8944 isInvalid = true;
8945 break;
8946 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008947
Douglas Gregord4eea832010-04-09 00:35:39 +00008948 QualType FirstType, SecondType;
8949 switch (Action) {
8950 case AA_Assigning:
8951 case AA_Initializing:
8952 // The destination type comes first.
8953 FirstType = DstType;
8954 SecondType = SrcType;
8955 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008956
Douglas Gregord4eea832010-04-09 00:35:39 +00008957 case AA_Returning:
8958 case AA_Passing:
8959 case AA_Converting:
8960 case AA_Sending:
8961 case AA_Casting:
8962 // The source type comes first.
8963 FirstType = SrcType;
8964 SecondType = DstType;
8965 break;
8966 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008967
Douglas Gregord4eea832010-04-09 00:35:39 +00008968 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008969 << SrcExpr->getSourceRange() << Hint;
Douglas Gregora41a8c52010-04-22 00:20:18 +00008970 if (Complained)
8971 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008972 return isInvalid;
8973}
Anders Carlssone21555e2008-11-30 19:50:32 +00008974
Chris Lattner3bf68932009-04-25 21:59:05 +00008975bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00008976 llvm::APSInt ICEResult;
8977 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8978 if (Result)
8979 *Result = ICEResult;
8980 return false;
8981 }
8982
Anders Carlssone21555e2008-11-30 19:50:32 +00008983 Expr::EvalResult EvalResult;
8984
Mike Stumpeed9cac2009-02-19 03:04:26 +00008985 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00008986 EvalResult.HasSideEffects) {
8987 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8988
8989 if (EvalResult.Diag) {
8990 // We only show the note if it's not the usual "invalid subexpression"
8991 // or if it's actually in a subexpression.
8992 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8993 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8994 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8995 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008996
Anders Carlssone21555e2008-11-30 19:50:32 +00008997 return true;
8998 }
8999
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009000 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9001 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009002
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009003 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009004 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9005 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009006 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009007
Anders Carlssone21555e2008-11-30 19:50:32 +00009008 if (Result)
9009 *Result = EvalResult.Val.getInt();
9010 return false;
9011}
Douglas Gregore0762c92009-06-19 23:52:42 +00009012
Douglas Gregor2afce722009-11-26 00:44:06 +00009013void
Mike Stump1eb44332009-09-09 15:08:12 +00009014Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009015 ExprEvalContexts.push_back(
9016 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00009017}
9018
Mike Stump1eb44332009-09-09 15:08:12 +00009019void
Douglas Gregor2afce722009-11-26 00:44:06 +00009020Sema::PopExpressionEvaluationContext() {
9021 // Pop the current expression evaluation context off the stack.
9022 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9023 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009024
Douglas Gregor06d33692009-12-12 07:57:52 +00009025 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9026 if (Rec.PotentiallyReferenced) {
9027 // Mark any remaining declarations in the current position of the stack
9028 // as "referenced". If they were not meant to be referenced, semantic
9029 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009030 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009031 I = Rec.PotentiallyReferenced->begin(),
9032 IEnd = Rec.PotentiallyReferenced->end();
9033 I != IEnd; ++I)
9034 MarkDeclarationReferenced(I->first, I->second);
9035 }
9036
9037 if (Rec.PotentiallyDiagnosed) {
9038 // Emit any pending diagnostics.
9039 for (PotentiallyEmittedDiagnostics::iterator
9040 I = Rec.PotentiallyDiagnosed->begin(),
9041 IEnd = Rec.PotentiallyDiagnosed->end();
9042 I != IEnd; ++I)
9043 Diag(I->first, I->second);
9044 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009045 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009046
9047 // When are coming out of an unevaluated context, clear out any
9048 // temporaries that we may have created as part of the evaluation of
9049 // the expression in that context: they aren't relevant because they
9050 // will never be constructed.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009051 if (Rec.Context == Unevaluated &&
Douglas Gregor2afce722009-11-26 00:44:06 +00009052 ExprTemporaries.size() > Rec.NumTemporaries)
9053 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9054 ExprTemporaries.end());
9055
9056 // Destroy the popped expression evaluation record.
9057 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009058}
Douglas Gregore0762c92009-06-19 23:52:42 +00009059
9060/// \brief Note that the given declaration was referenced in the source code.
9061///
9062/// This routine should be invoke whenever a given declaration is referenced
9063/// in the source code, and where that reference occurred. If this declaration
9064/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9065/// C99 6.9p3), then the declaration will be marked as used.
9066///
9067/// \param Loc the location where the declaration was referenced.
9068///
9069/// \param D the declaration that has been referenced by the source code.
9070void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9071 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009072
Douglas Gregorc070cc62010-06-17 23:14:26 +00009073 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009074 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009075
Douglas Gregorb5352cf2009-10-08 21:35:42 +00009076 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9077 // template or not. The reason for this is that unevaluated expressions
9078 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9079 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009080 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009081 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009082 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009083 return;
9084 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009085
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009086 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9087 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009088
Douglas Gregore0762c92009-06-19 23:52:42 +00009089 // Do not mark anything as "used" within a dependent context; wait for
9090 // an instantiation.
9091 if (CurContext->isDependentContext())
9092 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009093
Douglas Gregor2afce722009-11-26 00:44:06 +00009094 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009095 case Unevaluated:
9096 // We are in an expression that is not potentially evaluated; do nothing.
9097 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009098
Douglas Gregorac7610d2009-06-22 20:57:11 +00009099 case PotentiallyEvaluated:
9100 // We are in a potentially-evaluated expression, so this declaration is
9101 // "used"; handle this below.
9102 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009103
Douglas Gregorac7610d2009-06-22 20:57:11 +00009104 case PotentiallyPotentiallyEvaluated:
9105 // We are in an expression that may be potentially evaluated; queue this
9106 // declaration reference until we know whether the expression is
9107 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009108 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009109 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009110
9111 case PotentiallyEvaluatedIfUsed:
9112 // Referenced declarations will only be used if the construct in the
9113 // containing expression is used.
9114 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009115 }
Mike Stump1eb44332009-09-09 15:08:12 +00009116
Douglas Gregore0762c92009-06-19 23:52:42 +00009117 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009118 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009119 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00009120 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00009121 if (Constructor->getParent()->hasTrivialConstructor())
9122 return;
9123 if (!Constructor->isUsed(false))
9124 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00009125 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00009126 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009127 if (!Constructor->isUsed(false))
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009128 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9129 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009130
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009131 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009132 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009133 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009134 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009135 if (Destructor->isVirtual())
9136 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009137 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9138 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9139 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009140 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +00009141 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009142 } else if (MethodDecl->isVirtual())
9143 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009144 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009145 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00009146 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009147 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009148 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009149 bool AlreadyInstantiated = false;
9150 if (FunctionTemplateSpecializationInfo *SpecInfo
9151 = Function->getTemplateSpecializationInfo()) {
9152 if (SpecInfo->getPointOfInstantiation().isInvalid())
9153 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009154 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009155 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009156 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009157 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009158 = Function->getMemberSpecializationInfo()) {
9159 if (MSInfo->getPointOfInstantiation().isInvalid())
9160 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009161 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009162 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009163 AlreadyInstantiated = true;
9164 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009165
Douglas Gregor60406be2010-01-16 22:29:39 +00009166 if (!AlreadyInstantiated) {
9167 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9168 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9169 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9170 Loc));
9171 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009172 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009173 }
Gabor Greif40181c42010-08-28 00:16:06 +00009174 } else // Walk redefinitions, as some of them may be instantiable.
9175 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9176 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009177 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009178 MarkDeclarationReferenced(Loc, *i);
9179 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009180
Douglas Gregore0762c92009-06-19 23:52:42 +00009181 // FIXME: keep track of references to static functions
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009182
9183 // Recursive functions should be marked when used from another function.
9184 if (CurContext != Function)
9185 Function->setUsed(true);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009186
Douglas Gregore0762c92009-06-19 23:52:42 +00009187 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009188 }
Mike Stump1eb44332009-09-09 15:08:12 +00009189
Douglas Gregore0762c92009-06-19 23:52:42 +00009190 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009191 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009192 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009193 Var->getInstantiatedFromStaticDataMember()) {
9194 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9195 assert(MSInfo && "Missing member specialization information?");
9196 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9197 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9198 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009199 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009200 }
9201 }
Mike Stump1eb44332009-09-09 15:08:12 +00009202
Douglas Gregore0762c92009-06-19 23:52:42 +00009203 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00009204
Douglas Gregore0762c92009-06-19 23:52:42 +00009205 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00009206 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00009207 }
Douglas Gregore0762c92009-06-19 23:52:42 +00009208}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009209
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009210namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009211 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009212 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009213 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009214 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9215 Sema &S;
9216 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009217
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009218 public:
9219 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009220
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009221 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009222
9223 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9224 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009225 };
9226}
9227
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009228bool MarkReferencedDecls::TraverseTemplateArgument(
9229 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009230 if (Arg.getKind() == TemplateArgument::Declaration) {
9231 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9232 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009233
9234 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009235}
9236
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009237bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009238 if (ClassTemplateSpecializationDecl *Spec
9239 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9240 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00009241 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009242 }
9243
Chandler Carruthe3e210c2010-06-10 10:31:57 +00009244 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009245}
9246
9247void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9248 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009249 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009250}
9251
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009252namespace {
9253 /// \brief Helper class that marks all of the declarations referenced by
9254 /// potentially-evaluated subexpressions as "referenced".
9255 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9256 Sema &S;
9257
9258 public:
9259 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9260
9261 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9262
9263 void VisitDeclRefExpr(DeclRefExpr *E) {
9264 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9265 }
9266
9267 void VisitMemberExpr(MemberExpr *E) {
9268 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009269 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009270 }
9271
9272 void VisitCXXNewExpr(CXXNewExpr *E) {
9273 if (E->getConstructor())
9274 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9275 if (E->getOperatorNew())
9276 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9277 if (E->getOperatorDelete())
9278 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009279 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009280 }
9281
9282 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9283 if (E->getOperatorDelete())
9284 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009285 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9286 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9287 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9288 S.MarkDeclarationReferenced(E->getLocStart(),
9289 S.LookupDestructor(Record));
9290 }
9291
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009292 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009293 }
9294
9295 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9296 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009297 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009298 }
9299
9300 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9301 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9302 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009303
9304 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9305 Visit(E->getExpr());
9306 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009307 };
9308}
9309
9310/// \brief Mark any declarations that appear within this expression or any
9311/// potentially-evaluated subexpressions as "referenced".
9312void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9313 EvaluatedExprMarker(*this).Visit(E);
9314}
9315
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009316/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9317/// of the program being compiled.
9318///
9319/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009320/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009321/// possibility that the code will actually be executable. Code in sizeof()
9322/// expressions, code used only during overload resolution, etc., are not
9323/// potentially evaluated. This routine will suppress such diagnostics or,
9324/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009325/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009326/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009327///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009328/// This routine should be used for all diagnostics that describe the run-time
9329/// behavior of a program, such as passing a non-POD value through an ellipsis.
9330/// Failure to do so will likely result in spurious diagnostics or failures
9331/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009332bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009333 const PartialDiagnostic &PD) {
9334 switch (ExprEvalContexts.back().Context ) {
9335 case Unevaluated:
9336 // The argument will never be evaluated, so don't complain.
9337 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009338
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009339 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009340 case PotentiallyEvaluatedIfUsed:
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009341 Diag(Loc, PD);
9342 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009343
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009344 case PotentiallyPotentiallyEvaluated:
9345 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9346 break;
9347 }
9348
9349 return false;
9350}
9351
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009352bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9353 CallExpr *CE, FunctionDecl *FD) {
9354 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9355 return false;
9356
9357 PartialDiagnostic Note =
9358 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9359 << FD->getDeclName() : PDiag();
9360 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009361
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009362 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009363 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009364 PDiag(diag::err_call_function_incomplete_return)
9365 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009366 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009367 << CE->getSourceRange(),
9368 std::make_pair(NoteLoc, Note)))
9369 return true;
9370
9371 return false;
9372}
9373
Douglas Gregor92c3a042011-01-19 16:50:08 +00009374// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +00009375// will prevent this condition from triggering, which is what we want.
9376void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9377 SourceLocation Loc;
9378
John McCalla52ef082009-11-11 02:41:58 +00009379 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +00009380 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +00009381
John McCall5a881bb2009-10-12 21:59:07 +00009382 if (isa<BinaryOperator>(E)) {
9383 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +00009384 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +00009385 return;
9386
Douglas Gregor92c3a042011-01-19 16:50:08 +00009387 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9388
John McCallc8d8ac52009-11-12 00:06:05 +00009389 // Greylist some idioms by putting them into a warning subcategory.
9390 if (ObjCMessageExpr *ME
9391 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9392 Selector Sel = ME->getSelector();
9393
John McCallc8d8ac52009-11-12 00:06:05 +00009394 // self = [<foo> init...]
9395 if (isSelfExpr(Op->getLHS())
9396 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
9397 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9398
9399 // <foo> = [<bar> nextObject]
9400 else if (Sel.isUnarySelector() &&
9401 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
9402 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9403 }
John McCalla52ef082009-11-11 02:41:58 +00009404
John McCall5a881bb2009-10-12 21:59:07 +00009405 Loc = Op->getOperatorLoc();
9406 } else if (isa<CXXOperatorCallExpr>(E)) {
9407 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +00009408 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +00009409 return;
9410
Douglas Gregor92c3a042011-01-19 16:50:08 +00009411 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +00009412 Loc = Op->getOperatorLoc();
9413 } else {
9414 // Not an assignment.
9415 return;
9416 }
9417
John McCall5a881bb2009-10-12 21:59:07 +00009418 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00009419 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009420
Douglas Gregor55b38842010-04-14 16:09:52 +00009421 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +00009422
9423 if (IsOrAssign)
9424 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9425 << FixItHint::CreateReplacement(Loc, "!=");
9426 else
9427 Diag(Loc, diag::note_condition_assign_to_comparison)
9428 << FixItHint::CreateReplacement(Loc, "==");
9429
Douglas Gregor55b38842010-04-14 16:09:52 +00009430 Diag(Loc, diag::note_condition_assign_silence)
9431 << FixItHint::CreateInsertion(Open, "(")
9432 << FixItHint::CreateInsertion(Close, ")");
John McCall5a881bb2009-10-12 21:59:07 +00009433}
9434
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009435/// \brief Redundant parentheses over an equality comparison can indicate
9436/// that the user intended an assignment used as condition.
9437void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009438 // Don't warn if the parens came from a macro.
9439 SourceLocation parenLoc = parenE->getLocStart();
9440 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9441 return;
9442
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009443 Expr *E = parenE->IgnoreParens();
9444
9445 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +00009446 if (opE->getOpcode() == BO_EQ &&
9447 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9448 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009449 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +00009450
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009451 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9452 Diag(Loc, diag::note_equality_comparison_to_assign)
9453 << FixItHint::CreateReplacement(Loc, "=");
9454 Diag(Loc, diag::note_equality_comparison_silence)
9455 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9456 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009457 }
9458}
9459
John McCall5a881bb2009-10-12 21:59:07 +00009460bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9461 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009462 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9463 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +00009464
9465 if (!E->isTypeDependent()) {
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009466 if (E->isBoundMemberFunction(Context))
9467 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9468 << E->getSourceRange();
9469
John McCallf6a16482010-12-04 03:47:34 +00009470 if (getLangOptions().CPlusPlus)
9471 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9472
9473 DefaultFunctionArrayLvalueConversion(E);
John McCallabc56c72010-12-04 06:09:13 +00009474
9475 QualType T = E->getType();
John McCallf6a16482010-12-04 03:47:34 +00009476 if (!T->isScalarType()) // C99 6.8.4.1p1
9477 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9478 << T << E->getSourceRange();
John McCall5a881bb2009-10-12 21:59:07 +00009479 }
9480
9481 return false;
9482}
Douglas Gregor586596f2010-05-06 17:25:47 +00009483
John McCall60d7b3a2010-08-24 06:29:42 +00009484ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9485 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +00009486 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +00009487 return ExprError();
9488
Douglas Gregorff331c12010-07-25 18:17:45 +00009489 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregor586596f2010-05-06 17:25:47 +00009490 return ExprError();
Douglas Gregor586596f2010-05-06 17:25:47 +00009491
9492 return Owned(Sub);
9493}
John McCall2a984ca2010-10-12 00:20:44 +00009494
9495/// Check for operands with placeholder types and complain if found.
9496/// Returns true if there was an error and no recovery was possible.
9497ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9498 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9499 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9500
9501 // If this is overload, check for a single overload.
9502 if (BT->getKind() == BuiltinType::Overload) {
9503 if (FunctionDecl *Specialization
9504 = ResolveSingleFunctionTemplateSpecialization(E)) {
9505 // The access doesn't really matter in this case.
9506 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9507 Specialization->getAccess());
9508 E = FixOverloadedFunctionReference(E, Found, Specialization);
9509 if (!E) return ExprError();
9510 return Owned(E);
9511 }
9512
John McCall2cd11fe2010-10-12 02:09:17 +00009513 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
John McCall2a984ca2010-10-12 00:20:44 +00009514 return ExprError();
9515 }
9516
9517 // Otherwise it's a use of undeduced auto.
9518 assert(BT->getKind() == BuiltinType::UndeducedAuto);
9519
9520 DeclRefExpr *DRE = cast<DeclRefExpr>(E->IgnoreParens());
9521 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
9522 << DRE->getDecl() << E->getSourceRange();
9523 return ExprError();
9524}