blob: 0a7d22dd64b5b4e8ccfda0312f4746abba23d39d [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
Richard Smith34b41d92011-02-20 03:19:35 +000078 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +000079 if (ParsingInitForAutoVars.count(D)) {
80 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
81 << D->getDeclName();
82 return true;
Richard Smith34b41d92011-02-20 03:19:35 +000083 }
84
Chris Lattner76a642f2009-02-15 22:43:40 +000085 // See if the decl is deprecated.
Benjamin Kramerce2d1862010-10-09 15:49:00 +000086 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>())
Peter Collingbourne743b82b2011-01-02 19:53:12 +000087 EmitDeprecationWarning(D, DA->getMessage(), Loc, UnknownObjCClass);
Chris Lattner76a642f2009-02-15 22:43:40 +000088
Chris Lattnerffb93682009-10-25 17:21:40 +000089 // See if the decl is unavailable
Fariborz Jahanianc784dc12010-10-06 23:12:32 +000090 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) {
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000091 if (UA->getMessage().empty()) {
Peter Collingbourne743b82b2011-01-02 19:53:12 +000092 if (!UnknownObjCClass)
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000093 Diag(Loc, diag::err_unavailable) << D->getDeclName();
94 else
95 Diag(Loc, diag::warn_unavailable_fwdclass_message)
96 << D->getDeclName();
97 }
98 else
Fariborz Jahanianc784dc12010-10-06 23:12:32 +000099 Diag(Loc, diag::err_unavailable_message)
Benjamin Kramerce2d1862010-10-09 15:49:00 +0000100 << D->getDeclName() << UA->getMessage();
Chris Lattnerffb93682009-10-25 17:21:40 +0000101 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
102 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000103
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000104 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000105 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000106 if (FD->isDeleted()) {
107 Diag(Loc, diag::err_deleted_function_use);
108 Diag(D->getLocation(), diag::note_unavailable_here) << true;
109 return true;
110 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000111 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000112
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000113 // Warn if this is used but marked unused.
114 if (D->hasAttr<UnusedAttr>())
115 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
116
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000117 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000118}
119
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000120/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +0000121/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000122/// attribute. It warns if call does not have the sentinel argument.
123///
124void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000125 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000126 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000127 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000128 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000129
130 // FIXME: In C++0x, if any of the arguments are parameter pack
131 // expansions, we can't check for the sentinel now.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000132 int sentinelPos = attr->getSentinel();
133 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +0000134
Mike Stump390b4cc2009-05-16 07:39:55 +0000135 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
136 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000137 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000138 bool warnNotEnoughArgs = false;
139 int isMethod = 0;
140 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
141 // skip over named parameters.
142 ObjCMethodDecl::param_iterator P, E = MD->param_end();
143 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
144 if (nullPos)
145 --nullPos;
146 else
147 ++i;
148 }
149 warnNotEnoughArgs = (P != E || i >= NumArgs);
150 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000151 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000152 // skip over named parameters.
153 ObjCMethodDecl::param_iterator P, E = FD->param_end();
154 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
155 if (nullPos)
156 --nullPos;
157 else
158 ++i;
159 }
160 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000161 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000162 // block or function pointer call.
163 QualType Ty = V->getType();
164 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000165 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000166 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
167 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000168 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
169 unsigned NumArgsInProto = Proto->getNumArgs();
170 unsigned k;
171 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
172 if (nullPos)
173 --nullPos;
174 else
175 ++i;
176 }
177 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
178 }
179 if (Ty->isBlockPointerType())
180 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000181 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000182 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000183 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000184 return;
185
186 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000187 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000188 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000189 return;
190 }
191 int sentinel = i;
192 while (sentinelPos > 0 && i < NumArgs-1) {
193 --sentinelPos;
194 ++i;
195 }
196 if (sentinelPos > 0) {
197 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000198 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000199 return;
200 }
201 while (i < NumArgs-1) {
202 ++i;
203 ++sentinel;
204 }
205 Expr *sentinelExpr = Args[sentinel];
John McCall8eb662e2010-05-06 23:53:00 +0000206 if (!sentinelExpr) return;
207 if (sentinelExpr->isTypeDependent()) return;
208 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000209
210 // nullptr_t is always treated as null.
211 if (sentinelExpr->getType()->isNullPtrType()) return;
212
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000213 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000214 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
215 Expr::NPC_ValueDependentIsNull))
216 return;
217
218 // Unfortunately, __null has type 'int'.
219 if (isa<GNUNullExpr>(sentinelExpr)) return;
220
221 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
222 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000223}
224
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000225SourceRange Sema::getExprRange(ExprTy *E) const {
226 Expr *Ex = (Expr *)E;
227 return Ex? Ex->getSourceRange() : SourceRange();
228}
229
Chris Lattnere7a2e912008-07-25 21:10:04 +0000230//===----------------------------------------------------------------------===//
231// Standard Promotions and Conversions
232//===----------------------------------------------------------------------===//
233
Chris Lattnere7a2e912008-07-25 21:10:04 +0000234/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
235void Sema::DefaultFunctionArrayConversion(Expr *&E) {
236 QualType Ty = E->getType();
237 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
238
Chris Lattnere7a2e912008-07-25 21:10:04 +0000239 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000240 ImpCastExprToType(E, Context.getPointerType(Ty),
John McCall2de56d12010-08-25 11:45:40 +0000241 CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000242 else if (Ty->isArrayType()) {
243 // In C90 mode, arrays only promote to pointers if the array expression is
244 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
245 // type 'array of type' is converted to an expression that has type 'pointer
246 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
247 // that has type 'array of type' ...". The relevant change is "an lvalue"
248 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000249 //
250 // C++ 4.2p1:
251 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
252 // T" can be converted to an rvalue of type "pointer to T".
253 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000254 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
Anders Carlsson112a0a82009-08-07 23:48:20 +0000255 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
John McCall2de56d12010-08-25 11:45:40 +0000256 CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000257 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000258}
259
John McCall409fa9a2010-12-06 20:48:59 +0000260void Sema::DefaultLvalueConversion(Expr *&E) {
John McCall0ae287a2010-12-01 04:43:34 +0000261 // C++ [conv.lval]p1:
262 // A glvalue of a non-function, non-array type T can be
263 // converted to a prvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000264 if (!E->isGLValue()) return;
John McCallf6a16482010-12-04 03:47:34 +0000265
John McCall409fa9a2010-12-06 20:48:59 +0000266 QualType T = E->getType();
267 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000268
John McCall409fa9a2010-12-06 20:48:59 +0000269 // Create a load out of an ObjCProperty l-value, if necessary.
270 if (E->getObjectKind() == OK_ObjCProperty) {
271 ConvertPropertyForRValue(E);
272 if (!E->isGLValue())
John McCallf6a16482010-12-04 03:47:34 +0000273 return;
Douglas Gregora873dfc2010-02-03 00:27:59 +0000274 }
John McCall409fa9a2010-12-06 20:48:59 +0000275
276 // We don't want to throw lvalue-to-rvalue casts on top of
277 // expressions of certain types in C++.
278 if (getLangOptions().CPlusPlus &&
279 (E->getType() == Context.OverloadTy ||
280 T->isDependentType() ||
281 T->isRecordType()))
282 return;
283
284 // The C standard is actually really unclear on this point, and
285 // DR106 tells us what the result should be but not why. It's
286 // generally best to say that void types just doesn't undergo
287 // lvalue-to-rvalue at all. Note that expressions of unqualified
288 // 'void' type are never l-values, but qualified void can be.
289 if (T->isVoidType())
290 return;
291
292 // C++ [conv.lval]p1:
293 // [...] If T is a non-class type, the type of the prvalue is the
294 // cv-unqualified version of T. Otherwise, the type of the
295 // rvalue is T.
296 //
297 // C99 6.3.2.1p2:
298 // If the lvalue has qualified type, the value has the unqualified
299 // version of the type of the lvalue; otherwise, the value has the
300 // type of the lvalue.
301 if (T.hasQualifiers())
302 T = T.getUnqualifiedType();
303
Ted Kremeneka0125d82011-02-16 01:57:07 +0000304 if (const ArraySubscriptExpr *ae = dyn_cast<ArraySubscriptExpr>(E))
305 CheckArrayAccess(ae);
306
John McCall409fa9a2010-12-06 20:48:59 +0000307 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
308 E, 0, VK_RValue);
309}
310
311void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
312 DefaultFunctionArrayConversion(E);
313 DefaultLvalueConversion(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000314}
315
316
Chris Lattnere7a2e912008-07-25 21:10:04 +0000317/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000318/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000319/// sometimes surpressed. For example, the array->pointer conversion doesn't
320/// apply if the array is an argument to the sizeof or address (&) operators.
321/// In these instances, this routine should *not* be called.
John McCall0ae287a2010-12-01 04:43:34 +0000322Expr *Sema::UsualUnaryConversions(Expr *&E) {
323 // First, convert to an r-value.
324 DefaultFunctionArrayLvalueConversion(E);
325
326 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000327 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000328
329 // Try to perform integral promotions if the object has a theoretically
330 // promotable type.
331 if (Ty->isIntegralOrUnscopedEnumerationType()) {
332 // C99 6.3.1.1p2:
333 //
334 // The following may be used in an expression wherever an int or
335 // unsigned int may be used:
336 // - an object or expression with an integer type whose integer
337 // conversion rank is less than or equal to the rank of int
338 // and unsigned int.
339 // - A bit-field of type _Bool, int, signed int, or unsigned int.
340 //
341 // If an int can represent all values of the original type, the
342 // value is converted to an int; otherwise, it is converted to an
343 // unsigned int. These are called the integer promotions. All
344 // other types are unchanged by the integer promotions.
345
346 QualType PTy = Context.isPromotableBitField(E);
347 if (!PTy.isNull()) {
348 ImpCastExprToType(E, PTy, CK_IntegralCast);
349 return E;
350 }
351 if (Ty->isPromotableIntegerType()) {
352 QualType PT = Context.getPromotedIntegerType(Ty);
353 ImpCastExprToType(E, PT, CK_IntegralCast);
354 return E;
355 }
Eli Friedman04e83572009-08-20 04:21:42 +0000356 }
357
John McCall0ae287a2010-12-01 04:43:34 +0000358 return E;
Chris Lattnere7a2e912008-07-25 21:10:04 +0000359}
360
Chris Lattner05faf172008-07-25 22:25:12 +0000361/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000362/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000363/// double. All other argument types are converted by UsualUnaryConversions().
364void Sema::DefaultArgumentPromotion(Expr *&Expr) {
365 QualType Ty = Expr->getType();
366 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000367
John McCall40c29132010-12-06 18:36:11 +0000368 UsualUnaryConversions(Expr);
369
Chris Lattner05faf172008-07-25 22:25:12 +0000370 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000371 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John McCall40c29132010-12-06 18:36:11 +0000372 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
Chris Lattner05faf172008-07-25 22:25:12 +0000373}
374
Chris Lattner312531a2009-04-12 08:11:20 +0000375/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
376/// will warn if the resulting type is not a POD type, and rejects ObjC
377/// interfaces passed by value. This returns true if the argument type is
378/// completely illegal.
Chris Lattner40378332010-05-16 04:01:30 +0000379bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
380 FunctionDecl *FDecl) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000381 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Chris Lattner40378332010-05-16 04:01:30 +0000383 // __builtin_va_start takes the second argument as a "varargs" argument, but
384 // it doesn't actually do anything with it. It doesn't need to be non-pod
385 // etc.
386 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
387 return false;
388
John McCallc12c5bb2010-05-15 11:32:37 +0000389 if (Expr->getType()->isObjCObjectType() &&
Ted Kremenek351ba912011-02-23 01:52:04 +0000390 DiagRuntimeBehavior(Expr->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000391 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
392 << Expr->getType() << CT))
393 return true;
Douglas Gregor75b699a2009-12-12 07:25:49 +0000394
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000395 if (!Expr->getType()->isPODType() &&
Ted Kremenek351ba912011-02-23 01:52:04 +0000396 DiagRuntimeBehavior(Expr->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000397 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
398 << Expr->getType() << CT))
399 return true;
Chris Lattner312531a2009-04-12 08:11:20 +0000400
401 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000402}
403
Chris Lattnere7a2e912008-07-25 21:10:04 +0000404/// UsualArithmeticConversions - Performs various conversions that are common to
405/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000406/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000407/// responsible for emitting appropriate error diagnostics.
408/// FIXME: verify the conversion rules for "complex int" are consistent with
409/// GCC.
410QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
411 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000412 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000413 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000414
415 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000416
Mike Stump1eb44332009-09-09 15:08:12 +0000417 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000418 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000419 QualType lhs =
420 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000421 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000422 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000423
424 // If both types are identical, no conversion is needed.
425 if (lhs == rhs)
426 return lhs;
427
428 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
429 // The caller can deal with this (e.g. pointer + int).
430 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
431 return lhs;
432
John McCallcf33b242010-11-13 08:17:45 +0000433 // Apply unary and bitfield promotions to the LHS's type.
434 QualType lhs_unpromoted = lhs;
435 if (lhs->isPromotableIntegerType())
436 lhs = Context.getPromotedIntegerType(lhs);
Eli Friedman04e83572009-08-20 04:21:42 +0000437 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000438 if (!LHSBitfieldPromoteTy.isNull())
439 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000440 if (lhs != lhs_unpromoted && !isCompAssign)
441 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000442
John McCallcf33b242010-11-13 08:17:45 +0000443 // If both types are identical, no conversion is needed.
444 if (lhs == rhs)
445 return lhs;
446
447 // At this point, we have two different arithmetic types.
448
449 // Handle complex types first (C99 6.3.1.8p1).
450 bool LHSComplexFloat = lhs->isComplexType();
451 bool RHSComplexFloat = rhs->isComplexType();
452 if (LHSComplexFloat || RHSComplexFloat) {
453 // if we have an integer operand, the result is the complex type.
454
John McCall2bb5d002010-11-13 09:02:35 +0000455 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
456 if (rhs->isIntegerType()) {
457 QualType fp = cast<ComplexType>(lhs)->getElementType();
458 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
459 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
460 } else {
461 assert(rhs->isComplexIntegerType());
John McCallf3ea8cf2010-11-14 08:17:51 +0000462 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000463 }
John McCallcf33b242010-11-13 08:17:45 +0000464 return lhs;
465 }
466
John McCall2bb5d002010-11-13 09:02:35 +0000467 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
468 if (!isCompAssign) {
469 // int -> float -> _Complex float
470 if (lhs->isIntegerType()) {
471 QualType fp = cast<ComplexType>(rhs)->getElementType();
472 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
473 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
474 } else {
475 assert(lhs->isComplexIntegerType());
John McCallf3ea8cf2010-11-14 08:17:51 +0000476 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000477 }
478 }
John McCallcf33b242010-11-13 08:17:45 +0000479 return rhs;
480 }
481
482 // This handles complex/complex, complex/float, or float/complex.
483 // When both operands are complex, the shorter operand is converted to the
484 // type of the longer, and that is the type of the result. This corresponds
485 // to what is done when combining two real floating-point operands.
486 // The fun begins when size promotion occur across type domains.
487 // From H&S 6.3.4: When one operand is complex and the other is a real
488 // floating-point type, the less precise type is converted, within it's
489 // real or complex domain, to the precision of the other type. For example,
490 // when combining a "long double" with a "double _Complex", the
491 // "double _Complex" is promoted to "long double _Complex".
492 int order = Context.getFloatingTypeOrder(lhs, rhs);
493
494 // If both are complex, just cast to the more precise type.
495 if (LHSComplexFloat && RHSComplexFloat) {
496 if (order > 0) {
497 // _Complex float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000498 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000499 return lhs;
500
501 } else if (order < 0) {
502 // _Complex float -> _Complex double
503 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000504 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000505 return rhs;
506 }
507 return lhs;
508 }
509
510 // If just the LHS is complex, the RHS needs to be converted,
511 // and the LHS might need to be promoted.
512 if (LHSComplexFloat) {
513 if (order > 0) { // LHS is wider
514 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000515 QualType fp = cast<ComplexType>(lhs)->getElementType();
516 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
517 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000518 return lhs;
519 }
520
521 // RHS is at least as wide. Find its corresponding complex type.
522 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
523
524 // double -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000525 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000526
527 // _Complex float -> _Complex double
528 if (!isCompAssign && order < 0)
John McCall2bb5d002010-11-13 09:02:35 +0000529 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000530
531 return result;
532 }
533
534 // Just the RHS is complex, so the LHS needs to be converted
535 // and the RHS might need to be promoted.
536 assert(RHSComplexFloat);
537
538 if (order < 0) { // RHS is wider
539 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000540 if (!isCompAssign) {
Argyrios Kyrtzidise1889332011-01-18 18:49:33 +0000541 QualType fp = cast<ComplexType>(rhs)->getElementType();
542 ImpCastExprToType(lhsExpr, fp, CK_FloatingCast);
John McCall2bb5d002010-11-13 09:02:35 +0000543 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
544 }
John McCallcf33b242010-11-13 08:17:45 +0000545 return rhs;
546 }
547
548 // LHS is at least as wide. Find its corresponding complex type.
549 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
550
551 // double -> _Complex double
552 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000553 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000554
555 // _Complex float -> _Complex double
556 if (order > 0)
John McCall2bb5d002010-11-13 09:02:35 +0000557 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000558
559 return result;
560 }
561
562 // Now handle "real" floating types (i.e. float, double, long double).
563 bool LHSFloat = lhs->isRealFloatingType();
564 bool RHSFloat = rhs->isRealFloatingType();
565 if (LHSFloat || RHSFloat) {
566 // If we have two real floating types, convert the smaller operand
567 // to the bigger result.
568 if (LHSFloat && RHSFloat) {
569 int order = Context.getFloatingTypeOrder(lhs, rhs);
570 if (order > 0) {
571 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
572 return lhs;
573 }
574
575 assert(order < 0 && "illegal float comparison");
576 if (!isCompAssign)
577 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
578 return rhs;
579 }
580
581 // If we have an integer operand, the result is the real floating type.
582 if (LHSFloat) {
583 if (rhs->isIntegerType()) {
584 // Convert rhs to the lhs floating point type.
585 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
586 return lhs;
587 }
588
589 // Convert both sides to the appropriate complex float.
590 assert(rhs->isComplexIntegerType());
591 QualType result = Context.getComplexType(lhs);
592
593 // _Complex int -> _Complex float
John McCallf3ea8cf2010-11-14 08:17:51 +0000594 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000595
596 // float -> _Complex float
597 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000598 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000599
600 return result;
601 }
602
603 assert(RHSFloat);
604 if (lhs->isIntegerType()) {
605 // Convert lhs to the rhs floating point type.
606 if (!isCompAssign)
607 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
608 return rhs;
609 }
610
611 // Convert both sides to the appropriate complex float.
612 assert(lhs->isComplexIntegerType());
613 QualType result = Context.getComplexType(rhs);
614
615 // _Complex int -> _Complex float
616 if (!isCompAssign)
John McCallf3ea8cf2010-11-14 08:17:51 +0000617 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000618
619 // float -> _Complex float
John McCall2bb5d002010-11-13 09:02:35 +0000620 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000621
622 return result;
623 }
624
625 // Handle GCC complex int extension.
626 // FIXME: if the operands are (int, _Complex long), we currently
627 // don't promote the complex. Also, signedness?
628 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
629 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
630 if (lhsComplexInt && rhsComplexInt) {
631 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
632 rhsComplexInt->getElementType());
633 assert(order && "inequal types with equal element ordering");
634 if (order > 0) {
635 // _Complex int -> _Complex long
John McCall2bb5d002010-11-13 09:02:35 +0000636 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000637 return lhs;
638 }
639
640 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000641 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000642 return rhs;
643 } else if (lhsComplexInt) {
644 // int -> _Complex int
John McCall2bb5d002010-11-13 09:02:35 +0000645 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000646 return lhs;
647 } else if (rhsComplexInt) {
648 // int -> _Complex int
649 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000650 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000651 return rhs;
652 }
653
654 // Finally, we have two differing integer types.
655 // The rules for this case are in C99 6.3.1.8
656 int compare = Context.getIntegerTypeOrder(lhs, rhs);
657 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
658 rhsSigned = rhs->hasSignedIntegerRepresentation();
659 if (lhsSigned == rhsSigned) {
660 // Same signedness; use the higher-ranked type
661 if (compare >= 0) {
662 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
663 return lhs;
664 } else if (!isCompAssign)
665 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
666 return rhs;
667 } else if (compare != (lhsSigned ? 1 : -1)) {
668 // The unsigned type has greater than or equal rank to the
669 // signed type, so use the unsigned type
670 if (rhsSigned) {
671 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
672 return lhs;
673 } else if (!isCompAssign)
674 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
675 return rhs;
676 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
677 // The two types are different widths; if we are here, that
678 // means the signed type is larger than the unsigned type, so
679 // use the signed type.
680 if (lhsSigned) {
681 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
682 return lhs;
683 } else if (!isCompAssign)
684 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
685 return rhs;
686 } else {
687 // The signed type is higher-ranked than the unsigned type,
688 // but isn't actually any bigger (like unsigned int and long
689 // on most 32-bit systems). Use the unsigned type corresponding
690 // to the signed type.
691 QualType result =
692 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
693 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
694 if (!isCompAssign)
695 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
696 return result;
697 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000698}
699
Chris Lattnere7a2e912008-07-25 21:10:04 +0000700//===----------------------------------------------------------------------===//
701// Semantic Analysis for various Expression Types
702//===----------------------------------------------------------------------===//
703
704
Steve Narofff69936d2007-09-16 03:34:24 +0000705/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000706/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
707/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
708/// multiple tokens. However, the common case is that StringToks points to one
709/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000710///
John McCall60d7b3a2010-08-24 06:29:42 +0000711ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +0000712Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000713 assert(NumStringToks && "Must have at least one string!");
714
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000715 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000716 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000717 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000718
719 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
720 for (unsigned i = 0; i != NumStringToks; ++i)
721 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000722
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000723 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000724 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000725 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000726
727 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +0000728 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +0000729 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000730
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000731 // Get an array type for the string, according to C99 6.4.5. This includes
732 // the nul terminator character as well as the string length for pascal
733 // strings.
734 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000735 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000736 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Reid Spencer5f016e22007-07-11 17:01:13 +0000738 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +0000739 return Owned(StringLiteral::Create(Context, Literal.GetString(),
740 Literal.GetStringLength(),
741 Literal.AnyWide, StrTy,
742 &StringTokLocs[0],
743 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000744}
745
John McCall469a1eb2011-02-02 13:00:07 +0000746enum CaptureResult {
747 /// No capture is required.
748 CR_NoCapture,
749
750 /// A capture is required.
751 CR_Capture,
752
John McCall6b5a61b2011-02-07 10:33:21 +0000753 /// A by-ref capture is required.
754 CR_CaptureByRef,
755
John McCall469a1eb2011-02-02 13:00:07 +0000756 /// An error occurred when trying to capture the given variable.
757 CR_Error
758};
759
760/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +0000761///
John McCall469a1eb2011-02-02 13:00:07 +0000762/// \param var - the variable referenced
763/// \param DC - the context which we couldn't capture through
764static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +0000765diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +0000766 VarDecl *var, DeclContext *DC) {
767 switch (S.ExprEvalContexts.back().Context) {
768 case Sema::Unevaluated:
769 // The argument will never be evaluated, so don't complain.
770 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +0000771
John McCall469a1eb2011-02-02 13:00:07 +0000772 case Sema::PotentiallyEvaluated:
773 case Sema::PotentiallyEvaluatedIfUsed:
774 break;
Chris Lattner639e2d32008-10-20 05:16:36 +0000775
John McCall469a1eb2011-02-02 13:00:07 +0000776 case Sema::PotentiallyPotentiallyEvaluated:
777 // FIXME: delay these!
778 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000779 }
Mike Stump1eb44332009-09-09 15:08:12 +0000780
John McCall469a1eb2011-02-02 13:00:07 +0000781 // Don't diagnose about capture if we're not actually in code right
782 // now; in general, there are more appropriate places that will
783 // diagnose this.
784 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
785
786 // This particular madness can happen in ill-formed default
787 // arguments; claim it's okay and let downstream code handle it.
788 if (isa<ParmVarDecl>(var) &&
789 S.CurContext == var->getDeclContext()->getParent())
790 return CR_NoCapture;
791
792 DeclarationName functionName;
793 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
794 functionName = fn->getDeclName();
795 // FIXME: variable from enclosing block that we couldn't capture from!
796
797 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
798 << var->getIdentifier() << functionName;
799 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
800 << var->getIdentifier();
801
802 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +0000803}
804
John McCall6b5a61b2011-02-07 10:33:21 +0000805/// There is a well-formed capture at a particular scope level;
806/// propagate it through all the nested blocks.
807static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
808 const BlockDecl::Capture &capture) {
809 VarDecl *var = capture.getVariable();
810
811 // Update all the inner blocks with the capture information.
812 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
813 i != e; ++i) {
814 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
815 innerBlock->Captures.push_back(
816 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
817 /*nested*/ true, capture.getCopyExpr()));
818 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
819 }
820
821 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
822}
823
824/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +0000825/// given value in the current context requires a variable capture.
826///
827/// This also keeps the captures set in the BlockScopeInfo records
828/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +0000829static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +0000830 ValueDecl *value) {
831 // Only variables ever require capture.
832 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +0000833 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +0000834
835 // Fast path: variables from the current context never require capture.
836 DeclContext *DC = S.CurContext;
837 if (var->getDeclContext() == DC) return CR_NoCapture;
838
839 // Only variables with local storage require capture.
840 // FIXME: What about 'const' variables in C++?
841 if (!var->hasLocalStorage()) return CR_NoCapture;
842
843 // Otherwise, we need to capture.
844
845 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +0000846 do {
847 // Only blocks (and eventually C++0x closures) can capture; other
848 // scopes don't work.
849 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +0000850 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +0000851
852 BlockScopeInfo *blockScope =
853 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
854 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
855
John McCall6b5a61b2011-02-07 10:33:21 +0000856 // Check whether we've already captured it in this block. If so,
857 // we're done.
858 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
859 return propagateCapture(S, functionScopesIndex,
860 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +0000861
862 functionScopesIndex--;
863 DC = cast<BlockDecl>(DC)->getDeclContext();
864 } while (var->getDeclContext() != DC);
865
John McCall6b5a61b2011-02-07 10:33:21 +0000866 // Okay, we descended all the way to the block that defines the variable.
867 // Actually try to capture it.
868 QualType type = var->getType();
869
870 // Prohibit variably-modified types.
871 if (type->isVariablyModifiedType()) {
872 S.Diag(loc, diag::err_ref_vm_type);
873 S.Diag(var->getLocation(), diag::note_declared_at);
874 return CR_Error;
875 }
876
877 // Prohibit arrays, even in __block variables, but not references to
878 // them.
879 if (type->isArrayType()) {
880 S.Diag(loc, diag::err_ref_array_type);
881 S.Diag(var->getLocation(), diag::note_declared_at);
882 return CR_Error;
883 }
884
885 S.MarkDeclarationReferenced(loc, var);
886
887 // The BlocksAttr indicates the variable is bound by-reference.
888 bool byRef = var->hasAttr<BlocksAttr>();
889
890 // Build a copy expression.
891 Expr *copyExpr = 0;
892 if (!byRef && S.getLangOptions().CPlusPlus &&
893 !type->isDependentType() && type->isStructureOrClassType()) {
894 // According to the blocks spec, the capture of a variable from
895 // the stack requires a const copy constructor. This is not true
896 // of the copy/move done to move a __block variable to the heap.
897 type.addConst();
898
899 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
900 ExprResult result =
901 S.PerformCopyInitialization(
902 InitializedEntity::InitializeBlock(var->getLocation(),
903 type, false),
904 loc, S.Owned(declRef));
905
906 // Build a full-expression copy expression if initialization
907 // succeeded and used a non-trivial constructor. Recover from
908 // errors by pretending that the copy isn't necessary.
909 if (!result.isInvalid() &&
910 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
911 result = S.MaybeCreateExprWithCleanups(result);
912 copyExpr = result.take();
913 }
914 }
915
916 // We're currently at the declarer; go back to the closure.
917 functionScopesIndex++;
918 BlockScopeInfo *blockScope =
919 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
920
921 // Build a valid capture in this scope.
922 blockScope->Captures.push_back(
923 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
924 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
925
926 // Propagate that to inner captures if necessary.
927 return propagateCapture(S, functionScopesIndex,
928 blockScope->Captures.back());
929}
930
931static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
932 const DeclarationNameInfo &NameInfo,
933 bool byRef) {
934 assert(isa<VarDecl>(vd) && "capturing non-variable");
935
936 VarDecl *var = cast<VarDecl>(vd);
937 assert(var->hasLocalStorage() && "capturing non-local");
938 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
939
940 QualType exprType = var->getType().getNonReferenceType();
941
942 BlockDeclRefExpr *BDRE;
943 if (!byRef) {
944 // The variable will be bound by copy; make it const within the
945 // closure, but record that this was done in the expression.
946 bool constAdded = !exprType.isConstQualified();
947 exprType.addConst();
948
949 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
950 NameInfo.getLoc(), false,
951 constAdded);
952 } else {
953 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
954 NameInfo.getLoc(), true);
955 }
956
957 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +0000958}
Chris Lattner639e2d32008-10-20 05:16:36 +0000959
John McCall60d7b3a2010-08-24 06:29:42 +0000960ExprResult
John McCallf89e55a2010-11-18 06:31:45 +0000961Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +0000962 SourceLocation Loc,
963 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000964 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +0000965 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +0000966}
967
John McCall76a40212011-02-09 01:13:10 +0000968/// BuildDeclRefExpr - Build an expression that references a
969/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +0000970ExprResult
John McCall76a40212011-02-09 01:13:10 +0000971Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +0000972 const DeclarationNameInfo &NameInfo,
973 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000974 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +0000975
John McCall7eb0a9e2010-11-24 05:12:34 +0000976 Expr *E = DeclRefExpr::Create(Context,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000977 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
John McCall7eb0a9e2010-11-24 05:12:34 +0000978 SS? SS->getRange() : SourceRange(),
979 D, NameInfo, Ty, VK);
980
981 // Just in case we're building an illegal pointer-to-member.
982 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
983 E->setObjectKind(OK_BitField);
984
985 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +0000986}
987
John McCalldfa1edb2010-11-23 20:48:44 +0000988static ExprResult
989BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
990 const CXXScopeSpec &SS, FieldDecl *Field,
991 DeclAccessPair FoundDecl,
992 const DeclarationNameInfo &MemberNameInfo);
993
John McCall60d7b3a2010-08-24 06:29:42 +0000994ExprResult
John McCall5808ce42011-02-03 08:15:49 +0000995Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
996 SourceLocation loc,
997 IndirectFieldDecl *indirectField,
998 Expr *baseObjectExpr,
999 SourceLocation opLoc) {
1000 // First, build the expression that refers to the base object.
1001
1002 bool baseObjectIsPointer = false;
1003 Qualifiers baseQuals;
1004
1005 // Case 1: the base of the indirect field is not a field.
1006 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregorf5848322011-02-18 02:44:58 +00001007 CXXScopeSpec EmptySS;
John McCall5808ce42011-02-03 08:15:49 +00001008 if (baseVariable) {
1009 assert(baseVariable->getType()->isRecordType());
1010
1011 // In principle we could have a member access expression that
1012 // accesses an anonymous struct/union that's a static member of
1013 // the base object's class. However, under the current standard,
1014 // static data members cannot be anonymous structs or unions.
1015 // Supporting this is as easy as building a MemberExpr here.
1016 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1017
1018 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1019
1020 ExprResult result =
Douglas Gregorf5848322011-02-18 02:44:58 +00001021 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCall5808ce42011-02-03 08:15:49 +00001022 if (result.isInvalid()) return ExprError();
1023
1024 baseObjectExpr = result.take();
1025 baseObjectIsPointer = false;
1026 baseQuals = baseObjectExpr->getType().getQualifiers();
1027
1028 // Case 2: the base of the indirect field is a field and the user
1029 // wrote a member expression.
1030 } else if (baseObjectExpr) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001031 // The caller provided the base object expression. Determine
1032 // whether its a pointer and whether it adds any qualifiers to the
1033 // anonymous struct/union fields we're looking into.
John McCall5808ce42011-02-03 08:15:49 +00001034 QualType objectType = baseObjectExpr->getType();
1035
1036 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1037 baseObjectIsPointer = true;
1038 objectType = ptr->getPointeeType();
1039 } else {
1040 baseObjectIsPointer = false;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001041 }
John McCall5808ce42011-02-03 08:15:49 +00001042 baseQuals = objectType.getQualifiers();
1043
1044 // Case 3: the base of the indirect field is a field and we should
1045 // build an implicit member access.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001046 } else {
1047 // We've found a member of an anonymous struct/union that is
1048 // inside a non-anonymous struct/union, so in a well-formed
1049 // program our base object expression is "this".
John McCall5808ce42011-02-03 08:15:49 +00001050 CXXMethodDecl *method = tryCaptureCXXThis();
1051 if (!method) {
1052 Diag(loc, diag::err_invalid_member_use_in_static_method)
1053 << indirectField->getDeclName();
1054 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001055 }
1056
John McCall5808ce42011-02-03 08:15:49 +00001057 // Our base object expression is "this".
1058 baseObjectExpr =
1059 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1060 /*isImplicit=*/ true);
1061 baseObjectIsPointer = true;
1062 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001063 }
1064
1065 // Build the implicit member references to the field of the
1066 // anonymous struct/union.
John McCall5808ce42011-02-03 08:15:49 +00001067 Expr *result = baseObjectExpr;
1068 IndirectFieldDecl::chain_iterator
1069 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCalldfa1edb2010-11-23 20:48:44 +00001070
John McCall5808ce42011-02-03 08:15:49 +00001071 // Build the first member access in the chain with full information.
1072 if (!baseVariable) {
1073 FieldDecl *field = cast<FieldDecl>(*FI);
John McCalldfa1edb2010-11-23 20:48:44 +00001074
John McCall5808ce42011-02-03 08:15:49 +00001075 // FIXME: use the real found-decl info!
1076 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall0953e762009-09-24 19:53:00 +00001077
John McCall5808ce42011-02-03 08:15:49 +00001078 // Make a nameInfo that properly uses the anonymous name.
1079 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall0953e762009-09-24 19:53:00 +00001080
John McCall5808ce42011-02-03 08:15:49 +00001081 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregorf5848322011-02-18 02:44:58 +00001082 EmptySS, field, foundDecl,
John McCall5808ce42011-02-03 08:15:49 +00001083 memberNameInfo).take();
1084 baseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +00001085
John McCall5808ce42011-02-03 08:15:49 +00001086 // FIXME: check qualified member access
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001087 }
1088
John McCall5808ce42011-02-03 08:15:49 +00001089 // In all cases, we should now skip the first declaration in the chain.
1090 ++FI;
1091
Douglas Gregorf5848322011-02-18 02:44:58 +00001092 while (FI != FEnd) {
1093 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCall5808ce42011-02-03 08:15:49 +00001094
1095 // FIXME: these are somewhat meaningless
1096 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1097 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall5808ce42011-02-03 08:15:49 +00001098
1099 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregorf5848322011-02-18 02:44:58 +00001100 (FI == FEnd? SS : EmptySS), field,
1101 foundDecl, memberNameInfo)
John McCall5808ce42011-02-03 08:15:49 +00001102 .take();
1103 }
1104
1105 return Owned(result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001106}
1107
Abramo Bagnara25777432010-08-11 22:01:17 +00001108/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001109/// possibly a list of template arguments.
1110///
1111/// If this produces template arguments, it is permitted to call
1112/// DecomposeTemplateName.
1113///
1114/// This actually loses a lot of source location information for
1115/// non-standard name kinds; we should consider preserving that in
1116/// some way.
1117static void DecomposeUnqualifiedId(Sema &SemaRef,
1118 const UnqualifiedId &Id,
1119 TemplateArgumentListInfo &Buffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00001120 DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00001121 const TemplateArgumentListInfo *&TemplateArgs) {
1122 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1123 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1124 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1125
1126 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1127 Id.TemplateId->getTemplateArgs(),
1128 Id.TemplateId->NumArgs);
1129 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1130 TemplateArgsPtr.release();
1131
John McCall2b5289b2010-08-23 07:28:44 +00001132 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001133 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1134 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001135 TemplateArgs = &Buffer;
1136 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001137 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001138 TemplateArgs = 0;
1139 }
1140}
1141
John McCallaa81e162009-12-01 22:10:20 +00001142/// Determines if the given class is provably not derived from all of
1143/// the prospective base classes.
1144static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1145 CXXRecordDecl *Record,
1146 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +00001147 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +00001148 return false;
1149
Douglas Gregor952b0172010-02-11 01:04:33 +00001150 RecordDecl *RD = Record->getDefinition();
John McCallb1b42562009-12-01 22:28:41 +00001151 if (!RD) return false;
1152 Record = cast<CXXRecordDecl>(RD);
1153
John McCallaa81e162009-12-01 22:10:20 +00001154 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1155 E = Record->bases_end(); I != E; ++I) {
1156 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1157 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1158 if (!BaseRT) return false;
1159
1160 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +00001161 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1162 return false;
1163 }
1164
1165 return true;
1166}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001167
John McCallaa81e162009-12-01 22:10:20 +00001168enum IMAKind {
1169 /// The reference is definitely not an instance member access.
1170 IMA_Static,
1171
1172 /// The reference may be an implicit instance member access.
1173 IMA_Mixed,
1174
1175 /// The reference may be to an instance member, but it is invalid if
1176 /// so, because the context is not an instance method.
1177 IMA_Mixed_StaticContext,
1178
1179 /// The reference may be to an instance member, but it is invalid if
1180 /// so, because the context is from an unrelated class.
1181 IMA_Mixed_Unrelated,
1182
1183 /// The reference is definitely an implicit instance member access.
1184 IMA_Instance,
1185
1186 /// The reference may be to an unresolved using declaration.
1187 IMA_Unresolved,
1188
1189 /// The reference may be to an unresolved using declaration and the
1190 /// context is not an instance method.
1191 IMA_Unresolved_StaticContext,
1192
John McCallaa81e162009-12-01 22:10:20 +00001193 /// All possible referrents are instance members and the current
1194 /// context is not an instance method.
1195 IMA_Error_StaticContext,
1196
1197 /// All possible referrents are instance members of an unrelated
1198 /// class.
1199 IMA_Error_Unrelated
1200};
1201
1202/// The given lookup names class member(s) and is not being used for
1203/// an address-of-member expression. Classify the type of access
1204/// according to whether it's possible that this reference names an
1205/// instance member. This is best-effort; it is okay to
1206/// conservatively answer "yes", in which case some errors will simply
1207/// not be caught until template-instantiation.
1208static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1209 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +00001210 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +00001211
John McCallea1471e2010-05-20 01:18:31 +00001212 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCallaa81e162009-12-01 22:10:20 +00001213 bool isStaticContext =
John McCallea1471e2010-05-20 01:18:31 +00001214 (!isa<CXXMethodDecl>(DC) ||
1215 cast<CXXMethodDecl>(DC)->isStatic());
John McCallaa81e162009-12-01 22:10:20 +00001216
1217 if (R.isUnresolvableResult())
1218 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1219
1220 // Collect all the declaring classes of instance members we find.
1221 bool hasNonInstance = false;
Sebastian Redlf9780002010-11-26 16:28:07 +00001222 bool hasField = false;
John McCallaa81e162009-12-01 22:10:20 +00001223 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1224 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall161755a2010-04-06 21:38:20 +00001225 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00001226
John McCall161755a2010-04-06 21:38:20 +00001227 if (D->isCXXInstanceMember()) {
Sebastian Redlf9780002010-11-26 16:28:07 +00001228 if (dyn_cast<FieldDecl>(D))
1229 hasField = true;
1230
John McCallaa81e162009-12-01 22:10:20 +00001231 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCallaa81e162009-12-01 22:10:20 +00001232 Classes.insert(R->getCanonicalDecl());
1233 }
1234 else
1235 hasNonInstance = true;
1236 }
1237
1238 // If we didn't find any instance members, it can't be an implicit
1239 // member reference.
1240 if (Classes.empty())
1241 return IMA_Static;
1242
1243 // If the current context is not an instance method, it can't be
1244 // an implicit member reference.
Sebastian Redlf9780002010-11-26 16:28:07 +00001245 if (isStaticContext) {
1246 if (hasNonInstance)
1247 return IMA_Mixed_StaticContext;
1248
1249 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1250 // C++0x [expr.prim.general]p10:
1251 // An id-expression that denotes a non-static data member or non-static
1252 // member function of a class can only be used:
1253 // (...)
1254 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1255 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1256 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1257 if (isUnevaluatedExpression)
1258 return IMA_Mixed_StaticContext;
1259 }
1260
1261 return IMA_Error_StaticContext;
1262 }
John McCallaa81e162009-12-01 22:10:20 +00001263
1264 // If we can prove that the current context is unrelated to all the
1265 // declaring classes, it can't be an implicit member reference (in
1266 // which case it's an error if any of those members are selected).
1267 if (IsProvablyNotDerivedFrom(SemaRef,
John McCallea1471e2010-05-20 01:18:31 +00001268 cast<CXXMethodDecl>(DC)->getParent(),
John McCallaa81e162009-12-01 22:10:20 +00001269 Classes))
1270 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1271
1272 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1273}
1274
1275/// Diagnose a reference to a field with no object available.
1276static void DiagnoseInstanceReference(Sema &SemaRef,
1277 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00001278 NamedDecl *rep,
1279 const DeclarationNameInfo &nameInfo) {
1280 SourceLocation Loc = nameInfo.getLoc();
John McCallaa81e162009-12-01 22:10:20 +00001281 SourceRange Range(Loc);
1282 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1283
John McCall5808ce42011-02-03 08:15:49 +00001284 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCallaa81e162009-12-01 22:10:20 +00001285 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1286 if (MD->isStatic()) {
1287 // "invalid use of member 'x' in static member function"
1288 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCall5808ce42011-02-03 08:15:49 +00001289 << Range << nameInfo.getName();
John McCallaa81e162009-12-01 22:10:20 +00001290 return;
1291 }
1292 }
1293
1294 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCall5808ce42011-02-03 08:15:49 +00001295 << nameInfo.getName() << Range;
John McCallaa81e162009-12-01 22:10:20 +00001296 return;
1297 }
1298
1299 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +00001300}
1301
John McCall578b69b2009-12-16 08:11:27 +00001302/// Diagnose an empty lookup.
1303///
1304/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001305bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1306 CorrectTypoContext CTC) {
John McCall578b69b2009-12-16 08:11:27 +00001307 DeclarationName Name = R.getLookupName();
1308
John McCall578b69b2009-12-16 08:11:27 +00001309 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001310 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001311 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1312 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001313 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001314 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001315 diagnostic_suggest = diag::err_undeclared_use_suggest;
1316 }
John McCall578b69b2009-12-16 08:11:27 +00001317
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001318 // If the original lookup was an unqualified lookup, fake an
1319 // unqualified lookup. This is useful when (for example) the
1320 // original lookup would not have found something because it was a
1321 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001322 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001323 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001324 if (isa<CXXRecordDecl>(DC)) {
1325 LookupQualifiedName(R, DC);
1326
1327 if (!R.empty()) {
1328 // Don't give errors about ambiguities in this lookup.
1329 R.suppressDiagnostics();
1330
1331 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1332 bool isInstance = CurMethod &&
1333 CurMethod->isInstance() &&
1334 DC == CurMethod->getParent();
1335
1336 // Give a code modification hint to insert 'this->'.
1337 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1338 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001339 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001340 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1341 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001342 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001343 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001344 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001345 Diag(R.getNameLoc(), diagnostic) << Name
1346 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1347 QualType DepThisType = DepMethod->getThisType(Context);
1348 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1349 R.getNameLoc(), DepThisType, false);
1350 TemplateArgumentListInfo TList;
1351 if (ULE->hasExplicitTemplateArgs())
1352 ULE->copyTemplateArgumentsInto(TList);
1353 CXXDependentScopeMemberExpr *DepExpr =
1354 CXXDependentScopeMemberExpr::Create(
1355 Context, DepThis, DepThisType, true, SourceLocation(),
1356 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
1357 R.getLookupNameInfo(), &TList);
1358 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001359 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001360 // FIXME: we should be able to handle this case too. It is correct
1361 // to add this-> here. This is a workaround for PR7947.
1362 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001363 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001364 } else {
John McCall578b69b2009-12-16 08:11:27 +00001365 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001366 }
John McCall578b69b2009-12-16 08:11:27 +00001367
1368 // Do we really want to note all of these?
1369 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1370 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1371
1372 // Tell the callee to try to recover.
1373 return false;
1374 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001375
1376 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001377 }
1378 }
1379
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001380 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001381 DeclarationName Corrected;
Daniel Dunbardc32cdf2010-06-02 15:46:52 +00001382 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001383 if (!R.empty()) {
1384 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1385 if (SS.isEmpty())
1386 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1387 << FixItHint::CreateReplacement(R.getNameLoc(),
1388 R.getLookupName().getAsString());
1389 else
1390 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1391 << Name << computeDeclContext(SS, false) << R.getLookupName()
1392 << SS.getRange()
1393 << FixItHint::CreateReplacement(R.getNameLoc(),
1394 R.getLookupName().getAsString());
1395 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1396 Diag(ND->getLocation(), diag::note_previous_decl)
1397 << ND->getDeclName();
1398
1399 // Tell the callee to try to recover.
1400 return false;
1401 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001402
Douglas Gregoraaf87162010-04-14 20:04:41 +00001403 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1404 // FIXME: If we ended up with a typo for a type name or
1405 // Objective-C class name, we're in trouble because the parser
1406 // is in the wrong place to recover. Suggest the typo
1407 // correction, but don't make it a fix-it since we're not going
1408 // to recover well anyway.
1409 if (SS.isEmpty())
1410 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1411 else
1412 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1413 << Name << computeDeclContext(SS, false) << R.getLookupName()
1414 << SS.getRange();
1415
1416 // Don't try to recover; it won't work.
1417 return true;
1418 }
1419 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001420 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001421 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001422 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +00001423 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001424 else
Douglas Gregord203a162010-01-01 00:15:04 +00001425 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001426 << Name << computeDeclContext(SS, false) << Corrected
1427 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001428 return true;
1429 }
Douglas Gregord203a162010-01-01 00:15:04 +00001430 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001431 }
1432
1433 // Emit a special diagnostic for failed member lookups.
1434 // FIXME: computing the declaration context might fail here (?)
1435 if (!SS.isEmpty()) {
1436 Diag(R.getNameLoc(), diag::err_no_member)
1437 << Name << computeDeclContext(SS, false)
1438 << SS.getRange();
1439 return true;
1440 }
1441
John McCall578b69b2009-12-16 08:11:27 +00001442 // Give up, we can't recover.
1443 Diag(R.getNameLoc(), diagnostic) << Name;
1444 return true;
1445}
1446
Douglas Gregorca45da02010-11-02 20:36:02 +00001447ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1448 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001449 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1450 if (!IDecl)
1451 return 0;
1452 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1453 if (!ClassImpDecl)
1454 return 0;
Douglas Gregorca45da02010-11-02 20:36:02 +00001455 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001456 if (!property)
1457 return 0;
1458 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregorca45da02010-11-02 20:36:02 +00001459 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1460 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001461 return 0;
1462 return property;
1463}
1464
Douglas Gregorca45da02010-11-02 20:36:02 +00001465bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1466 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1467 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1468 if (!IDecl)
1469 return false;
1470 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1471 if (!ClassImpDecl)
1472 return false;
1473 if (ObjCPropertyImplDecl *PIDecl
1474 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1475 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1476 PIDecl->getPropertyIvarDecl())
1477 return false;
1478
1479 return true;
1480}
1481
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001482static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001483 LookupResult &Lookup,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001484 IdentifierInfo *II,
1485 SourceLocation NameLoc) {
1486 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001487 bool LookForIvars;
1488 if (Lookup.empty())
1489 LookForIvars = true;
1490 else if (CurMeth->isClassMethod())
1491 LookForIvars = false;
1492 else
1493 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahaniand0fbadd2011-01-26 00:57:01 +00001494 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1495 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001496 if (!LookForIvars)
1497 return 0;
1498
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001499 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1500 if (!IDecl)
1501 return 0;
1502 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001503 if (!ClassImpDecl)
1504 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001505 bool DynamicImplSeen = false;
1506 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1507 if (!property)
1508 return 0;
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001509 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001510 DynamicImplSeen =
1511 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001512 // property implementation has a designated ivar. No need to assume a new
1513 // one.
1514 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1515 return 0;
1516 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001517 if (!DynamicImplSeen) {
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001518 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1519 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001520 NameLoc,
1521 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian75049662010-12-15 23:29:04 +00001522 ObjCIvarDecl::Private,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001523 (Expr *)0, true);
1524 ClassImpDecl->addDecl(Ivar);
1525 IDecl->makeDeclVisibleInContext(Ivar, false);
1526 property->setPropertyIvarDecl(Ivar);
1527 return Ivar;
1528 }
1529 return 0;
1530}
1531
John McCall60d7b3a2010-08-24 06:29:42 +00001532ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001533 CXXScopeSpec &SS,
1534 UnqualifiedId &Id,
1535 bool HasTrailingLParen,
1536 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001537 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1538 "cannot be direct & operand and have a trailing lparen");
1539
1540 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001541 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001542
John McCall129e2df2009-11-30 22:42:35 +00001543 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001544
1545 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001546 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001547 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnara25777432010-08-11 22:01:17 +00001548 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001549
Abramo Bagnara25777432010-08-11 22:01:17 +00001550 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001551 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001552 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001553
John McCallf7a1a742009-11-24 19:00:30 +00001554 // C++ [temp.dep.expr]p3:
1555 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001556 // -- an identifier that was declared with a dependent type,
1557 // (note: handled after lookup)
1558 // -- a template-id that is dependent,
1559 // (note: handled in BuildTemplateIdExpr)
1560 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001561 // -- a nested-name-specifier that contains a class-name that
1562 // names a dependent type.
1563 // Determine whether this is a member of an unknown specialization;
1564 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001565 bool DependentID = false;
1566 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1567 Name.getCXXNameType()->isDependentType()) {
1568 DependentID = true;
1569 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001570 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001571 if (RequireCompleteDeclContext(SS, DC))
1572 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001573 } else {
1574 DependentID = true;
1575 }
1576 }
1577
Chris Lattner337e5502011-02-18 01:27:55 +00001578 if (DependentID)
Abramo Bagnara25777432010-08-11 22:01:17 +00001579 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001580 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001581
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001582 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001583 // Perform the required lookup.
Abramo Bagnara25777432010-08-11 22:01:17 +00001584 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001585 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001586 // Lookup the template name again to correctly establish the context in
1587 // which it was found. This is really unfortunate as we already did the
1588 // lookup to determine that it was a template name in the first place. If
1589 // this becomes a performance hit, we can work harder to preserve those
1590 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001591 bool MemberOfUnknownSpecialization;
1592 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1593 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001594
1595 if (MemberOfUnknownSpecialization ||
1596 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1597 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1598 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001599 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001600 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001601 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001603 // If the result might be in a dependent base class, this is a dependent
1604 // id-expression.
1605 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1606 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1607 TemplateArgs);
1608
John McCallf7a1a742009-11-24 19:00:30 +00001609 // If this reference is in an Objective-C method, then we need to do
1610 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001611 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001612 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001613 if (E.isInvalid())
1614 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Chris Lattner337e5502011-02-18 01:27:55 +00001616 if (Expr *Ex = E.takeAs<Expr>())
1617 return Owned(Ex);
1618
1619 // Synthesize ivars lazily.
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001620 if (getLangOptions().ObjCDefaultSynthProperties &&
1621 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahaniande267602010-11-17 19:41:23 +00001622 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1623 if (const ObjCPropertyDecl *Property =
1624 canSynthesizeProvisionalIvar(II)) {
1625 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1626 Diag(Property->getLocation(), diag::note_property_declare);
1627 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001628 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1629 isAddressOfOperand);
Fariborz Jahaniande267602010-11-17 19:41:23 +00001630 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001631 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001632 // for further use, this must be set to false if in class method.
1633 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001634 }
Chris Lattner8a934232008-03-31 00:36:02 +00001635 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001636
John McCallf7a1a742009-11-24 19:00:30 +00001637 if (R.isAmbiguous())
1638 return ExprError();
1639
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001640 // Determine whether this name might be a candidate for
1641 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001642 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001643
John McCallf7a1a742009-11-24 19:00:30 +00001644 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001645 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001646 // in C90, extension in C99, forbidden in C++).
1647 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1648 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1649 if (D) R.addDecl(D);
1650 }
1651
1652 // If this name wasn't predeclared and if this is not a function
1653 // call, diagnose the problem.
1654 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001655 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001656 return ExprError();
1657
1658 assert(!R.empty() &&
1659 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001660
1661 // If we found an Objective-C instance variable, let
1662 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001663 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001664 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1665 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001666 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001667 assert(E.isInvalid() || E.get());
1668 return move(E);
1669 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001670 }
1671 }
Mike Stump1eb44332009-09-09 15:08:12 +00001672
John McCallf7a1a742009-11-24 19:00:30 +00001673 // This is guaranteed from this point on.
1674 assert(!R.empty() || ADL);
1675
John McCallaa81e162009-12-01 22:10:20 +00001676 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001677 // C++ [class.mfct.non-static]p3:
1678 // When an id-expression that is not part of a class member access
1679 // syntax and not used to form a pointer to member is used in the
1680 // body of a non-static member function of class X, if name lookup
1681 // resolves the name in the id-expression to a non-static non-type
1682 // member of some class C, the id-expression is transformed into a
1683 // class member access expression using (*this) as the
1684 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001685 //
1686 // But we don't actually need to do this for '&' operands if R
1687 // resolved to a function or overloaded function set, because the
1688 // expression is ill-formed if it actually works out to be a
1689 // non-static member function:
1690 //
1691 // C++ [expr.ref]p4:
1692 // Otherwise, if E1.E2 refers to a non-static member function. . .
1693 // [t]he expression can be used only as the left-hand operand of a
1694 // member function call.
1695 //
1696 // There are other safeguards against such uses, but it's important
1697 // to get this right here so that we don't end up making a
1698 // spuriously dependent expression if we're inside a dependent
1699 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001700 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001701 bool MightBeImplicitMember;
1702 if (!isAddressOfOperand)
1703 MightBeImplicitMember = true;
1704 else if (!SS.isEmpty())
1705 MightBeImplicitMember = false;
1706 else if (R.isOverloadedResult())
1707 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001708 else if (R.isUnresolvableResult())
1709 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001710 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001711 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1712 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001713
1714 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001715 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001716 }
1717
John McCallf7a1a742009-11-24 19:00:30 +00001718 if (TemplateArgs)
1719 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001720
John McCallf7a1a742009-11-24 19:00:30 +00001721 return BuildDeclarationNameExpr(SS, R, ADL);
1722}
1723
John McCall3b4294e2009-12-16 12:17:52 +00001724/// Builds an expression which might be an implicit member expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001725ExprResult
John McCall3b4294e2009-12-16 12:17:52 +00001726Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1727 LookupResult &R,
1728 const TemplateArgumentListInfo *TemplateArgs) {
1729 switch (ClassifyImplicitMemberAccess(*this, R)) {
1730 case IMA_Instance:
1731 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1732
John McCall3b4294e2009-12-16 12:17:52 +00001733 case IMA_Mixed:
1734 case IMA_Mixed_Unrelated:
1735 case IMA_Unresolved:
1736 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1737
1738 case IMA_Static:
1739 case IMA_Mixed_StaticContext:
1740 case IMA_Unresolved_StaticContext:
1741 if (TemplateArgs)
1742 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1743 return BuildDeclarationNameExpr(SS, R, false);
1744
1745 case IMA_Error_StaticContext:
1746 case IMA_Error_Unrelated:
John McCall5808ce42011-02-03 08:15:49 +00001747 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1748 R.getLookupNameInfo());
John McCall3b4294e2009-12-16 12:17:52 +00001749 return ExprError();
1750 }
1751
1752 llvm_unreachable("unexpected instance member access kind");
1753 return ExprError();
1754}
1755
John McCall129e2df2009-11-30 22:42:35 +00001756/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1757/// declaration name, generally during template instantiation.
1758/// There's a large number of things which don't need to be done along
1759/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001760ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001761Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001762 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001763 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001764 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001765 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001766
John McCall77bb1aa2010-05-01 00:40:08 +00001767 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001768 return ExprError();
1769
Abramo Bagnara25777432010-08-11 22:01:17 +00001770 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001771 LookupQualifiedName(R, DC);
1772
1773 if (R.isAmbiguous())
1774 return ExprError();
1775
1776 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001777 Diag(NameInfo.getLoc(), diag::err_no_member)
1778 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001779 return ExprError();
1780 }
1781
1782 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1783}
1784
1785/// LookupInObjCMethod - The parser has read a name in, and Sema has
1786/// detected that we're currently inside an ObjC method. Perform some
1787/// additional lookup.
1788///
1789/// Ideally, most of this would be done by lookup, but there's
1790/// actually quite a lot of extra work involved.
1791///
1792/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001793ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001794Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001795 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001796 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001797 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001798
John McCallf7a1a742009-11-24 19:00:30 +00001799 // There are two cases to handle here. 1) scoped lookup could have failed,
1800 // in which case we should look for an ivar. 2) scoped lookup could have
1801 // found a decl, but that decl is outside the current instance method (i.e.
1802 // a global variable). In these two cases, we do a lookup for an ivar with
1803 // this name, if the lookup sucedes, we replace it our current decl.
1804
1805 // If we're in a class method, we don't normally want to look for
1806 // ivars. But if we don't find anything else, and there's an
1807 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001808 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001809
1810 bool LookForIvars;
1811 if (Lookup.empty())
1812 LookForIvars = true;
1813 else if (IsClassMethod)
1814 LookForIvars = false;
1815 else
1816 LookForIvars = (Lookup.isSingleResult() &&
1817 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001818 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001819 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001820 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001821 ObjCInterfaceDecl *ClassDeclared;
1822 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1823 // Diagnose using an ivar in a class method.
1824 if (IsClassMethod)
1825 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1826 << IV->getDeclName());
1827
1828 // If we're referencing an invalid decl, just return this as a silent
1829 // error node. The error diagnostic was already emitted on the decl.
1830 if (IV->isInvalidDecl())
1831 return ExprError();
1832
1833 // Check if referencing a field with __attribute__((deprecated)).
1834 if (DiagnoseUseOfDecl(IV, Loc))
1835 return ExprError();
1836
1837 // Diagnose the use of an ivar outside of the declaring class.
1838 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1839 ClassDeclared != IFace)
1840 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1841
1842 // FIXME: This should use a new expr for a direct reference, don't
1843 // turn this into Self->ivar, just return a BareIVarExpr or something.
1844 IdentifierInfo &II = Context.Idents.get("self");
1845 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001846 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00001847 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001848 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001849 SelfName, false, false);
1850 if (SelfExpr.isInvalid())
1851 return ExprError();
1852
John McCall409fa9a2010-12-06 20:48:59 +00001853 Expr *SelfE = SelfExpr.take();
1854 DefaultLvalueConversion(SelfE);
1855
John McCallf7a1a742009-11-24 19:00:30 +00001856 MarkDeclarationReferenced(Loc, IV);
1857 return Owned(new (Context)
1858 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall409fa9a2010-12-06 20:48:59 +00001859 SelfE, true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001860 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001861 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001862 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001863 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001864 ObjCInterfaceDecl *ClassDeclared;
1865 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1866 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1867 IFace == ClassDeclared)
1868 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1869 }
1870 }
1871
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001872 if (Lookup.empty() && II && AllowBuiltinCreation) {
1873 // FIXME. Consolidate this with similar code in LookupName.
1874 if (unsigned BuiltinID = II->getBuiltinID()) {
1875 if (!(getLangOptions().CPlusPlus &&
1876 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1877 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1878 S, Lookup.isForRedeclaration(),
1879 Lookup.getNameLoc());
1880 if (D) Lookup.addDecl(D);
1881 }
1882 }
1883 }
John McCallf7a1a742009-11-24 19:00:30 +00001884 // Sentinel value saying that we didn't do anything special.
1885 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001886}
John McCallba135432009-11-21 08:51:07 +00001887
John McCall6bb80172010-03-30 21:47:33 +00001888/// \brief Cast a base object to a member's actual type.
1889///
1890/// Logically this happens in three phases:
1891///
1892/// * First we cast from the base type to the naming class.
1893/// The naming class is the class into which we were looking
1894/// when we found the member; it's the qualifier type if a
1895/// qualifier was provided, and otherwise it's the base type.
1896///
1897/// * Next we cast from the naming class to the declaring class.
1898/// If the member we found was brought into a class's scope by
1899/// a using declaration, this is that class; otherwise it's
1900/// the class declaring the member.
1901///
1902/// * Finally we cast from the declaring class to the "true"
1903/// declaring class of the member. This conversion does not
1904/// obey access control.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001905bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00001906Sema::PerformObjectMemberConversion(Expr *&From,
1907 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001908 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001909 NamedDecl *Member) {
1910 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1911 if (!RD)
1912 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001913
Douglas Gregor5fccd362010-03-03 23:55:11 +00001914 QualType DestRecordType;
1915 QualType DestType;
1916 QualType FromRecordType;
1917 QualType FromType = From->getType();
1918 bool PointerConversions = false;
1919 if (isa<FieldDecl>(Member)) {
1920 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001921
Douglas Gregor5fccd362010-03-03 23:55:11 +00001922 if (FromType->getAs<PointerType>()) {
1923 DestType = Context.getPointerType(DestRecordType);
1924 FromRecordType = FromType->getPointeeType();
1925 PointerConversions = true;
1926 } else {
1927 DestType = DestRecordType;
1928 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001929 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001930 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1931 if (Method->isStatic())
1932 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001933
Douglas Gregor5fccd362010-03-03 23:55:11 +00001934 DestType = Method->getThisType(Context);
1935 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001936
Douglas Gregor5fccd362010-03-03 23:55:11 +00001937 if (FromType->getAs<PointerType>()) {
1938 FromRecordType = FromType->getPointeeType();
1939 PointerConversions = true;
1940 } else {
1941 FromRecordType = FromType;
1942 DestType = DestRecordType;
1943 }
1944 } else {
1945 // No conversion necessary.
1946 return false;
1947 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001948
Douglas Gregor5fccd362010-03-03 23:55:11 +00001949 if (DestType->isDependentType() || FromType->isDependentType())
1950 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001951
Douglas Gregor5fccd362010-03-03 23:55:11 +00001952 // If the unqualified types are the same, no conversion is necessary.
1953 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1954 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001955
John McCall6bb80172010-03-30 21:47:33 +00001956 SourceRange FromRange = From->getSourceRange();
1957 SourceLocation FromLoc = FromRange.getBegin();
1958
John McCall5baba9d2010-08-25 10:28:54 +00001959 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00001960
Douglas Gregor5fccd362010-03-03 23:55:11 +00001961 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001962 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00001963 // class name.
1964 //
1965 // If the member was a qualified name and the qualified referred to a
1966 // specific base subobject type, we'll cast to that intermediate type
1967 // first and then to the object in which the member is declared. That allows
1968 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1969 //
1970 // class Base { public: int x; };
1971 // class Derived1 : public Base { };
1972 // class Derived2 : public Base { };
1973 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1974 //
1975 // void VeryDerived::f() {
1976 // x = 17; // error: ambiguous base subobjects
1977 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1978 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001979 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00001980 QualType QType = QualType(Qualifier->getAsType(), 0);
1981 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1982 assert(QType->isRecordType() && "lookup done with non-record type");
1983
1984 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1985
1986 // In C++98, the qualifier type doesn't actually have to be a base
1987 // type of the object type, in which case we just ignore it.
1988 // Otherwise build the appropriate casts.
1989 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00001990 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00001991 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00001992 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00001993 return true;
1994
Douglas Gregor5fccd362010-03-03 23:55:11 +00001995 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00001996 QType = Context.getPointerType(QType);
John McCall5baba9d2010-08-25 10:28:54 +00001997 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
1998 VK, &BasePath);
John McCall6bb80172010-03-30 21:47:33 +00001999
2000 FromType = QType;
2001 FromRecordType = QRecordType;
2002
2003 // If the qualifier type was the same as the destination type,
2004 // we're done.
2005 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2006 return false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002007 }
2008 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002009
John McCall6bb80172010-03-30 21:47:33 +00002010 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002011
John McCall6bb80172010-03-30 21:47:33 +00002012 // If we actually found the member through a using declaration, cast
2013 // down to the using declaration's type.
2014 //
2015 // Pointer equality is fine here because only one declaration of a
2016 // class ever has member declarations.
2017 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2018 assert(isa<UsingShadowDecl>(FoundDecl));
2019 QualType URecordType = Context.getTypeDeclType(
2020 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2021
2022 // We only need to do this if the naming-class to declaring-class
2023 // conversion is non-trivial.
2024 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2025 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002026 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002027 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002028 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00002029 return true;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002030
John McCall6bb80172010-03-30 21:47:33 +00002031 QualType UType = URecordType;
2032 if (PointerConversions)
2033 UType = Context.getPointerType(UType);
John McCall2de56d12010-08-25 11:45:40 +00002034 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00002035 VK, &BasePath);
John McCall6bb80172010-03-30 21:47:33 +00002036 FromType = UType;
2037 FromRecordType = URecordType;
2038 }
2039
2040 // We don't do access control for the conversion from the
2041 // declaring class to the true declaring class.
2042 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002043 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002044
John McCallf871d0c2010-08-07 06:22:56 +00002045 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002046 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2047 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002048 IgnoreAccess))
Douglas Gregor5fccd362010-03-03 23:55:11 +00002049 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002050
John McCall2de56d12010-08-25 11:45:40 +00002051 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00002052 VK, &BasePath);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00002053 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002054}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002055
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002056/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00002057static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00002058 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00002059 DeclAccessPair FoundDecl,
Abramo Bagnara25777432010-08-11 22:01:17 +00002060 const DeclarationNameInfo &MemberNameInfo,
2061 QualType Ty,
John McCallf89e55a2010-11-18 06:31:45 +00002062 ExprValueKind VK, ExprObjectKind OK,
John McCallf7a1a742009-11-24 19:00:30 +00002063 const TemplateArgumentListInfo *TemplateArgs = 0) {
2064 NestedNameSpecifier *Qualifier = 0;
2065 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00002066 if (SS.isSet()) {
2067 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
2068 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002069 }
Mike Stump1eb44332009-09-09 15:08:12 +00002070
John McCallf7a1a742009-11-24 19:00:30 +00002071 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00002072 Member, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002073 TemplateArgs, Ty, VK, OK);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002074}
2075
John McCalldfa1edb2010-11-23 20:48:44 +00002076static ExprResult
2077BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2078 const CXXScopeSpec &SS, FieldDecl *Field,
2079 DeclAccessPair FoundDecl,
2080 const DeclarationNameInfo &MemberNameInfo) {
2081 // x.a is an l-value if 'a' has a reference type. Otherwise:
2082 // x.a is an l-value/x-value/pr-value if the base is (and note
2083 // that *x is always an l-value), except that if the base isn't
2084 // an ordinary object then we must have an rvalue.
2085 ExprValueKind VK = VK_LValue;
2086 ExprObjectKind OK = OK_Ordinary;
2087 if (!IsArrow) {
2088 if (BaseExpr->getObjectKind() == OK_Ordinary)
2089 VK = BaseExpr->getValueKind();
2090 else
2091 VK = VK_RValue;
2092 }
2093 if (VK != VK_RValue && Field->isBitField())
2094 OK = OK_BitField;
2095
2096 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2097 QualType MemberType = Field->getType();
2098 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2099 MemberType = Ref->getPointeeType();
2100 VK = VK_LValue;
2101 } else {
2102 QualType BaseType = BaseExpr->getType();
2103 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2104
2105 Qualifiers BaseQuals = BaseType.getQualifiers();
2106
2107 // GC attributes are never picked up by members.
2108 BaseQuals.removeObjCGCAttr();
2109
2110 // CVR attributes from the base are picked up by members,
2111 // except that 'mutable' members don't pick up 'const'.
2112 if (Field->isMutable()) BaseQuals.removeConst();
2113
2114 Qualifiers MemberQuals
2115 = S.Context.getCanonicalType(MemberType).getQualifiers();
2116
2117 // TR 18037 does not allow fields to be declared with address spaces.
2118 assert(!MemberQuals.hasAddressSpace());
2119
2120 Qualifiers Combined = BaseQuals + MemberQuals;
2121 if (Combined != MemberQuals)
2122 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2123 }
2124
2125 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2126 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2127 FoundDecl, Field))
2128 return ExprError();
2129 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2130 Field, FoundDecl, MemberNameInfo,
2131 MemberType, VK, OK));
2132}
2133
John McCallaa81e162009-12-01 22:10:20 +00002134/// Builds an implicit member access expression. The current context
2135/// is known to be an instance method, and the given unqualified lookup
2136/// set is known to contain only instance members, at least one of which
2137/// is from an appropriate type.
John McCall60d7b3a2010-08-24 06:29:42 +00002138ExprResult
John McCallaa81e162009-12-01 22:10:20 +00002139Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2140 LookupResult &R,
2141 const TemplateArgumentListInfo *TemplateArgs,
2142 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00002143 assert(!R.empty() && !R.isAmbiguous());
2144
John McCall5808ce42011-02-03 08:15:49 +00002145 SourceLocation loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00002146
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002147 // We may have found a field within an anonymous union or struct
2148 // (C++ [class.union]).
John McCallf7a1a742009-11-24 19:00:30 +00002149 // FIXME: template-ids inside anonymous structs?
Francois Pichet87c2e122010-11-21 06:08:52 +00002150 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCall5808ce42011-02-03 08:15:49 +00002151 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet87c2e122010-11-21 06:08:52 +00002152
John McCall5808ce42011-02-03 08:15:49 +00002153 // If this is known to be an instance access, go ahead and build an
2154 // implicit 'this' expression now.
John McCallaa81e162009-12-01 22:10:20 +00002155 // 'this' expression now.
John McCall5808ce42011-02-03 08:15:49 +00002156 CXXMethodDecl *method = tryCaptureCXXThis();
2157 assert(method && "didn't correctly pre-flight capture of 'this'");
2158
2159 QualType thisType = method->getThisType(Context);
2160 Expr *baseExpr = 0; // null signifies implicit access
John McCallaa81e162009-12-01 22:10:20 +00002161 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00002162 SourceLocation Loc = R.getNameLoc();
2163 if (SS.getRange().isValid())
2164 Loc = SS.getRange().getBegin();
John McCall5808ce42011-02-03 08:15:49 +00002165 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00002166 }
2167
John McCall5808ce42011-02-03 08:15:49 +00002168 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCallaa81e162009-12-01 22:10:20 +00002169 /*OpLoc*/ SourceLocation(),
2170 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00002171 SS,
2172 /*FirstQualifierInScope*/ 0,
2173 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00002174}
2175
John McCallf7a1a742009-11-24 19:00:30 +00002176bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002177 const LookupResult &R,
2178 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002179 // Only when used directly as the postfix-expression of a call.
2180 if (!HasTrailingLParen)
2181 return false;
2182
2183 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002184 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002185 return false;
2186
2187 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002188 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002189 return false;
2190
2191 // Turn off ADL when we find certain kinds of declarations during
2192 // normal lookup:
2193 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2194 NamedDecl *D = *I;
2195
2196 // C++0x [basic.lookup.argdep]p3:
2197 // -- a declaration of a class member
2198 // Since using decls preserve this property, we check this on the
2199 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002200 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002201 return false;
2202
2203 // C++0x [basic.lookup.argdep]p3:
2204 // -- a block-scope function declaration that is not a
2205 // using-declaration
2206 // NOTE: we also trigger this for function templates (in fact, we
2207 // don't check the decl type at all, since all other decl types
2208 // turn off ADL anyway).
2209 if (isa<UsingShadowDecl>(D))
2210 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2211 else if (D->getDeclContext()->isFunctionOrMethod())
2212 return false;
2213
2214 // C++0x [basic.lookup.argdep]p3:
2215 // -- a declaration that is neither a function or a function
2216 // template
2217 // And also for builtin functions.
2218 if (isa<FunctionDecl>(D)) {
2219 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2220
2221 // But also builtin functions.
2222 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2223 return false;
2224 } else if (!isa<FunctionTemplateDecl>(D))
2225 return false;
2226 }
2227
2228 return true;
2229}
2230
2231
John McCallba135432009-11-21 08:51:07 +00002232/// Diagnoses obvious problems with the use of the given declaration
2233/// as an expression. This is only actually called for lookups that
2234/// were not overloaded, and it doesn't promise that the declaration
2235/// will in fact be used.
2236static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2237 if (isa<TypedefDecl>(D)) {
2238 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2239 return true;
2240 }
2241
2242 if (isa<ObjCInterfaceDecl>(D)) {
2243 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2244 return true;
2245 }
2246
2247 if (isa<NamespaceDecl>(D)) {
2248 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2249 return true;
2250 }
2251
2252 return false;
2253}
2254
John McCall60d7b3a2010-08-24 06:29:42 +00002255ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002256Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002257 LookupResult &R,
2258 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002259 // If this is a single, fully-resolved result and we don't need ADL,
2260 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002261 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002262 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2263 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002264
2265 // We only need to check the declaration if there's exactly one
2266 // result, because in the overloaded case the results can only be
2267 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002268 if (R.isSingleResult() &&
2269 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002270 return ExprError();
2271
John McCallc373d482010-01-27 01:50:18 +00002272 // Otherwise, just build an unresolved lookup expression. Suppress
2273 // any lookup-related diagnostics; we'll hash these out later, when
2274 // we've picked a target.
2275 R.suppressDiagnostics();
2276
John McCallba135432009-11-21 08:51:07 +00002277 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002278 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00002279 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002280 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002281 NeedsADL, R.isOverloadedResult(),
2282 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002283
2284 return Owned(ULE);
2285}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002286
John McCallba135432009-11-21 08:51:07 +00002287/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002288ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002289Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002290 const DeclarationNameInfo &NameInfo,
2291 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002292 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002293 assert(!isa<FunctionTemplateDecl>(D) &&
2294 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002295
Abramo Bagnara25777432010-08-11 22:01:17 +00002296 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002297 if (CheckDeclInExpr(*this, Loc, D))
2298 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002299
Douglas Gregor9af2f522009-12-01 16:58:18 +00002300 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2301 // Specifically diagnose references to class templates that are missing
2302 // a template argument list.
2303 Diag(Loc, diag::err_template_decl_ref)
2304 << Template << SS.getRange();
2305 Diag(Template->getLocation(), diag::note_template_decl_here);
2306 return ExprError();
2307 }
2308
2309 // Make sure that we're referring to a value.
2310 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2311 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002312 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002313 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002314 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002315 return ExprError();
2316 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002317
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002318 // Check whether this declaration can be used. Note that we suppress
2319 // this check when we're going to perform argument-dependent lookup
2320 // on this function name, because this might not be the function
2321 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002322 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002323 return ExprError();
2324
Steve Naroffdd972f22008-09-05 22:11:13 +00002325 // Only create DeclRefExpr's for valid Decl's.
2326 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002327 return ExprError();
2328
John McCall5808ce42011-02-03 08:15:49 +00002329 // Handle members of anonymous structs and unions. If we got here,
2330 // and the reference is to a class member indirect field, then this
2331 // must be the subject of a pointer-to-member expression.
2332 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2333 if (!indirectField->isCXXClassMember())
2334 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2335 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002336
Chris Lattner639e2d32008-10-20 05:16:36 +00002337 // If the identifier reference is inside a block, and it refers to a value
2338 // that is outside the block, create a BlockDeclRefExpr instead of a
2339 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2340 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002341 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002342 // We do not do this for things like enum constants, global variables, etc,
2343 // as they do not get snapshotted.
2344 //
John McCall6b5a61b2011-02-07 10:33:21 +00002345 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002346 case CR_Error:
2347 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002348
John McCall469a1eb2011-02-02 13:00:07 +00002349 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002350 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2351 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2352
2353 case CR_CaptureByRef:
2354 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2355 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002356
2357 case CR_NoCapture: {
2358 // If this reference is not in a block or if the referenced
2359 // variable is within the block, create a normal DeclRefExpr.
2360
2361 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002362 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002363
2364 switch (D->getKind()) {
2365 // Ignore all the non-ValueDecl kinds.
2366#define ABSTRACT_DECL(kind)
2367#define VALUE(type, base)
2368#define DECL(type, base) \
2369 case Decl::type:
2370#include "clang/AST/DeclNodes.inc"
2371 llvm_unreachable("invalid value decl kind");
2372 return ExprError();
2373
2374 // These shouldn't make it here.
2375 case Decl::ObjCAtDefsField:
2376 case Decl::ObjCIvar:
2377 llvm_unreachable("forming non-member reference to ivar?");
2378 return ExprError();
2379
2380 // Enum constants are always r-values and never references.
2381 // Unresolved using declarations are dependent.
2382 case Decl::EnumConstant:
2383 case Decl::UnresolvedUsingValue:
2384 valueKind = VK_RValue;
2385 break;
2386
2387 // Fields and indirect fields that got here must be for
2388 // pointer-to-member expressions; we just call them l-values for
2389 // internal consistency, because this subexpression doesn't really
2390 // exist in the high-level semantics.
2391 case Decl::Field:
2392 case Decl::IndirectField:
2393 assert(getLangOptions().CPlusPlus &&
2394 "building reference to field in C?");
2395
2396 // These can't have reference type in well-formed programs, but
2397 // for internal consistency we do this anyway.
2398 type = type.getNonReferenceType();
2399 valueKind = VK_LValue;
2400 break;
2401
2402 // Non-type template parameters are either l-values or r-values
2403 // depending on the type.
2404 case Decl::NonTypeTemplateParm: {
2405 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2406 type = reftype->getPointeeType();
2407 valueKind = VK_LValue; // even if the parameter is an r-value reference
2408 break;
2409 }
2410
2411 // For non-references, we need to strip qualifiers just in case
2412 // the template parameter was declared as 'const int' or whatever.
2413 valueKind = VK_RValue;
2414 type = type.getUnqualifiedType();
2415 break;
2416 }
2417
2418 case Decl::Var:
2419 // In C, "extern void blah;" is valid and is an r-value.
2420 if (!getLangOptions().CPlusPlus &&
2421 !type.hasQualifiers() &&
2422 type->isVoidType()) {
2423 valueKind = VK_RValue;
2424 break;
2425 }
2426 // fallthrough
2427
2428 case Decl::ImplicitParam:
2429 case Decl::ParmVar:
2430 // These are always l-values.
2431 valueKind = VK_LValue;
2432 type = type.getNonReferenceType();
2433 break;
2434
2435 case Decl::Function: {
2436 // Functions are l-values in C++.
2437 if (getLangOptions().CPlusPlus) {
2438 valueKind = VK_LValue;
2439 break;
2440 }
2441
2442 // C99 DR 316 says that, if a function type comes from a
2443 // function definition (without a prototype), that type is only
2444 // used for checking compatibility. Therefore, when referencing
2445 // the function, we pretend that we don't have the full function
2446 // type.
2447 if (!cast<FunctionDecl>(VD)->hasPrototype())
2448 if (const FunctionProtoType *proto = type->getAs<FunctionProtoType>())
2449 type = Context.getFunctionNoProtoType(proto->getResultType(),
2450 proto->getExtInfo());
2451
2452 // Functions are r-values in C.
2453 valueKind = VK_RValue;
2454 break;
2455 }
2456
2457 case Decl::CXXMethod:
2458 // C++ methods are l-values if static, r-values if non-static.
2459 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2460 valueKind = VK_LValue;
2461 break;
2462 }
2463 // fallthrough
2464
2465 case Decl::CXXConversion:
2466 case Decl::CXXDestructor:
2467 case Decl::CXXConstructor:
2468 valueKind = VK_RValue;
2469 break;
2470 }
2471
2472 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2473 }
2474
John McCall469a1eb2011-02-02 13:00:07 +00002475 }
John McCallf89e55a2010-11-18 06:31:45 +00002476
John McCall6b5a61b2011-02-07 10:33:21 +00002477 llvm_unreachable("unknown capture result");
2478 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002479}
2480
John McCall60d7b3a2010-08-24 06:29:42 +00002481ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlcd965b92009-01-18 18:53:16 +00002482 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002483 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002484
Reid Spencer5f016e22007-07-11 17:01:13 +00002485 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002486 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002487 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2488 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2489 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002490 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002491
Chris Lattnerfa28b302008-01-12 08:14:25 +00002492 // Pre-defined identifiers are of type char[x], where x is the length of the
2493 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002494
Anders Carlsson3a082d82009-09-08 18:24:21 +00002495 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002496 if (!currentDecl && getCurBlock())
2497 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002498 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002499 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002500 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002501 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002502
Anders Carlsson773f3972009-09-11 01:22:35 +00002503 QualType ResTy;
2504 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2505 ResTy = Context.DependentTy;
2506 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002507 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002508
Anders Carlsson773f3972009-09-11 01:22:35 +00002509 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002510 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002511 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2512 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002513 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002514}
2515
John McCall60d7b3a2010-08-24 06:29:42 +00002516ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002517 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002518 bool Invalid = false;
2519 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2520 if (Invalid)
2521 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002522
Benjamin Kramerddeea562010-02-27 13:44:12 +00002523 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2524 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002525 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002526 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002527
Chris Lattnere8337df2009-12-30 21:19:39 +00002528 QualType Ty;
2529 if (!getLangOptions().CPlusPlus)
2530 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2531 else if (Literal.isWide())
2532 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002533 else if (Literal.isMultiChar())
2534 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002535 else
2536 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002537
Sebastian Redle91b3bc2009-01-20 22:23:13 +00002538 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2539 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00002540 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002541}
2542
John McCall60d7b3a2010-08-24 06:29:42 +00002543ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002544 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002545 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2546 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002547 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00002548 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002549 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002550 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002551 }
Ted Kremenek28396602009-01-13 23:19:12 +00002552
Reid Spencer5f016e22007-07-11 17:01:13 +00002553 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002554 // Add padding so that NumericLiteralParser can overread by one character.
2555 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002556 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002557
Reid Spencer5f016e22007-07-11 17:01:13 +00002558 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002559 bool Invalid = false;
2560 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2561 if (Invalid)
2562 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002563
Mike Stump1eb44332009-09-09 15:08:12 +00002564 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002565 Tok.getLocation(), PP);
2566 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002567 return ExprError();
2568
Chris Lattner5d661452007-08-26 03:42:43 +00002569 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002570
Chris Lattner5d661452007-08-26 03:42:43 +00002571 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002572 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002573 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002574 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002575 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002576 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002577 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002578 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002579
2580 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2581
John McCall94c939d2009-12-24 09:08:04 +00002582 using llvm::APFloat;
2583 APFloat Val(Format);
2584
2585 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002586
2587 // Overflow is always an error, but underflow is only an error if
2588 // we underflowed to zero (APFloat reports denormals as underflow).
2589 if ((result & APFloat::opOverflow) ||
2590 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002591 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002592 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002593 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002594 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002595 APFloat::getLargest(Format).toString(buffer);
2596 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002597 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002598 APFloat::getSmallest(Format).toString(buffer);
2599 }
2600
2601 Diag(Tok.getLocation(), diagnostic)
2602 << Ty
2603 << llvm::StringRef(buffer.data(), buffer.size());
2604 }
2605
2606 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002607 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002608
Peter Collingbourne09821362010-12-04 01:50:56 +00002609 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2610 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2611
Chris Lattner5d661452007-08-26 03:42:43 +00002612 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002613 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002614 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002615 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002616
Neil Boothb9449512007-08-29 22:00:19 +00002617 // long long is a C99 feature.
2618 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002619 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002620 Diag(Tok.getLocation(), diag::ext_longlong);
2621
Reid Spencer5f016e22007-07-11 17:01:13 +00002622 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00002623 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002624
Reid Spencer5f016e22007-07-11 17:01:13 +00002625 if (Literal.GetIntegerValue(ResultVal)) {
2626 // If this value didn't fit into uintmax_t, warn and force to ull.
2627 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002628 Ty = Context.UnsignedLongLongTy;
2629 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002630 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002631 } else {
2632 // If this value fits into a ULL, try to figure out what else it fits into
2633 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002634
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2636 // be an unsigned int.
2637 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2638
2639 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002640 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002641 if (!Literal.isLong && !Literal.isLongLong) {
2642 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002643 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002644
Reid Spencer5f016e22007-07-11 17:01:13 +00002645 // Does it fit in a unsigned int?
2646 if (ResultVal.isIntN(IntSize)) {
2647 // Does it fit in a signed int?
2648 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002649 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002650 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002651 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002652 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002653 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002654 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002655
Reid Spencer5f016e22007-07-11 17:01:13 +00002656 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002657 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002658 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002659
Reid Spencer5f016e22007-07-11 17:01:13 +00002660 // Does it fit in a unsigned long?
2661 if (ResultVal.isIntN(LongSize)) {
2662 // Does it fit in a signed long?
2663 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002664 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002665 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002666 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002667 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002668 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002669 }
2670
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002672 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002673 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002674
Reid Spencer5f016e22007-07-11 17:01:13 +00002675 // Does it fit in a unsigned long long?
2676 if (ResultVal.isIntN(LongLongSize)) {
2677 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002678 // To be compatible with MSVC, hex integer literals ending with the
2679 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002680 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2681 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002682 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002683 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002684 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002685 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002686 }
2687 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002688
Reid Spencer5f016e22007-07-11 17:01:13 +00002689 // If we still couldn't decide a type, we probably have something that
2690 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002691 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002692 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002693 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002694 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002695 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002696
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002697 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002698 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002700 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002701 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002702
Chris Lattner5d661452007-08-26 03:42:43 +00002703 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2704 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002705 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002706 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002707
2708 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002709}
2710
John McCall60d7b3a2010-08-24 06:29:42 +00002711ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00002712 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002713 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002714 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002715}
2716
2717/// The UsualUnaryConversions() function is *not* called by this routine.
2718/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00002719bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00002720 SourceLocation OpLoc,
John McCall2a984ca2010-10-12 00:20:44 +00002721 SourceRange ExprRange,
Sebastian Redl05189992008-11-11 17:56:53 +00002722 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00002723 if (exprType->isDependentType())
2724 return false;
2725
Sebastian Redl5d484e82009-11-23 17:18:46 +00002726 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2727 // the result is the size of the referenced type."
2728 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2729 // result shall be the alignment of the referenced type."
2730 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2731 exprType = Ref->getPointeeType();
2732
Reid Spencer5f016e22007-07-11 17:01:13 +00002733 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00002734 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002735 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002736 if (isSizeof)
2737 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2738 return false;
2739 }
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Chris Lattner1efaa952009-04-24 00:30:45 +00002741 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002742 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002743 Diag(OpLoc, diag::ext_sizeof_void_type)
2744 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00002745 return false;
2746 }
Mike Stump1eb44332009-09-09 15:08:12 +00002747
Chris Lattner1efaa952009-04-24 00:30:45 +00002748 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002749 PDiag(diag::err_sizeof_alignof_incomplete_type)
2750 << int(!isSizeof) << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002751 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002752
Chris Lattner1efaa952009-04-24 00:30:45 +00002753 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCallc12c5bb2010-05-15 11:32:37 +00002754 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002755 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00002756 << exprType << isSizeof << ExprRange;
2757 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00002758 }
Mike Stump1eb44332009-09-09 15:08:12 +00002759
Chris Lattner1efaa952009-04-24 00:30:45 +00002760 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002761}
2762
John McCall2a984ca2010-10-12 00:20:44 +00002763static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2764 SourceRange ExprRange) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002765 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002766
Mike Stump1eb44332009-09-09 15:08:12 +00002767 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002768 if (isa<DeclRefExpr>(E))
2769 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002770
2771 // Cannot know anything else if the expression is dependent.
2772 if (E->isTypeDependent())
2773 return false;
2774
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002775 if (E->getBitField()) {
John McCall2a984ca2010-10-12 00:20:44 +00002776 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002777 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002778 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002779
2780 // Alignment of a field access is always okay, so long as it isn't a
2781 // bit-field.
2782 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002783 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002784 return false;
2785
John McCall2a984ca2010-10-12 00:20:44 +00002786 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
Chris Lattner31e21e02009-01-24 20:17:12 +00002787}
2788
Douglas Gregorba498172009-03-13 21:01:28 +00002789/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002790ExprResult
John McCalla93c9342009-12-07 02:54:59 +00002791Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00002792 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002793 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002794 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002795 return ExprError();
2796
John McCalla93c9342009-12-07 02:54:59 +00002797 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002798
Douglas Gregorba498172009-03-13 21:01:28 +00002799 if (!T->isDependentType() &&
2800 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2801 return ExprError();
2802
2803 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00002804 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00002805 Context.getSizeType(), OpLoc,
2806 R.getEnd()));
2807}
2808
2809/// \brief Build a sizeof or alignof expression given an expression
2810/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002811ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00002812Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002813 bool isSizeOf, SourceRange R) {
2814 // Verify that the operand is valid.
2815 bool isInvalid = false;
2816 if (E->isTypeDependent()) {
2817 // Delay type-checking for type-dependent expressions.
2818 } else if (!isSizeOf) {
John McCall2a984ca2010-10-12 00:20:44 +00002819 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002820 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00002821 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2822 isInvalid = true;
John McCall2cd11fe2010-10-12 02:09:17 +00002823 } else if (E->getType()->isPlaceholderType()) {
2824 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2825 if (PE.isInvalid()) return ExprError();
2826 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
Douglas Gregorba498172009-03-13 21:01:28 +00002827 } else {
2828 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2829 }
2830
2831 if (isInvalid)
2832 return ExprError();
2833
2834 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2835 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2836 Context.getSizeType(), OpLoc,
2837 R.getEnd()));
2838}
2839
Sebastian Redl05189992008-11-11 17:56:53 +00002840/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2841/// the same for @c alignof and @c __alignof
2842/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00002843ExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00002844Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2845 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002846 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002847 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002848
Sebastian Redl05189992008-11-11 17:56:53 +00002849 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002850 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00002851 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
John McCalla93c9342009-12-07 02:54:59 +00002852 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002853 }
Sebastian Redl05189992008-11-11 17:56:53 +00002854
Douglas Gregorba498172009-03-13 21:01:28 +00002855 Expr *ArgEx = (Expr *)TyOrEx;
John McCall60d7b3a2010-08-24 06:29:42 +00002856 ExprResult Result
Douglas Gregorba498172009-03-13 21:01:28 +00002857 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2858
Douglas Gregorba498172009-03-13 21:01:28 +00002859 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002860}
2861
John McCall09431682010-11-18 19:01:18 +00002862static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2863 bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00002864 if (V->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00002865 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002866
John McCallf6a16482010-12-04 03:47:34 +00002867 // _Real and _Imag are only l-values for normal l-values.
2868 if (V->getObjectKind() != OK_Ordinary)
John McCall409fa9a2010-12-06 20:48:59 +00002869 S.DefaultLvalueConversion(V);
John McCallf6a16482010-12-04 03:47:34 +00002870
Chris Lattnercc26ed72007-08-26 05:39:26 +00002871 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00002872 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002873 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002874
Chris Lattnercc26ed72007-08-26 05:39:26 +00002875 // Otherwise they pass through real integer and floating point types here.
2876 if (V->getType()->isArithmeticType())
2877 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002878
John McCall2cd11fe2010-10-12 02:09:17 +00002879 // Test for placeholders.
John McCall09431682010-11-18 19:01:18 +00002880 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall2cd11fe2010-10-12 02:09:17 +00002881 if (PR.isInvalid()) return QualType();
2882 if (PR.take() != V) {
2883 V = PR.take();
John McCall09431682010-11-18 19:01:18 +00002884 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00002885 }
2886
Chris Lattnercc26ed72007-08-26 05:39:26 +00002887 // Reject anything else.
John McCall09431682010-11-18 19:01:18 +00002888 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002889 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002890 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002891}
2892
2893
Reid Spencer5f016e22007-07-11 17:01:13 +00002894
John McCall60d7b3a2010-08-24 06:29:42 +00002895ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00002896Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002897 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00002898 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00002899 switch (Kind) {
2900 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00002901 case tok::plusplus: Opc = UO_PostInc; break;
2902 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002903 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002904
John McCall9ae2f072010-08-23 23:25:46 +00002905 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002906}
2907
John McCall09431682010-11-18 19:01:18 +00002908/// Expressions of certain arbitrary types are forbidden by C from
2909/// having l-value type. These are:
2910/// - 'void', but not qualified void
2911/// - function types
2912///
2913/// The exact rule here is C99 6.3.2.1:
2914/// An lvalue is an expression with an object type or an incomplete
2915/// type other than void.
2916static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2917 return ((T->isVoidType() && !T.hasQualifiers()) ||
2918 T->isFunctionType());
2919}
2920
John McCall60d7b3a2010-08-24 06:29:42 +00002921ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002922Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2923 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00002924 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00002925 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00002926 if (Result.isInvalid()) return ExprError();
2927 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002928
John McCall9ae2f072010-08-23 23:25:46 +00002929 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00002930
Douglas Gregor337c6b92008-11-19 17:17:41 +00002931 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002932 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002933 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00002934 Context.DependentTy,
2935 VK_LValue, OK_Ordinary,
2936 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002937 }
2938
Mike Stump1eb44332009-09-09 15:08:12 +00002939 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002940 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00002941 LHSExp->getType()->isEnumeralType() ||
2942 RHSExp->getType()->isRecordType() ||
2943 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00002944 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00002945 }
2946
John McCall9ae2f072010-08-23 23:25:46 +00002947 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00002948}
2949
2950
John McCall60d7b3a2010-08-24 06:29:42 +00002951ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002952Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2953 Expr *Idx, SourceLocation RLoc) {
2954 Expr *LHSExp = Base;
2955 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00002956
Chris Lattner12d9ff62007-07-16 00:14:47 +00002957 // Perform default conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002958 if (!LHSExp->getType()->getAs<VectorType>())
2959 DefaultFunctionArrayLvalueConversion(LHSExp);
2960 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002961
Chris Lattner12d9ff62007-07-16 00:14:47 +00002962 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00002963 ExprValueKind VK = VK_LValue;
2964 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00002965
Reid Spencer5f016e22007-07-11 17:01:13 +00002966 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002967 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00002968 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00002969 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00002970 Expr *BaseExpr, *IndexExpr;
2971 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00002972 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2973 BaseExpr = LHSExp;
2974 IndexExpr = RHSExp;
2975 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002976 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00002977 BaseExpr = LHSExp;
2978 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002979 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002980 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00002981 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00002982 BaseExpr = RHSExp;
2983 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002984 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002985 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002986 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002987 BaseExpr = LHSExp;
2988 IndexExpr = RHSExp;
2989 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002990 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002991 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002992 // Handle the uncommon case of "123[Ptr]".
2993 BaseExpr = RHSExp;
2994 IndexExpr = LHSExp;
2995 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00002996 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00002997 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00002998 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00002999 VK = LHSExp->getValueKind();
3000 if (VK != VK_RValue)
3001 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003002
Chris Lattner12d9ff62007-07-16 00:14:47 +00003003 // FIXME: need to deal with const...
3004 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003005 } else if (LHSTy->isArrayType()) {
3006 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003007 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003008 // wasn't promoted because of the C90 rule that doesn't
3009 // allow promoting non-lvalue arrays. Warn, then
3010 // force the promotion here.
3011 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3012 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003013 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCall2de56d12010-08-25 11:45:40 +00003014 CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003015 LHSTy = LHSExp->getType();
3016
3017 BaseExpr = LHSExp;
3018 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003019 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003020 } else if (RHSTy->isArrayType()) {
3021 // Same as previous, except for 123[f().a] case
3022 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3023 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003024 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCall2de56d12010-08-25 11:45:40 +00003025 CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003026 RHSTy = RHSExp->getType();
3027
3028 BaseExpr = RHSExp;
3029 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003030 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003031 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003032 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3033 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003034 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003035 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003036 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003037 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3038 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003039
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003040 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003041 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3042 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003043 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3044
Douglas Gregore7450f52009-03-24 19:52:54 +00003045 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003046 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3047 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003048 // incomplete types are not object types.
3049 if (ResultType->isFunctionType()) {
3050 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3051 << ResultType << BaseExpr->getSourceRange();
3052 return ExprError();
3053 }
Mike Stump1eb44332009-09-09 15:08:12 +00003054
Abramo Bagnara46358452010-09-13 06:50:07 +00003055 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3056 // GNU extension: subscripting on pointer to void
3057 Diag(LLoc, diag::ext_gnu_void_ptr)
3058 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003059
3060 // C forbids expressions of unqualified void type from being l-values.
3061 // See IsCForbiddenLValueType.
3062 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003063 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003064 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003065 PDiag(diag::err_subscript_incomplete_type)
3066 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003067 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003068
Chris Lattner1efaa952009-04-24 00:30:45 +00003069 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003070 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003071 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3072 << ResultType << BaseExpr->getSourceRange();
3073 return ExprError();
3074 }
Mike Stump1eb44332009-09-09 15:08:12 +00003075
John McCall09431682010-11-18 19:01:18 +00003076 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3077 !IsCForbiddenLValueType(Context, ResultType));
3078
Mike Stumpeed9cac2009-02-19 03:04:26 +00003079 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003080 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003081}
3082
John McCall09431682010-11-18 19:01:18 +00003083/// Check an ext-vector component access expression.
3084///
3085/// VK should be set in advance to the value kind of the base
3086/// expression.
3087static QualType
3088CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3089 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003090 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00003091 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3092 // see FIXME there.
3093 //
3094 // FIXME: This logic can be greatly simplified by splitting it along
3095 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00003096 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00003097
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003098 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00003099 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003100
Mike Stumpeed9cac2009-02-19 03:04:26 +00003101 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00003102 // special names that indicate a subset of exactly half the elements are
3103 // to be selected.
3104 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003105
Nate Begeman353417a2009-01-18 01:47:54 +00003106 // This flag determines whether or not CompName has an 's' char prefix,
3107 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00003108 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00003109
John McCall09431682010-11-18 19:01:18 +00003110 bool HasRepeated = false;
3111 bool HasIndex[16] = {};
3112
3113 int Idx;
3114
Nate Begeman8a997642008-05-09 06:41:27 +00003115 // Check that we've found one of the special components, or that the component
3116 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003117 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00003118 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3119 HalvingSwizzle = true;
John McCall09431682010-11-18 19:01:18 +00003120 } else if (!HexSwizzle &&
3121 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3122 do {
3123 if (HasIndex[Idx]) HasRepeated = true;
3124 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003125 compStr++;
John McCall09431682010-11-18 19:01:18 +00003126 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3127 } else {
3128 if (HexSwizzle) compStr++;
3129 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3130 if (HasIndex[Idx]) HasRepeated = true;
3131 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003132 compStr++;
John McCall09431682010-11-18 19:01:18 +00003133 }
Chris Lattner88dca042007-08-02 22:33:49 +00003134 }
Nate Begeman353417a2009-01-18 01:47:54 +00003135
Mike Stumpeed9cac2009-02-19 03:04:26 +00003136 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003137 // We didn't get to the end of the string. This means the component names
3138 // didn't come from the same set *or* we encountered an illegal name.
John McCall09431682010-11-18 19:01:18 +00003139 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00003140 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003141 return QualType();
3142 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003143
Nate Begeman353417a2009-01-18 01:47:54 +00003144 // Ensure no component accessor exceeds the width of the vector type it
3145 // operates on.
3146 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00003147 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003148
3149 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003150 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00003151
3152 while (*compStr) {
3153 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall09431682010-11-18 19:01:18 +00003154 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begeman353417a2009-01-18 01:47:54 +00003155 << baseType << SourceRange(CompLoc);
3156 return QualType();
3157 }
3158 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003159 }
Nate Begeman8a997642008-05-09 06:41:27 +00003160
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003161 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003162 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003163 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00003164 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00003165 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00003166 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00003167 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00003168 if (HexSwizzle)
3169 CompSize--;
3170
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003171 if (CompSize == 1)
3172 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003173
John McCall09431682010-11-18 19:01:18 +00003174 if (HasRepeated) VK = VK_RValue;
3175
3176 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003177 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00003178 // diagostics look bad. We want extended vector types to appear built-in.
John McCall09431682010-11-18 19:01:18 +00003179 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3180 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3181 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00003182 }
3183 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003184}
3185
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003186static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003187 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003188 const Selector &Sel,
3189 ASTContext &Context) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003190 if (Member)
3191 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3192 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003193 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003194 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00003195
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003196 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3197 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003198 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3199 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003200 return D;
3201 }
3202 return 0;
3203}
3204
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003205static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3206 IdentifierInfo *Member,
3207 const Selector &Sel,
3208 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003209 // Check protocols on qualified interfaces.
3210 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003211 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003212 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003213 if (Member)
3214 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3215 GDecl = PD;
3216 break;
3217 }
3218 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003219 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003220 GDecl = OMD;
3221 break;
3222 }
3223 }
3224 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003225 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003226 E = QIdTy->qual_end(); I != E; ++I) {
3227 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003228 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3229 Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003230 if (GDecl)
3231 return GDecl;
3232 }
3233 }
3234 return GDecl;
3235}
Chris Lattner76a642f2009-02-15 22:43:40 +00003236
John McCall60d7b3a2010-08-24 06:29:42 +00003237ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003238Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCallaa81e162009-12-01 22:10:20 +00003239 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003240 const CXXScopeSpec &SS,
3241 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003242 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003243 const TemplateArgumentListInfo *TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00003244 // Even in dependent contexts, try to diagnose base expressions with
3245 // obviously wrong types, e.g.:
3246 //
3247 // T* t;
3248 // t.f;
3249 //
3250 // In Obj-C++, however, the above expression is valid, since it could be
3251 // accessing the 'f' property if T is an Obj-C interface. The extra check
3252 // allows this, while still reporting an error if T is a struct pointer.
3253 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00003254 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00003255 if (PT && (!getLangOptions().ObjC1 ||
3256 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00003257 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnara25777432010-08-11 22:01:17 +00003258 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00003259 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00003260 return ExprError();
3261 }
3262 }
3263
Abramo Bagnara25777432010-08-11 22:01:17 +00003264 assert(BaseType->isDependentType() ||
3265 NameInfo.getName().isDependentName() ||
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003266 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00003267
3268 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3269 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00003270 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003271 IsArrow, OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003272 SS.getScopeRep(),
John McCall129e2df2009-11-30 22:42:35 +00003273 SS.getRange(),
3274 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003275 NameInfo, TemplateArgs));
John McCall129e2df2009-11-30 22:42:35 +00003276}
3277
3278/// We know that the given qualified member reference points only to
3279/// declarations which do not belong to the static type of the base
3280/// expression. Diagnose the problem.
3281static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3282 Expr *BaseExpr,
3283 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003284 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00003285 NamedDecl *rep,
3286 const DeclarationNameInfo &nameInfo) {
John McCall2f841ba2009-12-02 03:53:29 +00003287 // If this is an implicit member access, use a different set of
3288 // diagnostics.
3289 if (!BaseExpr)
John McCall5808ce42011-02-03 08:15:49 +00003290 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003291
John McCall5808ce42011-02-03 08:15:49 +00003292 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3293 << SS.getRange() << rep << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00003294}
3295
3296// Check whether the declarations we found through a nested-name
3297// specifier in a member expression are actually members of the base
3298// type. The restriction here is:
3299//
3300// C++ [expr.ref]p2:
3301// ... In these cases, the id-expression shall name a
3302// member of the class or of one of its base classes.
3303//
3304// So it's perfectly legitimate for the nested-name specifier to name
3305// an unrelated class, and for us to find an overload set including
3306// decls from classes which are not superclasses, as long as the decl
3307// we actually pick through overload resolution is from a superclass.
3308bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3309 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003310 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003311 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00003312 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3313 if (!BaseRT) {
3314 // We can't check this yet because the base type is still
3315 // dependent.
3316 assert(BaseType->isDependentType());
3317 return false;
3318 }
3319 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00003320
3321 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00003322 // If this is an implicit member reference and we find a
3323 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00003324 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00003325 return false;
John McCall129e2df2009-11-30 22:42:35 +00003326
John McCallaa81e162009-12-01 22:10:20 +00003327 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman02463762010-07-27 20:51:02 +00003328 DeclContext *DC = (*I)->getDeclContext();
3329 while (DC->isTransparentContext())
3330 DC = DC->getParent();
John McCallaa81e162009-12-01 22:10:20 +00003331
Douglas Gregor9d4bb942010-07-28 22:27:52 +00003332 if (!DC->isRecord())
3333 continue;
3334
John McCallaa81e162009-12-01 22:10:20 +00003335 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman02463762010-07-27 20:51:02 +00003336 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCallaa81e162009-12-01 22:10:20 +00003337
3338 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3339 return false;
3340 }
3341
John McCall5808ce42011-02-03 08:15:49 +00003342 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3343 R.getRepresentativeDecl(),
3344 R.getLookupNameInfo());
John McCallaa81e162009-12-01 22:10:20 +00003345 return true;
3346}
3347
3348static bool
3349LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3350 SourceRange BaseRange, const RecordType *RTy,
John McCallad00b772010-06-16 08:42:20 +00003351 SourceLocation OpLoc, CXXScopeSpec &SS,
3352 bool HasTemplateArgs) {
John McCallaa81e162009-12-01 22:10:20 +00003353 RecordDecl *RDecl = RTy->getDecl();
3354 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003355 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00003356 << BaseRange))
3357 return true;
3358
John McCallad00b772010-06-16 08:42:20 +00003359 if (HasTemplateArgs) {
3360 // LookupTemplateName doesn't expect these both to exist simultaneously.
3361 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3362
3363 bool MOUS;
3364 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3365 return false;
3366 }
3367
John McCallaa81e162009-12-01 22:10:20 +00003368 DeclContext *DC = RDecl;
3369 if (SS.isSet()) {
3370 // If the member name was a qualified-id, look into the
3371 // nested-name-specifier.
3372 DC = SemaRef.computeDeclContext(SS, false);
3373
John McCall77bb1aa2010-05-01 00:40:08 +00003374 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCall2f841ba2009-12-02 03:53:29 +00003375 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3376 << SS.getRange() << DC;
3377 return true;
3378 }
3379
John McCallaa81e162009-12-01 22:10:20 +00003380 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003381
John McCallaa81e162009-12-01 22:10:20 +00003382 if (!isa<TypeDecl>(DC)) {
3383 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3384 << DC << SS.getRange();
3385 return true;
John McCall129e2df2009-11-30 22:42:35 +00003386 }
3387 }
3388
John McCallaa81e162009-12-01 22:10:20 +00003389 // The record definition is complete, now look up the member.
3390 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00003391
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003392 if (!R.empty())
3393 return false;
3394
3395 // We didn't find anything with the given name, so try to correct
3396 // for typos.
3397 DeclarationName Name = R.getLookupName();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003398 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00003399 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003400 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3401 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3402 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003403 << FixItHint::CreateReplacement(R.getNameLoc(),
3404 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003405 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3406 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3407 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003408 return false;
3409 } else {
3410 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003411 R.setLookupName(Name);
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003412 }
3413
John McCall129e2df2009-11-30 22:42:35 +00003414 return false;
3415}
3416
John McCall60d7b3a2010-08-24 06:29:42 +00003417ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003418Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003419 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003420 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003421 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003422 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003423 const TemplateArgumentListInfo *TemplateArgs) {
John McCall2f841ba2009-12-02 03:53:29 +00003424 if (BaseType->isDependentType() ||
3425 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall9ae2f072010-08-23 23:25:46 +00003426 return ActOnDependentMemberExpr(Base, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003427 IsArrow, OpLoc,
3428 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003429 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003430
Abramo Bagnara25777432010-08-11 22:01:17 +00003431 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00003432
John McCallaa81e162009-12-01 22:10:20 +00003433 // Implicit member accesses.
3434 if (!Base) {
3435 QualType RecordTy = BaseType;
3436 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3437 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3438 RecordTy->getAs<RecordType>(),
John McCallad00b772010-06-16 08:42:20 +00003439 OpLoc, SS, TemplateArgs != 0))
John McCallaa81e162009-12-01 22:10:20 +00003440 return ExprError();
3441
3442 // Explicit member accesses.
3443 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00003444 ExprResult Result =
John McCallaa81e162009-12-01 22:10:20 +00003445 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCalld226f652010-08-21 09:40:31 +00003446 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCallaa81e162009-12-01 22:10:20 +00003447
3448 if (Result.isInvalid()) {
3449 Owned(Base);
3450 return ExprError();
3451 }
3452
3453 if (Result.get())
3454 return move(Result);
Sebastian Redlf3e63372010-05-07 09:25:11 +00003455
3456 // LookupMemberExpr can modify Base, and thus change BaseType
3457 BaseType = Base->getType();
John McCall129e2df2009-11-30 22:42:35 +00003458 }
3459
John McCall9ae2f072010-08-23 23:25:46 +00003460 return BuildMemberReferenceExpr(Base, BaseType,
John McCallc2233c52010-01-15 08:34:02 +00003461 OpLoc, IsArrow, SS, FirstQualifierInScope,
3462 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003463}
3464
John McCall60d7b3a2010-08-24 06:29:42 +00003465ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003466Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCallaa81e162009-12-01 22:10:20 +00003467 SourceLocation OpLoc, bool IsArrow,
3468 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00003469 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00003470 LookupResult &R,
Douglas Gregor06a9f362010-05-01 20:49:11 +00003471 const TemplateArgumentListInfo *TemplateArgs,
3472 bool SuppressQualifierCheck) {
John McCallaa81e162009-12-01 22:10:20 +00003473 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00003474 if (IsArrow) {
3475 assert(BaseType->isPointerType());
3476 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3477 }
John McCall161755a2010-04-06 21:38:20 +00003478 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00003479
John McCall9ae2f072010-08-23 23:25:46 +00003480 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara25777432010-08-11 22:01:17 +00003481 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3482 DeclarationName MemberName = MemberNameInfo.getName();
3483 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall129e2df2009-11-30 22:42:35 +00003484
3485 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00003486 return ExprError();
3487
John McCall129e2df2009-11-30 22:42:35 +00003488 if (R.empty()) {
3489 // Rederive where we looked up.
3490 DeclContext *DC = (SS.isSet()
3491 ? computeDeclContext(SS, false)
3492 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00003493
John McCall129e2df2009-11-30 22:42:35 +00003494 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00003495 << MemberName << DC
3496 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00003497 return ExprError();
3498 }
3499
John McCallc2233c52010-01-15 08:34:02 +00003500 // Diagnose lookups that find only declarations from a non-base
3501 // type. This is possible for either qualified lookups (which may
3502 // have been qualified with an unrelated type) or implicit member
3503 // expressions (which were found with unqualified lookup and thus
3504 // may have come from an enclosing scope). Note that it's okay for
3505 // lookup to find declarations from a non-base type as long as those
3506 // aren't the ones picked by overload resolution.
3507 if ((SS.isSet() || !BaseExpr ||
3508 (isa<CXXThisExpr>(BaseExpr) &&
3509 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00003510 !SuppressQualifierCheck &&
John McCallc2233c52010-01-15 08:34:02 +00003511 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00003512 return ExprError();
3513
3514 // Construct an unresolved result if we in fact got an unresolved
3515 // result.
3516 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallc373d482010-01-27 01:50:18 +00003517 // Suppress any lookup-related diagnostics; we'll do these when we
3518 // pick a member.
3519 R.suppressDiagnostics();
3520
John McCall129e2df2009-11-30 22:42:35 +00003521 UnresolvedMemberExpr *MemExpr
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003522 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00003523 BaseExpr, BaseExprType,
3524 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003525 Qualifier, SS.getRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00003526 MemberNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00003527 TemplateArgs, R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00003528
3529 return Owned(MemExpr);
3530 }
3531
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003532 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00003533 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00003534 NamedDecl *MemberDecl = R.getFoundDecl();
3535
3536 // FIXME: diagnose the presence of template arguments now.
3537
3538 // If the decl being referenced had an error, return an error for this
3539 // sub-expr without emitting another error, in order to avoid cascading
3540 // error cases.
3541 if (MemberDecl->isInvalidDecl())
3542 return ExprError();
3543
John McCallaa81e162009-12-01 22:10:20 +00003544 // Handle the implicit-member-access case.
3545 if (!BaseExpr) {
3546 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00003547 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnara25777432010-08-11 22:01:17 +00003548 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCallaa81e162009-12-01 22:10:20 +00003549
Douglas Gregor828a1972010-01-07 23:12:05 +00003550 SourceLocation Loc = R.getNameLoc();
3551 if (SS.getRange().isValid())
3552 Loc = SS.getRange().getBegin();
3553 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003554 }
3555
John McCall129e2df2009-11-30 22:42:35 +00003556 bool ShouldCheckUse = true;
3557 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3558 // Don't diagnose the use of a virtual member function unless it's
3559 // explicitly qualified.
3560 if (MD->isVirtual() && !SS.isSet())
3561 ShouldCheckUse = false;
3562 }
3563
3564 // Check the use of this member.
3565 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3566 Owned(BaseExpr);
3567 return ExprError();
3568 }
3569
John McCallf6a16482010-12-04 03:47:34 +00003570 // Perform a property load on the base regardless of whether we
3571 // actually need it for the declaration.
3572 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3573 ConvertPropertyForRValue(BaseExpr);
3574
John McCalldfa1edb2010-11-23 20:48:44 +00003575 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3576 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3577 SS, FD, FoundDecl, MemberNameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003578
Francois Pichet87c2e122010-11-21 06:08:52 +00003579 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3580 // We may have found a field within an anonymous union or struct
3581 // (C++ [class.union]).
John McCall5808ce42011-02-03 08:15:49 +00003582 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCallf6a16482010-12-04 03:47:34 +00003583 BaseExpr, OpLoc);
Francois Pichet87c2e122010-11-21 06:08:52 +00003584
John McCall129e2df2009-11-30 22:42:35 +00003585 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3586 MarkDeclarationReferenced(MemberLoc, Var);
3587 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003588 Var, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003589 Var->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00003590 VK_LValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003591 }
3592
John McCallf89e55a2010-11-18 06:31:45 +00003593 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall129e2df2009-11-30 22:42:35 +00003594 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3595 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003596 MemberFn, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003597 MemberFn->getType(),
3598 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3599 OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003600 }
John McCallf89e55a2010-11-18 06:31:45 +00003601 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall129e2df2009-11-30 22:42:35 +00003602
3603 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3604 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3605 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003606 Enum, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003607 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003608 }
3609
3610 Owned(BaseExpr);
3611
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003612 // We found something that we didn't expect. Complain.
John McCall129e2df2009-11-30 22:42:35 +00003613 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnara25777432010-08-11 22:01:17 +00003614 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003615 << MemberName << BaseType << int(IsArrow);
3616 else
3617 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3618 << MemberName << BaseType << int(IsArrow);
John McCall129e2df2009-11-30 22:42:35 +00003619
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003620 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3621 << MemberName;
Douglas Gregor2b147f02010-04-25 21:15:30 +00003622 R.suppressDiagnostics();
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003623 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00003624}
3625
John McCall028d3972010-12-15 16:46:44 +00003626/// Given that normal member access failed on the given expression,
3627/// and given that the expression's type involves builtin-id or
3628/// builtin-Class, decide whether substituting in the redefinition
3629/// types would be profitable. The redefinition type is whatever
3630/// this translation unit tried to typedef to id/Class; we store
3631/// it to the side and then re-use it in places like this.
3632static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3633 const ObjCObjectPointerType *opty
3634 = base->getType()->getAs<ObjCObjectPointerType>();
3635 if (!opty) return false;
3636
3637 const ObjCObjectType *ty = opty->getObjectType();
3638
3639 QualType redef;
3640 if (ty->isObjCId()) {
3641 redef = S.Context.ObjCIdRedefinitionType;
3642 } else if (ty->isObjCClass()) {
3643 redef = S.Context.ObjCClassRedefinitionType;
3644 } else {
3645 return false;
3646 }
3647
3648 // Do the substitution as long as the redefinition type isn't just a
3649 // possibly-qualified pointer to builtin-id or builtin-Class again.
3650 opty = redef->getAs<ObjCObjectPointerType>();
3651 if (opty && !opty->getObjectType()->getInterface() != 0)
3652 return false;
3653
3654 S.ImpCastExprToType(base, redef, CK_BitCast);
3655 return true;
3656}
3657
John McCall129e2df2009-11-30 22:42:35 +00003658/// Look up the given member of the given non-type-dependent
3659/// expression. This can return in one of two ways:
3660/// * If it returns a sentinel null-but-valid result, the caller will
3661/// assume that lookup was performed and the results written into
3662/// the provided structure. It will take over from there.
3663/// * Otherwise, the returned expression will be produced in place of
3664/// an ordinary member expression.
3665///
3666/// The ObjCImpDecl bit is a gross hack that will need to be properly
3667/// fixed for ObjC++.
John McCall60d7b3a2010-08-24 06:29:42 +00003668ExprResult
John McCall129e2df2009-11-30 22:42:35 +00003669Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00003670 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003671 CXXScopeSpec &SS,
John McCalld226f652010-08-21 09:40:31 +00003672 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003673 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003674
Steve Naroff3cc4af82007-12-16 21:42:28 +00003675 // Perform default conversions.
3676 DefaultFunctionArrayConversion(BaseExpr);
John McCall5e3c67b2010-12-15 04:42:30 +00003677 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003678
Steve Naroffdfa6aae2007-07-26 03:11:44 +00003679 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00003680 assert(!BaseType->isDependentType());
3681
3682 DeclarationName MemberName = R.getLookupName();
3683 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003684
John McCall028d3972010-12-15 16:46:44 +00003685 // For later type-checking purposes, turn arrow accesses into dot
3686 // accesses. The only access type we support that doesn't follow
3687 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3688 // and those never use arrows, so this is unaffected.
3689 if (IsArrow) {
3690 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3691 BaseType = Ptr->getPointeeType();
3692 else if (const ObjCObjectPointerType *Ptr
3693 = BaseType->getAs<ObjCObjectPointerType>())
3694 BaseType = Ptr->getPointeeType();
3695 else if (BaseType->isRecordType()) {
3696 // Recover from arrow accesses to records, e.g.:
3697 // struct MyRecord foo;
3698 // foo->bar
3699 // This is actually well-formed in C++ if MyRecord has an
3700 // overloaded operator->, but that should have been dealt with
3701 // by now.
3702 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3703 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3704 << FixItHint::CreateReplacement(OpLoc, ".");
3705 IsArrow = false;
3706 } else {
3707 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3708 << BaseType << BaseExpr->getSourceRange();
3709 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003710 }
3711 }
3712
John McCall028d3972010-12-15 16:46:44 +00003713 // Handle field access to simple records.
3714 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3715 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3716 RTy, OpLoc, SS, HasTemplateArgs))
3717 return ExprError();
3718
3719 // Returning valid-but-null is how we indicate to the caller that
3720 // the lookup result was filled in.
3721 return Owned((Expr*) 0);
David Chisnall0f436562009-08-17 16:35:33 +00003722 }
John McCall129e2df2009-11-30 22:42:35 +00003723
John McCall028d3972010-12-15 16:46:44 +00003724 // Handle ivar access to Objective-C objects.
3725 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003726 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall028d3972010-12-15 16:46:44 +00003727
3728 // There are three cases for the base type:
3729 // - builtin id (qualified or unqualified)
3730 // - builtin Class (qualified or unqualified)
3731 // - an interface
3732 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3733 if (!IDecl) {
3734 // There's an implicit 'isa' ivar on all objects.
3735 // But we only actually find it this way on objects of type 'id',
3736 // apparently.
3737 if (OTy->isObjCId() && Member->isStr("isa"))
3738 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3739 Context.getObjCClassType()));
3740
3741 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3742 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3743 ObjCImpDecl, HasTemplateArgs);
3744 goto fail;
3745 }
3746
3747 ObjCInterfaceDecl *ClassDeclared;
3748 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3749
3750 if (!IV) {
3751 // Attempt to correct for typos in ivar names.
3752 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3753 LookupMemberName);
3754 if (CorrectTypo(Res, 0, 0, IDecl, false,
3755 IsArrow ? CTC_ObjCIvarLookup
3756 : CTC_ObjCPropertyLookup) &&
3757 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3758 Diag(R.getNameLoc(),
3759 diag::err_typecheck_member_reference_ivar_suggest)
3760 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3761 << FixItHint::CreateReplacement(R.getNameLoc(),
3762 IV->getNameAsString());
3763 Diag(IV->getLocation(), diag::note_previous_decl)
3764 << IV->getDeclName();
3765 } else {
3766 Res.clear();
3767 Res.setLookupName(Member);
3768
3769 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3770 << IDecl->getDeclName() << MemberName
3771 << BaseExpr->getSourceRange();
3772 return ExprError();
3773 }
3774 }
3775
3776 // If the decl being referenced had an error, return an error for this
3777 // sub-expr without emitting another error, in order to avoid cascading
3778 // error cases.
3779 if (IV->isInvalidDecl())
3780 return ExprError();
3781
3782 // Check whether we can reference this field.
3783 if (DiagnoseUseOfDecl(IV, MemberLoc))
3784 return ExprError();
3785 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3786 IV->getAccessControl() != ObjCIvarDecl::Package) {
3787 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3788 if (ObjCMethodDecl *MD = getCurMethodDecl())
3789 ClassOfMethodDecl = MD->getClassInterface();
3790 else if (ObjCImpDecl && getCurFunctionDecl()) {
3791 // Case of a c-function declared inside an objc implementation.
3792 // FIXME: For a c-style function nested inside an objc implementation
3793 // class, there is no implementation context available, so we pass
3794 // down the context as argument to this routine. Ideally, this context
3795 // need be passed down in the AST node and somehow calculated from the
3796 // AST for a function decl.
3797 if (ObjCImplementationDecl *IMPD =
3798 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3799 ClassOfMethodDecl = IMPD->getClassInterface();
3800 else if (ObjCCategoryImplDecl* CatImplClass =
3801 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3802 ClassOfMethodDecl = CatImplClass->getClassInterface();
3803 }
3804
3805 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3806 if (ClassDeclared != IDecl ||
3807 ClassOfMethodDecl != ClassDeclared)
3808 Diag(MemberLoc, diag::error_private_ivar_access)
3809 << IV->getDeclName();
3810 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3811 // @protected
3812 Diag(MemberLoc, diag::error_protected_ivar_access)
3813 << IV->getDeclName();
3814 }
3815
3816 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3817 MemberLoc, BaseExpr,
3818 IsArrow));
3819 }
3820
3821 // Objective-C property access.
3822 const ObjCObjectPointerType *OPT;
3823 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3824 // This actually uses the base as an r-value.
3825 DefaultLvalueConversion(BaseExpr);
3826 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3827
3828 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3829
3830 const ObjCObjectType *OT = OPT->getObjectType();
3831
3832 // id, with and without qualifiers.
3833 if (OT->isObjCId()) {
3834 // Check protocols on qualified interfaces.
3835 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3836 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3837 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3838 // Check the use of this declaration
3839 if (DiagnoseUseOfDecl(PD, MemberLoc))
3840 return ExprError();
3841
3842 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3843 VK_LValue,
3844 OK_ObjCProperty,
3845 MemberLoc,
3846 BaseExpr));
3847 }
3848
3849 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3850 // Check the use of this method.
3851 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3852 return ExprError();
3853 Selector SetterSel =
3854 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3855 PP.getSelectorTable(), Member);
3856 ObjCMethodDecl *SMD = 0;
3857 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3858 SetterSel, Context))
3859 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3860 QualType PType = OMD->getSendResultType();
3861
3862 ExprValueKind VK = VK_LValue;
3863 if (!getLangOptions().CPlusPlus &&
3864 IsCForbiddenLValueType(Context, PType))
3865 VK = VK_RValue;
3866 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3867
3868 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3869 VK, OK,
3870 MemberLoc, BaseExpr));
3871 }
3872 }
3873
3874 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3875 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3876 ObjCImpDecl, HasTemplateArgs);
3877
3878 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3879 << MemberName << BaseType);
3880 }
3881
3882 // 'Class', unqualified only.
3883 if (OT->isObjCClass()) {
3884 // Only works in a method declaration (??!).
3885 ObjCMethodDecl *MD = getCurMethodDecl();
3886 if (!MD) {
3887 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3888 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3889 ObjCImpDecl, HasTemplateArgs);
3890
3891 goto fail;
3892 }
3893
3894 // Also must look for a getter name which uses property syntax.
3895 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003896 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3897 ObjCMethodDecl *Getter;
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003898 if ((Getter = IFace->lookupClassMethod(Sel))) {
3899 // Check the use of this method.
3900 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3901 return ExprError();
John McCall028d3972010-12-15 16:46:44 +00003902 } else
Fariborz Jahanian74b27562010-12-03 23:37:08 +00003903 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003904 // If we found a getter then this may be a valid dot-reference, we
3905 // will look for the matching setter, in case it is needed.
3906 Selector SetterSel =
John McCall028d3972010-12-15 16:46:44 +00003907 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3908 PP.getSelectorTable(), Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003909 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3910 if (!Setter) {
3911 // If this reference is in an @implementation, also check for 'private'
3912 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00003913 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003914 }
3915 // Look through local category implementations associated with the class.
3916 if (!Setter)
3917 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003918
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003919 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3920 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003921
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003922 if (Getter || Setter) {
3923 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003924
John McCall09431682010-11-18 19:01:18 +00003925 ExprValueKind VK = VK_LValue;
3926 if (Getter) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003927 PType = Getter->getSendResultType();
John McCall09431682010-11-18 19:01:18 +00003928 if (!getLangOptions().CPlusPlus &&
3929 IsCForbiddenLValueType(Context, PType))
3930 VK = VK_RValue;
3931 } else {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003932 // Get the expression type from Setter's incoming parameter.
3933 PType = (*(Setter->param_end() -1))->getType();
John McCall09431682010-11-18 19:01:18 +00003934 }
3935 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3936
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003937 // FIXME: we must check that the setter has property type.
John McCall12f78a62010-12-02 01:19:52 +00003938 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3939 PType, VK, OK,
3940 MemberLoc, BaseExpr));
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003941 }
John McCall028d3972010-12-15 16:46:44 +00003942
3943 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3944 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3945 ObjCImpDecl, HasTemplateArgs);
3946
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003947 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall028d3972010-12-15 16:46:44 +00003948 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00003949 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003950
John McCall028d3972010-12-15 16:46:44 +00003951 // Normal property access.
3952 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3953 SourceLocation(), QualType(), false);
Steve Naroff14108da2009-07-10 23:34:53 +00003954 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003955
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003956 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00003957 if (BaseType->isExtVectorType()) {
John McCall5e3c67b2010-12-15 04:42:30 +00003958 // FIXME: this expr should store IsArrow.
Anders Carlsson8f28f992009-08-26 18:25:21 +00003959 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall5e3c67b2010-12-15 04:42:30 +00003960 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall09431682010-11-18 19:01:18 +00003961 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3962 Member, MemberLoc);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003963 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003964 return ExprError();
John McCall09431682010-11-18 19:01:18 +00003965
3966 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3967 *Member, MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003968 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003969
John McCall028d3972010-12-15 16:46:44 +00003970 // Adjust builtin-sel to the appropriate redefinition type if that's
3971 // not just a pointer to builtin-sel again.
3972 if (IsArrow &&
3973 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
3974 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
3975 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
3976 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3977 ObjCImpDecl, HasTemplateArgs);
3978 }
3979
3980 // Failure cases.
3981 fail:
3982
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00003983 // Recover from dot accesses to pointers, e.g.:
3984 // type *foo;
3985 // foo.bar
3986 // This is actually well-formed in two cases:
3987 // - 'type' is an Objective C type
3988 // - 'bar' is a pseudo-destructor name which happens to refer to
3989 // the appropriate pointer type
John McCall028d3972010-12-15 16:46:44 +00003990 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00003991 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
3992 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall028d3972010-12-15 16:46:44 +00003993 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00003994 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3995 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall028d3972010-12-15 16:46:44 +00003996
3997 // Recurse as an -> access.
3998 IsArrow = true;
3999 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4000 ObjCImpDecl, HasTemplateArgs);
4001 }
John McCall028d3972010-12-15 16:46:44 +00004002 }
4003
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004004 // If the user is trying to apply -> or . to a function name, it's probably
4005 // because they forgot parentheses to call that function.
4006 bool TryCall = false;
4007 bool Overloaded = false;
4008 UnresolvedSet<8> AllOverloads;
4009 if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr)) {
4010 AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end());
4011 TryCall = true;
4012 Overloaded = true;
4013 } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr)) {
4014 if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
4015 AllOverloads.addDecl(Fun);
4016 TryCall = true;
4017 }
4018 }
John McCall028d3972010-12-15 16:46:44 +00004019
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004020 if (TryCall) {
4021 // Plunder the overload set for something that would make the member
4022 // expression valid.
4023 UnresolvedSet<4> ViableOverloads;
4024 bool HasViableZeroArgOverload = false;
4025 for (OverloadExpr::decls_iterator it = AllOverloads.begin(),
4026 DeclsEnd = AllOverloads.end(); it != DeclsEnd; ++it) {
4027 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*it);
4028 QualType ResultTy = OverloadDecl->getResultType();
4029 if ((!IsArrow && ResultTy->isRecordType()) ||
4030 (IsArrow && ResultTy->isPointerType() &&
4031 ResultTy->getPointeeType()->isRecordType())) {
4032 ViableOverloads.addDecl(*it);
4033 if (OverloadDecl->getMinRequiredArguments() == 0) {
4034 HasViableZeroArgOverload = true;
4035 }
John McCall028d3972010-12-15 16:46:44 +00004036 }
4037 }
4038
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004039 if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) {
4040 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
4041 << 1 << 0
4042 << BaseExpr->getSourceRange();
4043 int ViableOverloadCount = ViableOverloads.size();
4044 int I;
4045 for (I = 0; I < ViableOverloadCount; ++I) {
4046 // FIXME: Magic number for max shown overloads stolen from
4047 // OverloadCandidateSet::NoteCandidates.
4048 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4049 break;
4050 }
4051 Diag(ViableOverloads[I].getDecl()->getSourceRange().getBegin(),
4052 diag::note_member_ref_possible_intended_overload);
4053 }
4054 if (I != ViableOverloadCount) {
4055 Diag(BaseExpr->getExprLoc(), diag::note_ovl_too_many_candidates)
4056 << int(ViableOverloadCount - I);
4057 }
4058 return ExprError();
4059 }
4060 } else {
4061 // We don't have an expression that's convenient to get a Decl from, but we
4062 // can at least check if the type is "function of 0 arguments which returns
4063 // an acceptable type".
4064 const FunctionType *Fun = NULL;
4065 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4066 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4067 TryCall = true;
4068 }
4069 } else if ((Fun = BaseType->getAs<FunctionType>())) {
4070 TryCall = true;
4071 }
John McCall028d3972010-12-15 16:46:44 +00004072
4073 if (TryCall) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004074 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4075 if (FPT->getNumArgs() == 0) {
4076 QualType ResultTy = Fun->getResultType();
4077 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4078 (IsArrow && ResultTy->isPointerType() &&
4079 ResultTy->getPointeeType()->isRecordType());
4080 }
Matt Beaumont-Gay26ae5dd2011-02-17 02:54:17 +00004081 }
John McCall028d3972010-12-15 16:46:44 +00004082 }
4083 }
4084
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004085 if (TryCall) {
4086 // At this point, we know BaseExpr looks like it's potentially callable with
4087 // 0 arguments, and that it returns something of a reasonable type, so we
4088 // can emit a fixit and carry on pretending that BaseExpr was actually a
4089 // CallExpr.
4090 SourceLocation ParenInsertionLoc =
4091 PP.getLocForEndOfToken(BaseExpr->getLocEnd());
4092 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
4093 << int(Overloaded) << 1
4094 << BaseExpr->getSourceRange()
4095 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4096 ExprResult NewBase = ActOnCallExpr(0, BaseExpr, ParenInsertionLoc,
4097 MultiExprArg(*this, 0, 0),
4098 ParenInsertionLoc);
4099 if (NewBase.isInvalid())
4100 return ExprError();
4101 BaseExpr = NewBase.takeAs<Expr>();
4102 DefaultFunctionArrayConversion(BaseExpr);
4103 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4104 ObjCImpDecl, HasTemplateArgs);
4105 }
4106
Douglas Gregor214f31a2009-03-27 06:00:30 +00004107 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
4108 << BaseType << BaseExpr->getSourceRange();
4109
Douglas Gregor214f31a2009-03-27 06:00:30 +00004110 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00004111}
4112
John McCall129e2df2009-11-30 22:42:35 +00004113/// The main callback when the parser finds something like
4114/// expression . [nested-name-specifier] identifier
4115/// expression -> [nested-name-specifier] identifier
4116/// where 'identifier' encompasses a fairly broad spectrum of
4117/// possibilities, including destructor and operator references.
4118///
4119/// \param OpKind either tok::arrow or tok::period
4120/// \param HasTrailingLParen whether the next token is '(', which
4121/// is used to diagnose mis-uses of special members that can
4122/// only be called
4123/// \param ObjCImpDecl the current ObjC @implementation decl;
4124/// this is an ugly hack around the fact that ObjC @implementations
4125/// aren't properly put in the context chain
John McCall60d7b3a2010-08-24 06:29:42 +00004126ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall5e3c67b2010-12-15 04:42:30 +00004127 SourceLocation OpLoc,
4128 tok::TokenKind OpKind,
4129 CXXScopeSpec &SS,
4130 UnqualifiedId &Id,
4131 Decl *ObjCImpDecl,
4132 bool HasTrailingLParen) {
John McCall129e2df2009-11-30 22:42:35 +00004133 if (SS.isSet() && SS.isInvalid())
4134 return ExprError();
4135
Francois Pichetdbee3412011-01-18 05:04:39 +00004136 // Warn about the explicit constructor calls Microsoft extension.
4137 if (getLangOptions().Microsoft &&
4138 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4139 Diag(Id.getSourceRange().getBegin(),
4140 diag::ext_ms_explicit_constructor_call);
4141
John McCall129e2df2009-11-30 22:42:35 +00004142 TemplateArgumentListInfo TemplateArgsBuffer;
4143
4144 // Decompose the name into its component parts.
Abramo Bagnara25777432010-08-11 22:01:17 +00004145 DeclarationNameInfo NameInfo;
John McCall129e2df2009-11-30 22:42:35 +00004146 const TemplateArgumentListInfo *TemplateArgs;
4147 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00004148 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004149
Abramo Bagnara25777432010-08-11 22:01:17 +00004150 DeclarationName Name = NameInfo.getName();
John McCall129e2df2009-11-30 22:42:35 +00004151 bool IsArrow = (OpKind == tok::arrow);
4152
4153 NamedDecl *FirstQualifierInScope
4154 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4155 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4156
4157 // This is a postfix expression, so get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004158 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004159 if (Result.isInvalid()) return ExprError();
4160 Base = Result.take();
John McCall129e2df2009-11-30 22:42:35 +00004161
Douglas Gregor01e56ae2010-04-12 20:54:26 +00004162 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4163 isDependentScopeSpecifier(SS)) {
John McCall9ae2f072010-08-23 23:25:46 +00004164 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00004165 IsArrow, OpLoc,
4166 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00004167 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004168 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00004169 LookupResult R(*this, NameInfo, LookupMemberName);
John McCallad00b772010-06-16 08:42:20 +00004170 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
4171 SS, ObjCImpDecl, TemplateArgs != 0);
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004172
John McCallad00b772010-06-16 08:42:20 +00004173 if (Result.isInvalid()) {
4174 Owned(Base);
4175 return ExprError();
4176 }
John McCall129e2df2009-11-30 22:42:35 +00004177
John McCallad00b772010-06-16 08:42:20 +00004178 if (Result.get()) {
4179 // The only way a reference to a destructor can be used is to
4180 // immediately call it, which falls into this case. If the
4181 // next token is not a '(', produce a diagnostic and build the
4182 // call now.
4183 if (!HasTrailingLParen &&
4184 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCall9ae2f072010-08-23 23:25:46 +00004185 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall129e2df2009-11-30 22:42:35 +00004186
John McCallad00b772010-06-16 08:42:20 +00004187 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00004188 }
4189
John McCall9ae2f072010-08-23 23:25:46 +00004190 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00004191 OpLoc, IsArrow, SS, FirstQualifierInScope,
4192 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004193 }
4194
4195 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00004196}
4197
John McCall60d7b3a2010-08-24 06:29:42 +00004198ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00004199 FunctionDecl *FD,
4200 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00004201 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004202 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00004203 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00004204 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004205 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00004206 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004207 return ExprError();
4208 }
4209
4210 if (Param->hasUninstantiatedDefaultArg()) {
4211 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00004212
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004213 // Instantiate the expression.
4214 MultiLevelTemplateArgumentList ArgList
4215 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00004216
Nico Weber08e41a62010-11-29 18:19:25 +00004217 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004218 = ArgList.getInnermost();
4219 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4220 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004221
Nico Weber08e41a62010-11-29 18:19:25 +00004222 ExprResult Result;
4223 {
4224 // C++ [dcl.fct.default]p5:
4225 // The names in the [default argument] expression are bound, and
4226 // the semantic constraints are checked, at the point where the
4227 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00004228 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00004229 Result = SubstExpr(UninstExpr, ArgList);
4230 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004231 if (Result.isInvalid())
4232 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004233
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004234 // Check the expression as an initializer for the parameter.
4235 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004236 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004237 InitializationKind Kind
4238 = InitializationKind::CreateCopy(Param->getLocation(),
4239 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4240 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00004241
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004242 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4243 Result = InitSeq.Perform(*this, Entity, Kind,
4244 MultiExprArg(*this, &ResultE, 1));
4245 if (Result.isInvalid())
4246 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004247
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004248 // Build the default argument expression.
4249 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4250 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004251 }
4252
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004253 // If the default expression creates temporaries, we need to
4254 // push them to the current stack of expression temporaries so they'll
4255 // be properly destroyed.
4256 // FIXME: We should really be rebuilding the default argument with new
4257 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00004258 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4259 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4260 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4261 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4262 ExprTemporaries.push_back(Temporary);
4263 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004264
4265 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00004266 // Just mark all of the declarations in this potentially-evaluated expression
4267 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004268 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00004269 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004270}
4271
Douglas Gregor88a35142008-12-22 05:46:06 +00004272/// ConvertArgumentsForCall - Converts the arguments specified in
4273/// Args/NumArgs to the parameter types of the function FDecl with
4274/// function prototype Proto. Call is the call expression itself, and
4275/// Fn is the function expression. For a C++ member function, this
4276/// routine does not attempt to convert the object argument. Returns
4277/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004278bool
4279Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00004280 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00004281 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00004282 Expr **Args, unsigned NumArgs,
4283 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004284 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00004285 // assignment, to the types of the corresponding parameter, ...
4286 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004287 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004288
Douglas Gregor88a35142008-12-22 05:46:06 +00004289 // If too few arguments are available (and we don't have default
4290 // arguments for the remaining parameters), don't make the call.
4291 if (NumArgs < NumArgsInProto) {
4292 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4293 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004294 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00004295 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004296 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00004297 }
4298
4299 // If too many are passed and not variadic, error on the extras and drop
4300 // them.
4301 if (NumArgs > NumArgsInProto) {
4302 if (!Proto->isVariadic()) {
4303 Diag(Args[NumArgsInProto]->getLocStart(),
4304 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004305 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00004306 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00004307 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4308 Args[NumArgs-1]->getLocEnd());
4309 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004310 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004311 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004312 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004313 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004314 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004315 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004316 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4317 if (Fn->getType()->isBlockPointerType())
4318 CallType = VariadicBlock; // Block
4319 else if (isa<MemberExpr>(Fn))
4320 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004321 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004322 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004323 if (Invalid)
4324 return true;
4325 unsigned TotalNumArgs = AllArgs.size();
4326 for (unsigned i = 0; i < TotalNumArgs; ++i)
4327 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004328
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004329 return false;
4330}
Mike Stumpeed9cac2009-02-19 03:04:26 +00004331
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004332bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4333 FunctionDecl *FDecl,
4334 const FunctionProtoType *Proto,
4335 unsigned FirstProtoArg,
4336 Expr **Args, unsigned NumArgs,
4337 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004338 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004339 unsigned NumArgsInProto = Proto->getNumArgs();
4340 unsigned NumArgsToCheck = NumArgs;
4341 bool Invalid = false;
4342 if (NumArgs != NumArgsInProto)
4343 // Use default arguments for missing arguments
4344 NumArgsToCheck = NumArgsInProto;
4345 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00004346 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004347 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004348 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004349
Douglas Gregor88a35142008-12-22 05:46:06 +00004350 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004351 if (ArgIx < NumArgs) {
4352 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004353
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004354 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4355 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004356 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004357 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004358 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004359
Douglas Gregora188ff22009-12-22 16:09:06 +00004360 // Pass the argument
4361 ParmVarDecl *Param = 0;
4362 if (FDecl && i < FDecl->getNumParams())
4363 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00004364
Douglas Gregora188ff22009-12-22 16:09:06 +00004365 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004366 Param? InitializedEntity::InitializeParameter(Context, Param)
4367 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCall60d7b3a2010-08-24 06:29:42 +00004368 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00004369 SourceLocation(),
4370 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00004371 if (ArgE.isInvalid())
4372 return true;
4373
4374 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004375 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00004376 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004377
John McCall60d7b3a2010-08-24 06:29:42 +00004378 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004379 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004380 if (ArgExpr.isInvalid())
4381 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004382
Anders Carlsson56c5e332009-08-25 03:49:14 +00004383 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004384 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004385 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004386 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004387
Douglas Gregor88a35142008-12-22 05:46:06 +00004388 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004389 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004390 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner40378332010-05-16 04:01:30 +00004391 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004392 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00004393 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004394 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004395 }
4396 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004397 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00004398}
4399
Steve Narofff69936d2007-09-16 03:34:24 +00004400/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00004401/// This provides the location of the left/right parens and a list of comma
4402/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00004403ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004404Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004405 MultiExprArg args, SourceLocation RParenLoc,
4406 Expr *ExecConfig) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00004407 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00004408
4409 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004410 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00004411 if (Result.isInvalid()) return ExprError();
4412 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00004413
John McCall9ae2f072010-08-23 23:25:46 +00004414 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004415
Douglas Gregor88a35142008-12-22 05:46:06 +00004416 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00004417 // If this is a pseudo-destructor expression, build the call immediately.
4418 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4419 if (NumArgs > 0) {
4420 // Pseudo-destructor calls should not have any arguments.
4421 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00004422 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00004423 SourceRange(Args[0]->getLocStart(),
4424 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00004425
Douglas Gregora71d8192009-09-04 17:36:40 +00004426 NumArgs = 0;
4427 }
Mike Stump1eb44332009-09-09 15:08:12 +00004428
Douglas Gregora71d8192009-09-04 17:36:40 +00004429 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00004430 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00004431 }
Mike Stump1eb44332009-09-09 15:08:12 +00004432
Douglas Gregor17330012009-02-04 15:01:18 +00004433 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004434 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00004435 // FIXME: Will need to cache the results of name lookup (including ADL) in
4436 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00004437 bool Dependent = false;
4438 if (Fn->isTypeDependent())
4439 Dependent = true;
4440 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4441 Dependent = true;
4442
Peter Collingbournee08ce652011-02-09 21:07:24 +00004443 if (Dependent) {
4444 if (ExecConfig) {
4445 return Owned(new (Context) CUDAKernelCallExpr(
4446 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4447 Context.DependentTy, VK_RValue, RParenLoc));
4448 } else {
4449 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4450 Context.DependentTy, VK_RValue,
4451 RParenLoc));
4452 }
4453 }
Douglas Gregor17330012009-02-04 15:01:18 +00004454
4455 // Determine whether this is a call to an object (C++ [over.call.object]).
4456 if (Fn->getType()->isRecordType())
4457 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004458 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00004459
John McCall129e2df2009-11-30 22:42:35 +00004460 Expr *NakedFn = Fn->IgnoreParens();
4461
4462 // Determine whether this is a call to an unresolved member function.
4463 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4464 // If lookup was unresolved but not dependent (i.e. didn't find
4465 // an unresolved using declaration), it has to be an overloaded
4466 // function set, which means it must contain either multiple
4467 // declarations (all methods or method templates) or a single
4468 // method template.
4469 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor2b147f02010-04-25 21:15:30 +00004470 isa<FunctionTemplateDecl>(
4471 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00004472 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00004473
John McCallaa81e162009-12-01 22:10:20 +00004474 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004475 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00004476 }
4477
Douglas Gregorfa047642009-02-04 00:32:51 +00004478 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00004479 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00004480 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00004481 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00004482 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004483 RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00004484 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004485
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004486 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00004487 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCall2de56d12010-08-25 11:45:40 +00004488 if (BO->getOpcode() == BO_PtrMemD ||
4489 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00004490 if (const FunctionProtoType *FPT
4491 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004492 QualType ResultTy = FPT->getCallResultType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00004493 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004494
Douglas Gregorfdc13a02011-02-04 12:57:49 +00004495 // Check that the object type isn't more qualified than the
4496 // member function we're calling.
4497 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4498 Qualifiers ObjectQuals
4499 = BO->getOpcode() == BO_PtrMemD
4500 ? BO->getLHS()->getType().getQualifiers()
4501 : BO->getLHS()->getType()->getAs<PointerType>()
4502 ->getPointeeType().getQualifiers();
4503
4504 Qualifiers Difference = ObjectQuals - FuncQuals;
4505 Difference.removeObjCGCAttr();
4506 Difference.removeAddressSpace();
4507 if (Difference) {
4508 std::string QualsString = Difference.getAsString();
4509 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4510 << BO->getType().getUnqualifiedType()
4511 << QualsString
4512 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4513 }
4514
John McCall9ae2f072010-08-23 23:25:46 +00004515 CXXMemberCallExpr *TheCall
Abramo Bagnara6c572f12010-12-03 21:39:42 +00004516 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCallf89e55a2010-11-18 06:31:45 +00004517 NumArgs, ResultTy, VK,
John McCall9ae2f072010-08-23 23:25:46 +00004518 RParenLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004519
4520 if (CheckCallReturnType(FPT->getResultType(),
4521 BO->getRHS()->getSourceRange().getBegin(),
John McCall9ae2f072010-08-23 23:25:46 +00004522 TheCall, 0))
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004523 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00004524
John McCall9ae2f072010-08-23 23:25:46 +00004525 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004526 RParenLoc))
4527 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004528
John McCall9ae2f072010-08-23 23:25:46 +00004529 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004530 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004531 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004532 diag::err_typecheck_call_not_function)
4533 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004534 }
4535 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004536 }
4537
Douglas Gregorfa047642009-02-04 00:32:51 +00004538 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004539 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004540 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004541
Eli Friedmanefa42f72009-12-26 03:35:45 +00004542 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00004543 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4544 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4545 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004546 RParenLoc, ExecConfig);
Douglas Gregoref9b1492010-11-09 20:03:54 +00004547 }
4548
John McCall3b4294e2009-12-16 12:17:52 +00004549 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00004550 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4551 if (UnOp->getOpcode() == UO_AddrOf)
4552 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4553
John McCall3b4294e2009-12-16 12:17:52 +00004554 if (isa<DeclRefExpr>(NakedFn))
4555 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4556
Peter Collingbournee08ce652011-02-09 21:07:24 +00004557 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4558 ExecConfig);
4559}
4560
4561ExprResult
4562Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4563 MultiExprArg execConfig, SourceLocation GGGLoc) {
4564 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4565 if (!ConfigDecl)
4566 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4567 << "cudaConfigureCall");
4568 QualType ConfigQTy = ConfigDecl->getType();
4569
4570 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4571 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4572
4573 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00004574}
4575
John McCall3b4294e2009-12-16 12:17:52 +00004576/// BuildResolvedCallExpr - Build a call to a resolved expression,
4577/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00004578/// unary-convert to an expression of function-pointer or
4579/// block-pointer type.
4580///
4581/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00004582ExprResult
John McCallaa81e162009-12-01 22:10:20 +00004583Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4584 SourceLocation LParenLoc,
4585 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004586 SourceLocation RParenLoc,
4587 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00004588 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4589
Chris Lattner04421082008-04-08 04:40:51 +00004590 // Promote the function operand.
4591 UsualUnaryConversions(Fn);
4592
Chris Lattner925e60d2007-12-28 05:29:59 +00004593 // Make the call expr early, before semantic checks. This guarantees cleanup
4594 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004595 CallExpr *TheCall;
4596 if (Config) {
4597 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4598 cast<CallExpr>(Config),
4599 Args, NumArgs,
4600 Context.BoolTy,
4601 VK_RValue,
4602 RParenLoc);
4603 } else {
4604 TheCall = new (Context) CallExpr(Context, Fn,
4605 Args, NumArgs,
4606 Context.BoolTy,
4607 VK_RValue,
4608 RParenLoc);
4609 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004610
Steve Naroffdd972f22008-09-05 22:11:13 +00004611 const FunctionType *FuncT;
4612 if (!Fn->getType()->isBlockPointerType()) {
4613 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4614 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00004615 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00004616 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00004617 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4618 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00004619 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00004620 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00004621 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00004622 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00004623 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004624 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00004625 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4626 << Fn->getType() << Fn->getSourceRange());
4627
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004628 if (getLangOptions().CUDA) {
4629 if (Config) {
4630 // CUDA: Kernel calls must be to global functions
4631 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4632 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4633 << FDecl->getName() << Fn->getSourceRange());
4634
4635 // CUDA: Kernel function must have 'void' return type
4636 if (!FuncT->getResultType()->isVoidType())
4637 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4638 << Fn->getType() << Fn->getSourceRange());
4639 }
4640 }
4641
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004642 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004643 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00004644 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004645 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004646 return ExprError();
4647
Chris Lattner925e60d2007-12-28 05:29:59 +00004648 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004649 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004650 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004651
Douglas Gregor72564e72009-02-26 23:50:07 +00004652 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00004653 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00004654 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004655 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004656 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004657 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004658
Douglas Gregor74734d52009-04-02 15:37:10 +00004659 if (FDecl) {
4660 // Check if we have too few/too many template arguments, based
4661 // on our knowledge of the function definition.
4662 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004663 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004664 const FunctionProtoType *Proto
4665 = Def->getType()->getAs<FunctionProtoType>();
4666 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004667 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4668 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004669 }
Douglas Gregor46542412010-10-25 20:39:23 +00004670
4671 // If the function we're calling isn't a function prototype, but we have
4672 // a function prototype from a prior declaratiom, use that prototype.
4673 if (!FDecl->hasPrototype())
4674 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004675 }
4676
Steve Naroffb291ab62007-08-28 23:30:39 +00004677 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004678 for (unsigned i = 0; i != NumArgs; i++) {
4679 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004680
4681 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004682 InitializedEntity Entity
4683 = InitializedEntity::InitializeParameter(Context,
4684 Proto->getArgType(i));
4685 ExprResult ArgE = PerformCopyInitialization(Entity,
4686 SourceLocation(),
4687 Owned(Arg));
4688 if (ArgE.isInvalid())
4689 return true;
4690
4691 Arg = ArgE.takeAs<Expr>();
4692
4693 } else {
4694 DefaultArgumentPromotion(Arg);
Douglas Gregor46542412010-10-25 20:39:23 +00004695 }
4696
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004697 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4698 Arg->getType(),
4699 PDiag(diag::err_call_incomplete_argument)
4700 << Arg->getSourceRange()))
4701 return ExprError();
4702
Chris Lattner925e60d2007-12-28 05:29:59 +00004703 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004704 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004705 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004706
Douglas Gregor88a35142008-12-22 05:46:06 +00004707 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4708 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004709 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4710 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004711
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004712 // Check for sentinels
4713 if (NDecl)
4714 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004715
Chris Lattner59907c42007-08-10 20:18:51 +00004716 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004717 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00004718 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00004719 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004720
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004721 if (unsigned BuiltinID = FDecl->getBuiltinID())
4722 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004723 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00004724 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00004725 return ExprError();
4726 }
Chris Lattner59907c42007-08-10 20:18:51 +00004727
John McCall9ae2f072010-08-23 23:25:46 +00004728 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004729}
4730
John McCall60d7b3a2010-08-24 06:29:42 +00004731ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004732Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004733 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004734 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004735 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004736 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004737
4738 TypeSourceInfo *TInfo;
4739 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4740 if (!TInfo)
4741 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4742
John McCall9ae2f072010-08-23 23:25:46 +00004743 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004744}
4745
John McCall60d7b3a2010-08-24 06:29:42 +00004746ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004747Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00004748 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004749 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004750
Eli Friedman6223c222008-05-20 05:22:08 +00004751 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004752 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4753 PDiag(diag::err_illegal_decl_array_incomplete_type)
4754 << SourceRange(LParenLoc,
4755 literalExpr->getSourceRange().getEnd())))
4756 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004757 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004758 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4759 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004760 } else if (!literalType->isDependentType() &&
4761 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004762 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00004763 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00004764 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004765 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004766
Douglas Gregor99a2e602009-12-16 01:38:02 +00004767 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004768 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004769 InitializationKind Kind
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004770 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004771 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00004772 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00004773 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00004774 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00004775 &literalType);
4776 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004777 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004778 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004779
Chris Lattner371f2582008-12-04 23:50:19 +00004780 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004781 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00004782 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004783 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004784 }
Eli Friedman08544622009-12-22 02:35:53 +00004785
John McCallf89e55a2010-11-18 06:31:45 +00004786 // In C, compound literals are l-values for some reason.
4787 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4788
John McCall1d7d8d62010-01-19 22:33:45 +00004789 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCallf89e55a2010-11-18 06:31:45 +00004790 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004791}
4792
John McCall60d7b3a2010-08-24 06:29:42 +00004793ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004794Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004795 SourceLocation RBraceLoc) {
4796 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00004797 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00004798
Steve Naroff08d92e42007-09-15 18:49:24 +00004799 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004800 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004801
Ted Kremenek709210f2010-04-13 23:39:13 +00004802 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4803 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004804 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004805 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004806}
4807
John McCallf3ea8cf2010-11-14 08:17:51 +00004808/// Prepares for a scalar cast, performing all the necessary stages
4809/// except the final cast and returning the kind required.
4810static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4811 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4812 // Also, callers should have filtered out the invalid cases with
4813 // pointers. Everything else should be possible.
4814
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004815 QualType SrcTy = Src->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00004816 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004817 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004818
John McCalldaa8e4e2010-11-15 09:13:47 +00004819 switch (SrcTy->getScalarTypeKind()) {
4820 case Type::STK_MemberPointer:
4821 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004822
John McCalldaa8e4e2010-11-15 09:13:47 +00004823 case Type::STK_Pointer:
4824 switch (DestTy->getScalarTypeKind()) {
4825 case Type::STK_Pointer:
4826 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00004827 CK_AnyPointerToObjCPointerCast :
4828 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004829 case Type::STK_Bool:
4830 return CK_PointerToBoolean;
4831 case Type::STK_Integral:
4832 return CK_PointerToIntegral;
4833 case Type::STK_Floating:
4834 case Type::STK_FloatingComplex:
4835 case Type::STK_IntegralComplex:
4836 case Type::STK_MemberPointer:
4837 llvm_unreachable("illegal cast from pointer");
4838 }
4839 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004840
John McCalldaa8e4e2010-11-15 09:13:47 +00004841 case Type::STK_Bool: // casting from bool is like casting from an integer
4842 case Type::STK_Integral:
4843 switch (DestTy->getScalarTypeKind()) {
4844 case Type::STK_Pointer:
John McCallf3ea8cf2010-11-14 08:17:51 +00004845 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004846 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004847 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004848 case Type::STK_Bool:
4849 return CK_IntegralToBoolean;
4850 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004851 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004852 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004853 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004854 case Type::STK_IntegralComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004855 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCall8786da72010-12-14 17:51:41 +00004856 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004857 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004858 case Type::STK_FloatingComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004859 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004860 CK_IntegralToFloating);
4861 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004862 case Type::STK_MemberPointer:
4863 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004864 }
4865 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004866
John McCalldaa8e4e2010-11-15 09:13:47 +00004867 case Type::STK_Floating:
4868 switch (DestTy->getScalarTypeKind()) {
4869 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004870 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004871 case Type::STK_Bool:
4872 return CK_FloatingToBoolean;
4873 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004874 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004875 case Type::STK_FloatingComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004876 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCall8786da72010-12-14 17:51:41 +00004877 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004878 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004879 case Type::STK_IntegralComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004880 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004881 CK_FloatingToIntegral);
4882 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004883 case Type::STK_Pointer:
4884 llvm_unreachable("valid float->pointer cast?");
4885 case Type::STK_MemberPointer:
4886 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004887 }
4888 break;
4889
John McCalldaa8e4e2010-11-15 09:13:47 +00004890 case Type::STK_FloatingComplex:
4891 switch (DestTy->getScalarTypeKind()) {
4892 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004893 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004894 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004895 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004896 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004897 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00004898 if (S.Context.hasSameType(ET, DestTy))
4899 return CK_FloatingComplexToReal;
4900 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4901 return CK_FloatingCast;
4902 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004903 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004904 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004905 case Type::STK_Integral:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004906 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004907 CK_FloatingComplexToReal);
4908 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004909 case Type::STK_Pointer:
4910 llvm_unreachable("valid complex float->pointer cast?");
4911 case Type::STK_MemberPointer:
4912 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004913 }
4914 break;
4915
John McCalldaa8e4e2010-11-15 09:13:47 +00004916 case Type::STK_IntegralComplex:
4917 switch (DestTy->getScalarTypeKind()) {
4918 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004919 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004920 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004921 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004922 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004923 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00004924 if (S.Context.hasSameType(ET, DestTy))
4925 return CK_IntegralComplexToReal;
4926 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4927 return CK_IntegralCast;
4928 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004929 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004930 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004931 case Type::STK_Floating:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004932 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004933 CK_IntegralComplexToReal);
4934 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004935 case Type::STK_Pointer:
4936 llvm_unreachable("valid complex int->pointer cast?");
4937 case Type::STK_MemberPointer:
4938 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004939 }
4940 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00004941 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004942
John McCallf3ea8cf2010-11-14 08:17:51 +00004943 llvm_unreachable("Unhandled scalar cast");
4944 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00004945}
4946
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004947/// CheckCastTypes - Check type constraints for casting between types.
John McCallf89e55a2010-11-18 06:31:45 +00004948bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4949 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4950 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004951 if (getLangOptions().CPlusPlus)
Douglas Gregor40749ee2010-11-03 00:35:38 +00004952 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4953 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00004954 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004955 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004956
John McCallf89e55a2010-11-18 06:31:45 +00004957 // We only support r-value casts in C.
4958 VK = VK_RValue;
4959
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004960 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4961 // type needs to be scalar.
4962 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00004963 // We don't necessarily do lvalue-to-rvalue conversions on this.
4964 IgnoredValueConversions(castExpr);
4965
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004966 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00004967 Kind = CK_ToVoid;
Anders Carlssonebeaf202009-10-16 02:35:04 +00004968 return false;
4969 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004970
John McCallf6a16482010-12-04 03:47:34 +00004971 DefaultFunctionArrayLvalueConversion(castExpr);
4972
Eli Friedman8d438082010-07-17 20:43:49 +00004973 if (RequireCompleteType(TyR.getBegin(), castType,
4974 diag::err_typecheck_cast_to_incomplete))
4975 return true;
4976
Anders Carlssonebeaf202009-10-16 02:35:04 +00004977 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00004978 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004979 (castType->isStructureType() || castType->isUnionType())) {
4980 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004981 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004982 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4983 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004984 Kind = CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00004985 return false;
4986 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004987
Anders Carlssonc3516322009-10-16 02:48:28 +00004988 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004989 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00004990 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004991 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004992 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004993 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004994 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00004995 castExpr->getType()) &&
4996 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004997 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4998 << castExpr->getSourceRange();
4999 break;
5000 }
5001 }
5002 if (Field == FieldEnd)
5003 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
5004 << castExpr->getType() << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005005 Kind = CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00005006 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005007 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005008
Anders Carlssonc3516322009-10-16 02:48:28 +00005009 // Reject any other conversions to non-scalar types.
5010 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
5011 << castType << castExpr->getSourceRange();
5012 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005013
John McCallf3ea8cf2010-11-14 08:17:51 +00005014 // The type we're casting to is known to be a scalar or vector.
5015
5016 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005017 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00005018 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005019 return Diag(castExpr->getLocStart(),
5020 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00005021 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00005022 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005023
5024 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00005025 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005026
Anders Carlssonc3516322009-10-16 02:48:28 +00005027 if (castType->isVectorType())
5028 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
5029 if (castExpr->getType()->isVectorType())
5030 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
5031
John McCallf3ea8cf2010-11-14 08:17:51 +00005032 // The source and target types are both scalars, i.e.
5033 // - arithmetic types (fundamental, enum, and complex)
5034 // - all kinds of pointers
5035 // Note that member pointers were filtered out with C++, above.
5036
Anders Carlsson16a89042009-10-16 05:23:41 +00005037 if (isa<ObjCSelectorExpr>(castExpr))
5038 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005039
John McCallf3ea8cf2010-11-14 08:17:51 +00005040 // If either type is a pointer, the other type has to be either an
5041 // integer or a pointer.
Anders Carlssonc3516322009-10-16 02:48:28 +00005042 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00005043 QualType castExprType = castExpr->getType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005044 if (!castExprType->isIntegralType(Context) &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005045 castExprType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00005046 return Diag(castExpr->getLocStart(),
5047 diag::err_cast_pointer_from_non_pointer_int)
5048 << castExprType << castExpr->getSourceRange();
5049 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005050 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00005051 return Diag(castExpr->getLocStart(),
5052 diag::err_cast_pointer_to_non_pointer_int)
5053 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005054 }
Anders Carlsson82debc72009-10-18 18:12:03 +00005055
John McCallf3ea8cf2010-11-14 08:17:51 +00005056 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCallb7f4ffe2010-08-12 21:44:57 +00005057
John McCallf3ea8cf2010-11-14 08:17:51 +00005058 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00005059 CheckCastAlign(castExpr, castType, TyR);
5060
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005061 return false;
5062}
5063
Anders Carlssonc3516322009-10-16 02:48:28 +00005064bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00005065 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00005066 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005067
Anders Carlssona64db8f2007-11-27 05:51:55 +00005068 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00005069 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00005070 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00005071 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00005072 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005073 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00005074 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005075 } else
5076 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005077 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00005078 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005079
John McCall2de56d12010-08-25 11:45:40 +00005080 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005081 return false;
5082}
5083
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005084bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCall2de56d12010-08-25 11:45:40 +00005085 CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00005086 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005087
Anders Carlsson16a89042009-10-16 05:23:41 +00005088 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005089
Nate Begeman9b10da62009-06-27 22:05:55 +00005090 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5091 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00005092 if (SrcTy->isVectorType()) {
5093 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
5094 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5095 << DestTy << SrcTy << R;
John McCall2de56d12010-08-25 11:45:40 +00005096 Kind = CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00005097 return false;
5098 }
5099
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005100 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00005101 // conversion will take place first from scalar to elt type, and then
5102 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005103 if (SrcTy->isPointerType())
5104 return Diag(R.getBegin(),
5105 diag::err_invalid_conversion_between_vector_and_scalar)
5106 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00005107
5108 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5109 ImpCastExprToType(CastExpr, DestElemTy,
John McCallf3ea8cf2010-11-14 08:17:51 +00005110 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005111
John McCall2de56d12010-08-25 11:45:40 +00005112 Kind = CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00005113 return false;
5114}
5115
John McCall60d7b3a2010-08-24 06:29:42 +00005116ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005117Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005118 SourceLocation RParenLoc, Expr *castExpr) {
5119 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005120 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00005121
John McCall9d125032010-01-15 18:39:57 +00005122 TypeSourceInfo *castTInfo;
5123 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5124 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00005125 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00005126
Nate Begeman2ef13e52009-08-10 23:49:36 +00005127 // If the Expr being casted is a ParenListExpr, handle it specially.
5128 if (isa<ParenListExpr>(castExpr))
John McCall9ae2f072010-08-23 23:25:46 +00005129 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCall42f56b52010-01-18 19:35:47 +00005130 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00005131
John McCall9ae2f072010-08-23 23:25:46 +00005132 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00005133}
5134
John McCall60d7b3a2010-08-24 06:29:42 +00005135ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00005136Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005137 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005138 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00005139 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00005140 CXXCastPath BasePath;
John McCallb042fdf2010-01-15 18:56:44 +00005141 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCallf89e55a2010-11-18 06:31:45 +00005142 Kind, VK, BasePath))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005143 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00005144
John McCallf871d0c2010-08-07 06:22:56 +00005145 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +00005146 Ty->getType().getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +00005147 VK, Kind, castExpr, &BasePath, Ty,
John McCallf871d0c2010-08-07 06:22:56 +00005148 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005149}
5150
Nate Begeman2ef13e52009-08-10 23:49:36 +00005151/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5152/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005153ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005154Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005155 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5156 if (!E)
5157 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00005158
John McCall60d7b3a2010-08-24 06:29:42 +00005159 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00005160
Nate Begeman2ef13e52009-08-10 23:49:36 +00005161 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00005162 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5163 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00005164
John McCall9ae2f072010-08-23 23:25:46 +00005165 if (Result.isInvalid()) return ExprError();
5166
5167 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005168}
5169
John McCall60d7b3a2010-08-24 06:29:42 +00005170ExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00005171Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00005172 SourceLocation RParenLoc, Expr *Op,
John McCall42f56b52010-01-18 19:35:47 +00005173 TypeSourceInfo *TInfo) {
John McCall9ae2f072010-08-23 23:25:46 +00005174 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCall42f56b52010-01-18 19:35:47 +00005175 QualType Ty = TInfo->getType();
John Thompson8bb59a82010-06-30 22:55:51 +00005176 bool isAltiVecLiteral = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005177
John Thompson8bb59a82010-06-30 22:55:51 +00005178 // Check for an altivec literal,
5179 // i.e. all the elements are integer constants.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005180 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5181 if (PE->getNumExprs() == 0) {
5182 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5183 return ExprError();
5184 }
John Thompson8bb59a82010-06-30 22:55:51 +00005185 if (PE->getNumExprs() == 1) {
5186 if (!PE->getExpr(0)->getType()->isVectorType())
5187 isAltiVecLiteral = true;
5188 }
5189 else
5190 isAltiVecLiteral = true;
5191 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00005192
John Thompson8bb59a82010-06-30 22:55:51 +00005193 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
5194 // then handle it as such.
5195 if (isAltiVecLiteral) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005196 llvm::SmallVector<Expr *, 8> initExprs;
5197 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5198 initExprs.push_back(PE->getExpr(i));
5199
5200 // FIXME: This means that pretty-printing the final AST will produce curly
5201 // braces instead of the original commas.
Ted Kremenek709210f2010-04-13 23:39:13 +00005202 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5203 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00005204 initExprs.size(), RParenLoc);
5205 E->setType(Ty);
John McCall9ae2f072010-08-23 23:25:46 +00005206 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005207 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005208 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00005209 // sequence of BinOp comma operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005210 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCall9ae2f072010-08-23 23:25:46 +00005211 if (Result.isInvalid()) return ExprError();
5212 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005213 }
5214}
5215
John McCall60d7b3a2010-08-24 06:29:42 +00005216ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00005217 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005218 MultiExprArg Val,
John McCallb3d87482010-08-24 05:47:05 +00005219 ParsedType TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005220 unsigned nexprs = Val.size();
5221 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005222 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5223 Expr *expr;
5224 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5225 expr = new (Context) ParenExpr(L, R, exprs[0]);
5226 else
5227 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005228 return Owned(expr);
5229}
5230
Chandler Carruth82214a82011-02-18 23:54:50 +00005231/// \brief Emit a specialized diagnostic when one expression is a null pointer
5232/// constant and the other is not a pointer.
5233bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5234 SourceLocation QuestionLoc) {
5235 Expr *NullExpr = LHS;
5236 Expr *NonPointerExpr = RHS;
5237 Expr::NullPointerConstantKind NullKind =
5238 NullExpr->isNullPointerConstant(Context,
5239 Expr::NPC_ValueDependentIsNotNull);
5240
5241 if (NullKind == Expr::NPCK_NotNull) {
5242 NullExpr = RHS;
5243 NonPointerExpr = LHS;
5244 NullKind =
5245 NullExpr->isNullPointerConstant(Context,
5246 Expr::NPC_ValueDependentIsNotNull);
5247 }
5248
5249 if (NullKind == Expr::NPCK_NotNull)
5250 return false;
5251
5252 if (NullKind == Expr::NPCK_ZeroInteger) {
5253 // In this case, check to make sure that we got here from a "NULL"
5254 // string in the source code.
5255 NullExpr = NullExpr->IgnoreParenImpCasts();
5256 SourceManager& SM = Context.getSourceManager();
5257 SourceLocation Loc = SM.getInstantiationLoc(NullExpr->getExprLoc());
5258 unsigned Len =
5259 Lexer::MeasureTokenLength(Loc, SM, Context.getLangOptions());
5260 if (Len != 4 || memcmp(SM.getCharacterData(Loc), "NULL", 4))
5261 return false;
5262 }
5263
5264 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5265 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5266 << NonPointerExpr->getType() << DiagType
5267 << NonPointerExpr->getSourceRange();
5268 return true;
5269}
5270
Sebastian Redl28507842009-02-26 14:39:58 +00005271/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5272/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00005273/// C99 6.5.15
5274QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005275 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00005276 SourceLocation QuestionLoc) {
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005277 // If both LHS and RHS are overloaded functions, try to resolve them.
5278 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
5279 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
5280 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
5281 if (LHSResult.isInvalid())
5282 return QualType();
5283
5284 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
5285 if (RHSResult.isInvalid())
5286 return QualType();
5287
5288 LHS = LHSResult.take();
5289 RHS = RHSResult.take();
5290 }
5291
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005292 // C++ is sufficiently different to merit its own checker.
5293 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00005294 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00005295
5296 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005297 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005298
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005299 UsualUnaryConversions(Cond);
John McCall56ca35d2011-02-17 10:25:35 +00005300 UsualUnaryConversions(LHS);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005301 UsualUnaryConversions(RHS);
5302 QualType CondTy = Cond->getType();
5303 QualType LHSTy = LHS->getType();
5304 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005305
Reid Spencer5f016e22007-07-11 17:01:13 +00005306 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005307 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begeman6155d732010-09-20 22:41:17 +00005308 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5309 // Throw an error if its not either.
5310 if (getLangOptions().OpenCL) {
5311 if (!CondTy->isVectorType()) {
5312 Diag(Cond->getLocStart(),
5313 diag::err_typecheck_cond_expect_scalar_or_vector)
5314 << CondTy;
5315 return QualType();
5316 }
5317 }
5318 else {
5319 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5320 << CondTy;
5321 return QualType();
5322 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005323 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005324
Chris Lattner70d67a92008-01-06 22:42:25 +00005325 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005326 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5327 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00005328
Nate Begeman6155d732010-09-20 22:41:17 +00005329 // OpenCL: If the condition is a vector, and both operands are scalar,
5330 // attempt to implicity convert them to the vector type to act like the
5331 // built in select.
5332 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5333 // Both operands should be of scalar type.
5334 if (!LHSTy->isScalarType()) {
5335 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5336 << CondTy;
5337 return QualType();
5338 }
5339 if (!RHSTy->isScalarType()) {
5340 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5341 << CondTy;
5342 return QualType();
5343 }
5344 // Implicity convert these scalars to the type of the condition.
5345 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5346 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5347 }
5348
Chris Lattner70d67a92008-01-06 22:42:25 +00005349 // If both operands have arithmetic type, do the usual arithmetic conversions
5350 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005351 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5352 UsualArithmeticConversions(LHS, RHS);
5353 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005354 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005355
Chris Lattner70d67a92008-01-06 22:42:25 +00005356 // If both operands are the same structure or union type, the result is that
5357 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005358 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5359 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005360 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005361 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005362 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005363 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005364 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005365 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005366
Chris Lattner70d67a92008-01-06 22:42:25 +00005367 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005368 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005369 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5370 if (!LHSTy->isVoidType())
5371 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5372 << RHS->getSourceRange();
5373 if (!RHSTy->isVoidType())
5374 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5375 << LHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005376 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5377 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00005378 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00005379 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00005380 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5381 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005382 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005383 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005384 // promote the null to a pointer.
John McCalldaa8e4e2010-11-15 09:13:47 +00005385 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005386 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005387 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005388 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005389 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005390 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005391 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005392 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005393
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005394 // All objective-c pointer type analysis is done here.
5395 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5396 QuestionLoc);
5397 if (!compositeType.isNull())
5398 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005399
5400
Steve Naroff7154a772009-07-01 14:36:47 +00005401 // Handle block pointer types.
5402 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5403 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5404 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5405 QualType destType = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005406 ImpCastExprToType(LHS, destType, CK_BitCast);
5407 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005408 return destType;
5409 }
5410 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005411 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00005412 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005413 }
Steve Naroff7154a772009-07-01 14:36:47 +00005414 // We have 2 block pointer types.
5415 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5416 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005417 return LHSTy;
5418 }
Steve Naroff7154a772009-07-01 14:36:47 +00005419 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00005420 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5421 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005422
Steve Naroff7154a772009-07-01 14:36:47 +00005423 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5424 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00005425 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005426 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005427 // In this situation, we assume void* type. No especially good
5428 // reason, but this is what gcc does, and we do have to pick
5429 // to get a consistent AST.
5430 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005431 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5432 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00005433 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005434 }
Steve Naroff7154a772009-07-01 14:36:47 +00005435 // The block pointer types are compatible.
John McCall2de56d12010-08-25 11:45:40 +00005436 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5437 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00005438 return LHSTy;
5439 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005440
Steve Naroff7154a772009-07-01 14:36:47 +00005441 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5442 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5443 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00005444 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5445 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00005446
5447 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5448 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5449 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00005450 QualType destPointee
5451 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005452 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005453 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005454 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005455 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005456 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005457 return destType;
5458 }
5459 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00005460 QualType destPointee
5461 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005462 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005463 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005464 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005465 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005466 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005467 return destType;
5468 }
5469
5470 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5471 // Two identical pointer types are always compatible.
5472 return LHSTy;
5473 }
5474 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5475 rhptee.getUnqualifiedType())) {
5476 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5477 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5478 // In this situation, we assume void* type. No especially good
5479 // reason, but this is what gcc does, and we do have to pick
5480 // to get a consistent AST.
5481 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005482 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5483 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005484 return incompatTy;
5485 }
5486 // The pointer types are compatible.
5487 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5488 // differently qualified versions of compatible types, the result type is
5489 // a pointer to an appropriately qualified version of the *composite*
5490 // type.
5491 // FIXME: Need to calculate the composite type.
5492 // FIXME: Need to add qualifiers
John McCall2de56d12010-08-25 11:45:40 +00005493 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5494 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005495 return LHSTy;
5496 }
Mike Stump1eb44332009-09-09 15:08:12 +00005497
John McCall404cd162010-11-13 01:35:44 +00005498 // GCC compatibility: soften pointer/integer mismatch. Note that
5499 // null pointers have been filtered out by this point.
Steve Naroff7154a772009-07-01 14:36:47 +00005500 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5501 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5502 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005503 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005504 return RHSTy;
5505 }
5506 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5507 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5508 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005509 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005510 return LHSTy;
5511 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005512
Chandler Carruth82214a82011-02-18 23:54:50 +00005513 // Emit a better diagnostic if one of the expressions is a null pointer
5514 // constant and the other is not a pointer type. In this case, the user most
5515 // likely forgot to take the address of the other expression.
5516 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
5517 return QualType();
5518
Chris Lattner70d67a92008-01-06 22:42:25 +00005519 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005520 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5521 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005522 return QualType();
5523}
5524
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005525/// FindCompositeObjCPointerType - Helper method to find composite type of
5526/// two objective-c pointer types of the two input expressions.
5527QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5528 SourceLocation QuestionLoc) {
5529 QualType LHSTy = LHS->getType();
5530 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005531
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005532 // Handle things like Class and struct objc_class*. Here we case the result
5533 // to the pseudo-builtin, because that will be implicitly cast back to the
5534 // redefinition type if an attempt is made to access its fields.
5535 if (LHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005536 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005537 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005538 return LHSTy;
5539 }
5540 if (RHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005541 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005542 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005543 return RHSTy;
5544 }
5545 // And the same for struct objc_object* / id
5546 if (LHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005547 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005548 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005549 return LHSTy;
5550 }
5551 if (RHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005552 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005553 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005554 return RHSTy;
5555 }
5556 // And the same for struct objc_selector* / SEL
5557 if (Context.isObjCSelType(LHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00005558 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005559 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005560 return LHSTy;
5561 }
5562 if (Context.isObjCSelType(RHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00005563 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005564 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005565 return RHSTy;
5566 }
5567 // Check constraints for Objective-C object pointers types.
5568 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005569
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005570 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5571 // Two identical object pointer types are always compatible.
5572 return LHSTy;
5573 }
5574 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5575 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5576 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005577
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005578 // If both operands are interfaces and either operand can be
5579 // assigned to the other, use that type as the composite
5580 // type. This allows
5581 // xxx ? (A*) a : (B*) b
5582 // where B is a subclass of A.
5583 //
5584 // Additionally, as for assignment, if either type is 'id'
5585 // allow silent coercion. Finally, if the types are
5586 // incompatible then make sure to use 'id' as the composite
5587 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005588
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005589 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5590 // It could return the composite type.
5591 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5592 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5593 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5594 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5595 } else if ((LHSTy->isObjCQualifiedIdType() ||
5596 RHSTy->isObjCQualifiedIdType()) &&
5597 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5598 // Need to handle "id<xx>" explicitly.
5599 // GCC allows qualified id and any Objective-C type to devolve to
5600 // id. Currently localizing to here until clear this should be
5601 // part of ObjCQualifiedIdTypesAreCompatible.
5602 compositeType = Context.getObjCIdType();
5603 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5604 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005605 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005606 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5607 ;
5608 else {
5609 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5610 << LHSTy << RHSTy
5611 << LHS->getSourceRange() << RHS->getSourceRange();
5612 QualType incompatTy = Context.getObjCIdType();
John McCall2de56d12010-08-25 11:45:40 +00005613 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5614 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005615 return incompatTy;
5616 }
5617 // The object pointer types are compatible.
John McCall2de56d12010-08-25 11:45:40 +00005618 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5619 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005620 return compositeType;
5621 }
5622 // Check Objective-C object pointer types and 'void *'
5623 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5624 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5625 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5626 QualType destPointee
5627 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5628 QualType destType = Context.getPointerType(destPointee);
5629 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005630 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005631 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005632 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005633 return destType;
5634 }
5635 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5636 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5637 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5638 QualType destPointee
5639 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5640 QualType destType = Context.getPointerType(destPointee);
5641 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005642 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005643 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005644 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005645 return destType;
5646 }
5647 return QualType();
5648}
5649
Steve Narofff69936d2007-09-16 03:34:24 +00005650/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005651/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005652ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005653 SourceLocation ColonLoc,
5654 Expr *CondExpr, Expr *LHSExpr,
5655 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005656 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5657 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005658 OpaqueValueExpr *opaqueValue = 0;
5659 Expr *commonExpr = 0;
5660 if (LHSExpr == 0) {
5661 commonExpr = CondExpr;
5662
5663 // We usually want to apply unary conversions *before* saving, except
5664 // in the special case of a C++ l-value conditional.
5665 if (!(getLangOptions().CPlusPlus
5666 && !commonExpr->isTypeDependent()
5667 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5668 && commonExpr->isGLValue()
5669 && commonExpr->isOrdinaryOrBitFieldObject()
5670 && RHSExpr->isOrdinaryOrBitFieldObject()
5671 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5672 UsualUnaryConversions(commonExpr);
5673 }
5674
5675 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5676 commonExpr->getType(),
5677 commonExpr->getValueKind(),
5678 commonExpr->getObjectKind());
5679 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005680 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005681
John McCallf89e55a2010-11-18 06:31:45 +00005682 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005683 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian1fb019b2010-09-18 19:38:38 +00005684 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCall56ca35d2011-02-17 10:25:35 +00005685 VK, OK, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00005686 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005687 return ExprError();
5688
John McCall56ca35d2011-02-17 10:25:35 +00005689 if (!commonExpr)
5690 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
5691 LHSExpr, ColonLoc,
5692 RHSExpr, result, VK, OK));
5693
5694 return Owned(new (Context)
5695 BinaryConditionalOperator(commonExpr, opaqueValue, CondExpr, LHSExpr,
5696 RHSExpr, QuestionLoc, ColonLoc, result, VK, OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005697}
5698
John McCalle4be87e2011-01-31 23:13:11 +00005699// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005700// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005701// routine is it effectively iqnores the qualifiers on the top level pointee.
5702// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5703// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005704static Sema::AssignConvertType
5705checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5706 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5707 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005708
Reid Spencer5f016e22007-07-11 17:01:13 +00005709 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005710 const Type *lhptee, *rhptee;
5711 Qualifiers lhq, rhq;
5712 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5713 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005714
John McCalle4be87e2011-01-31 23:13:11 +00005715 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005716
5717 // C99 6.5.16.1p1: This following citation is common to constraints
5718 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5719 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005720 Qualifiers lq;
5721
5722 if (!lhq.compatiblyIncludes(rhq)) {
5723 // Treat address-space mismatches as fatal. TODO: address subspaces
5724 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5725 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5726
5727 // For GCC compatibility, other qualifier mismatches are treated
5728 // as still compatible in C.
5729 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5730 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005731
Mike Stumpeed9cac2009-02-19 03:04:26 +00005732 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5733 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005734 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005735 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005736 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005737 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005738
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005739 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005740 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005741 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005742 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005743
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005744 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005745 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005746 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005747
5748 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005749 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005750 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005751 }
John McCall86c05f32011-02-01 00:10:29 +00005752
Mike Stumpeed9cac2009-02-19 03:04:26 +00005753 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005754 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005755 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5756 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005757 // Check if the pointee types are compatible ignoring the sign.
5758 // We explicitly check for char so that we catch "char" vs
5759 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005760 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005761 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005762 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005763 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005764
Chris Lattner6a2b9262009-10-17 20:33:28 +00005765 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005766 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005767 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005768 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005769
John McCall86c05f32011-02-01 00:10:29 +00005770 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005771 // Types are compatible ignoring the sign. Qualifier incompatibility
5772 // takes priority over sign incompatibility because the sign
5773 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005774 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005775 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005776
John McCalle4be87e2011-01-31 23:13:11 +00005777 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005778 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005779
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005780 // If we are a multi-level pointer, it's possible that our issue is simply
5781 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5782 // the eventual target type is the same and the pointers have the same
5783 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005784 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005785 do {
John McCall86c05f32011-02-01 00:10:29 +00005786 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5787 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005788 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005789
John McCall86c05f32011-02-01 00:10:29 +00005790 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005791 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005792 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005793
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005794 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005795 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005796 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005797 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005798}
5799
John McCalle4be87e2011-01-31 23:13:11 +00005800/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005801/// block pointer types are compatible or whether a block and normal pointer
5802/// are compatible. It is more restrict than comparing two function pointer
5803// types.
John McCalle4be87e2011-01-31 23:13:11 +00005804static Sema::AssignConvertType
5805checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5806 QualType rhsType) {
5807 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5808 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5809
Steve Naroff1c7d0672008-09-04 15:10:53 +00005810 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005811
Steve Naroff1c7d0672008-09-04 15:10:53 +00005812 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00005813 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5814 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005815
John McCalle4be87e2011-01-31 23:13:11 +00005816 // In C++, the types have to match exactly.
5817 if (S.getLangOptions().CPlusPlus)
5818 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005819
John McCalle4be87e2011-01-31 23:13:11 +00005820 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005821
Steve Naroff1c7d0672008-09-04 15:10:53 +00005822 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005823 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5824 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005825
John McCalle4be87e2011-01-31 23:13:11 +00005826 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5827 return Sema::IncompatibleBlockPointer;
5828
Steve Naroff1c7d0672008-09-04 15:10:53 +00005829 return ConvTy;
5830}
5831
John McCalle4be87e2011-01-31 23:13:11 +00005832/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005833/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005834static Sema::AssignConvertType
5835checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5836 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5837 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5838
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005839 if (lhsType->isObjCBuiltinType()) {
5840 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005841 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5842 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005843 return Sema::IncompatiblePointer;
5844 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005845 }
5846 if (rhsType->isObjCBuiltinType()) {
5847 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005848 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5849 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005850 return Sema::IncompatiblePointer;
5851 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005852 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005853 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005854 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005855 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005856 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005857
John McCalle4be87e2011-01-31 23:13:11 +00005858 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5859 return Sema::CompatiblePointerDiscardsQualifiers;
5860
5861 if (S.Context.typesAreCompatible(lhsType, rhsType))
5862 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005863 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005864 return Sema::IncompatibleObjCQualifiedId;
5865 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005866}
5867
John McCall1c23e912010-11-16 02:32:08 +00005868Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005869Sema::CheckAssignmentConstraints(SourceLocation Loc,
5870 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00005871 // Fake up an opaque expression. We don't actually care about what
5872 // cast operations are required, so if CheckAssignmentConstraints
5873 // adds casts to this they'll be wasted, but fortunately that doesn't
5874 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00005875 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John McCall1c23e912010-11-16 02:32:08 +00005876 Expr *rhsPtr = &rhs;
5877 CastKind K = CK_Invalid;
5878
5879 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5880}
5881
Mike Stumpeed9cac2009-02-19 03:04:26 +00005882/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5883/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005884/// pointers. Here are some objectionable examples that GCC considers warnings:
5885///
5886/// int a, *pint;
5887/// short *pshort;
5888/// struct foo *pfoo;
5889///
5890/// pint = pshort; // warning: assignment from incompatible pointer type
5891/// a = pint; // warning: assignment makes integer from pointer without a cast
5892/// pint = a; // warning: assignment makes pointer from integer without a cast
5893/// pint = pfoo; // warning: assignment from incompatible pointer type
5894///
5895/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005896/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005897///
John McCalldaa8e4e2010-11-15 09:13:47 +00005898/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005899Sema::AssignConvertType
John McCall1c23e912010-11-16 02:32:08 +00005900Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00005901 CastKind &Kind) {
John McCall1c23e912010-11-16 02:32:08 +00005902 QualType rhsType = rhs->getType();
5903
Chris Lattnerfc144e22008-01-04 23:18:45 +00005904 // Get canonical types. We're not formatting these types, just comparing
5905 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005906 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5907 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005908
John McCallb6cfa242011-01-31 22:28:28 +00005909 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00005910 if (lhsType == rhsType) {
5911 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005912 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005913 }
5914
Douglas Gregor9d293df2008-10-28 00:22:11 +00005915 // If the left-hand side is a reference type, then we are in a
5916 // (rare!) case where we've allowed the use of references in C,
5917 // e.g., as a parameter type in a built-in function. In this case,
5918 // just make sure that the type referenced is compatible with the
5919 // right-hand side type. The caller is responsible for adjusting
5920 // lhsType so that the resulting expression does not have reference
5921 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005922 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005923 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5924 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005925 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005926 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005927 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005928 }
John McCallb6cfa242011-01-31 22:28:28 +00005929
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005930 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5931 // to the same ExtVector type.
5932 if (lhsType->isExtVectorType()) {
5933 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005934 return Incompatible;
5935 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005936 // CK_VectorSplat does T -> vector T, so first cast to the
5937 // element type.
5938 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5939 if (elType != rhsType) {
5940 Kind = PrepareScalarCast(*this, rhs, elType);
5941 ImpCastExprToType(rhs, elType, Kind);
5942 }
5943 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005944 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005945 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005946 }
Mike Stump1eb44332009-09-09 15:08:12 +00005947
John McCallb6cfa242011-01-31 22:28:28 +00005948 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005949 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00005950 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005951 // Allow assignments of an AltiVec vector type to an equivalent GCC
5952 // vector type and vice versa
5953 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5954 Kind = CK_BitCast;
5955 return Compatible;
5956 }
5957
Douglas Gregor255210e2010-08-06 10:14:59 +00005958 // If we are allowing lax vector conversions, and LHS and RHS are both
5959 // vectors, the total size only needs to be the same. This is a bitcast;
5960 // no bits are changed but the result type is different.
5961 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005962 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005963 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005964 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005965 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005966 }
5967 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005968 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005969
John McCallb6cfa242011-01-31 22:28:28 +00005970 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00005971 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005972 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00005973 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005974 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005975 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005976
John McCallb6cfa242011-01-31 22:28:28 +00005977 // Conversions to normal pointers.
5978 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5979 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00005980 if (isa<PointerType>(rhsType)) {
5981 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00005982 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005983 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005984
John McCallb6cfa242011-01-31 22:28:28 +00005985 // int -> T*
5986 if (rhsType->isIntegerType()) {
5987 Kind = CK_IntegralToPointer; // FIXME: null?
5988 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005989 }
John McCallb6cfa242011-01-31 22:28:28 +00005990
5991 // C pointers are not compatible with ObjC object pointers,
5992 // with two exceptions:
5993 if (isa<ObjCObjectPointerType>(rhsType)) {
5994 // - conversions to void*
5995 if (lhsPointer->getPointeeType()->isVoidType()) {
5996 Kind = CK_AnyPointerToObjCPointerCast;
5997 return Compatible;
5998 }
5999
6000 // - conversions from 'Class' to the redefinition type
6001 if (rhsType->isObjCClassType() &&
6002 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006003 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006004 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006005 }
Steve Naroffb4406862008-09-29 18:10:17 +00006006
John McCallb6cfa242011-01-31 22:28:28 +00006007 Kind = CK_BitCast;
6008 return IncompatiblePointer;
6009 }
6010
6011 // U^ -> void*
6012 if (rhsType->getAs<BlockPointerType>()) {
6013 if (lhsPointer->getPointeeType()->isVoidType()) {
6014 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006015 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006016 }
Steve Naroffb4406862008-09-29 18:10:17 +00006017 }
John McCallb6cfa242011-01-31 22:28:28 +00006018
Steve Naroff1c7d0672008-09-04 15:10:53 +00006019 return Incompatible;
6020 }
6021
John McCallb6cfa242011-01-31 22:28:28 +00006022 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00006023 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006024 // U^ -> T^
6025 if (rhsType->isBlockPointerType()) {
6026 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00006027 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006028 }
6029
6030 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006031 if (rhsType->isIntegerType()) {
6032 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00006033 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006034 }
6035
John McCallb6cfa242011-01-31 22:28:28 +00006036 // id -> T^
6037 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6038 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006039 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006040 }
Steve Naroffb4406862008-09-29 18:10:17 +00006041
John McCallb6cfa242011-01-31 22:28:28 +00006042 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006043 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00006044 if (RHSPT->getPointeeType()->isVoidType()) {
6045 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006046 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006047 }
John McCalldaa8e4e2010-11-15 09:13:47 +00006048
Chris Lattnerfc144e22008-01-04 23:18:45 +00006049 return Incompatible;
6050 }
6051
John McCallb6cfa242011-01-31 22:28:28 +00006052 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00006053 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006054 // A* -> B*
6055 if (rhsType->isObjCObjectPointerType()) {
6056 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006057 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006058 }
6059
6060 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00006061 if (rhsType->isIntegerType()) {
6062 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00006063 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006064 }
6065
John McCallb6cfa242011-01-31 22:28:28 +00006066 // In general, C pointers are not compatible with ObjC object pointers,
6067 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00006068 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006069 // - conversions from 'void*'
6070 if (rhsType->isVoidPointerType()) {
6071 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006072 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006073 }
6074
6075 // - conversions to 'Class' from its redefinition type
6076 if (lhsType->isObjCClassType() &&
6077 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6078 Kind = CK_BitCast;
6079 return Compatible;
6080 }
6081
6082 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006083 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006084 }
John McCallb6cfa242011-01-31 22:28:28 +00006085
6086 // T^ -> A*
6087 if (rhsType->isBlockPointerType()) {
6088 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00006089 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006090 }
6091
Steve Naroff14108da2009-07-10 23:34:53 +00006092 return Incompatible;
6093 }
John McCallb6cfa242011-01-31 22:28:28 +00006094
6095 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00006096 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006097 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006098 if (lhsType == Context.BoolTy) {
6099 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006100 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006101 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006102
John McCallb6cfa242011-01-31 22:28:28 +00006103 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006104 if (lhsType->isIntegerType()) {
6105 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006106 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006107 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006108
Chris Lattnerfc144e22008-01-04 23:18:45 +00006109 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00006110 }
John McCallb6cfa242011-01-31 22:28:28 +00006111
6112 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00006113 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006114 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006115 if (lhsType == Context.BoolTy) {
6116 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00006117 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006118 }
Steve Naroff14108da2009-07-10 23:34:53 +00006119
John McCallb6cfa242011-01-31 22:28:28 +00006120 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006121 if (lhsType->isIntegerType()) {
6122 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00006123 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006124 }
6125
Steve Naroff14108da2009-07-10 23:34:53 +00006126 return Incompatible;
6127 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006128
John McCallb6cfa242011-01-31 22:28:28 +00006129 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00006130 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006131 if (Context.typesAreCompatible(lhsType, rhsType)) {
6132 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00006133 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006134 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006135 }
John McCallb6cfa242011-01-31 22:28:28 +00006136
Reid Spencer5f016e22007-07-11 17:01:13 +00006137 return Incompatible;
6138}
6139
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006140/// \brief Constructs a transparent union from an expression that is
6141/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00006142static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006143 QualType UnionType, FieldDecl *Field) {
6144 // Build an initializer list that designates the appropriate member
6145 // of the transparent union.
Ted Kremenek709210f2010-04-13 23:39:13 +00006146 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00006147 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006148 SourceLocation());
6149 Initializer->setType(UnionType);
6150 Initializer->setInitializedFieldInUnion(Field);
6151
6152 // Build a compound literal constructing a value of the transparent
6153 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00006154 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall1d7d8d62010-01-19 22:33:45 +00006155 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCallf89e55a2010-11-18 06:31:45 +00006156 VK_RValue, Initializer, false);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006157}
6158
6159Sema::AssignConvertType
6160Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
6161 QualType FromType = rExpr->getType();
6162
Mike Stump1eb44332009-09-09 15:08:12 +00006163 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006164 // transparent_union GCC extension.
6165 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006166 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006167 return Incompatible;
6168
6169 // The field to initialize within the transparent union.
6170 RecordDecl *UD = UT->getDecl();
6171 FieldDecl *InitField = 0;
6172 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006173 for (RecordDecl::field_iterator it = UD->field_begin(),
6174 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006175 it != itend; ++it) {
6176 if (it->getType()->isPointerType()) {
6177 // If the transparent union contains a pointer type, we allow:
6178 // 1) void pointer
6179 // 2) null pointer constant
6180 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00006181 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCall2de56d12010-08-25 11:45:40 +00006182 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006183 InitField = *it;
6184 break;
6185 }
Mike Stump1eb44332009-09-09 15:08:12 +00006186
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006187 if (rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006188 Expr::NPC_ValueDependentIsNull)) {
John McCall404cd162010-11-13 01:35:44 +00006189 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006190 InitField = *it;
6191 break;
6192 }
6193 }
6194
John McCall1c23e912010-11-16 02:32:08 +00006195 Expr *rhs = rExpr;
John McCalldaa8e4e2010-11-15 09:13:47 +00006196 CastKind Kind = CK_Invalid;
John McCall1c23e912010-11-16 02:32:08 +00006197 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006198 == Compatible) {
John McCall1c23e912010-11-16 02:32:08 +00006199 ImpCastExprToType(rhs, it->getType(), Kind);
6200 rExpr = rhs;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006201 InitField = *it;
6202 break;
6203 }
6204 }
6205
6206 if (!InitField)
6207 return Incompatible;
6208
6209 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
6210 return Compatible;
6211}
6212
Chris Lattner5cf216b2008-01-04 18:04:52 +00006213Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00006214Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00006215 if (getLangOptions().CPlusPlus) {
6216 if (!lhsType->isRecordType()) {
6217 // C++ 5.17p3: If the left operand is not of class type, the
6218 // expression is implicitly converted (C++ 4) to the
6219 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00006220 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00006221 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00006222 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00006223 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00006224 }
6225
6226 // FIXME: Currently, we fall through and treat C++ classes like C
6227 // structures.
John McCallf6a16482010-12-04 03:47:34 +00006228 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00006229
Steve Naroff529a4ad2007-11-27 17:58:44 +00006230 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6231 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00006232 if ((lhsType->isPointerType() ||
6233 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00006234 lhsType->isBlockPointerType())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006235 && rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006236 Expr::NPC_ValueDependentIsNull)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006237 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00006238 return Compatible;
6239 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006240
Chris Lattner943140e2007-10-16 02:55:40 +00006241 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00006242 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00006243 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00006244 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00006245 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00006246 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00006247 if (!lhsType->isReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00006248 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00006249
John McCalldaa8e4e2010-11-15 09:13:47 +00006250 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006251 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00006252 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006253
Steve Narofff1120de2007-08-24 22:33:52 +00006254 // C99 6.5.16.1p2: The value of the right operand is converted to the
6255 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006256 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6257 // so that we can use references in built-in functions even in C.
6258 // The getNonReferenceType() call makes sure that the resulting expression
6259 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006260 if (result != Incompatible && rExpr->getType() != lhsType)
John McCalldaa8e4e2010-11-15 09:13:47 +00006261 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006262 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006263}
6264
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006265QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006266 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00006267 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006268 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00006269 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006270}
6271
Chris Lattner7ef655a2010-01-12 21:23:57 +00006272QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00006273 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006274 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00006275 QualType lhsType =
6276 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
6277 QualType rhsType =
6278 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006279
Nate Begemanbe2341d2008-07-14 18:02:46 +00006280 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006281 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00006282 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006283
Nate Begemanbe2341d2008-07-14 18:02:46 +00006284 // Handle the case of a vector & extvector type of the same size and element
6285 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006286 if (getLangOptions().LaxVectorConversions) {
John McCall183700f2009-09-21 23:43:11 +00006287 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth629f9e42010-08-30 07:36:24 +00006288 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006289 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006290 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregor26bcf672010-05-19 03:21:00 +00006291 if (lhsType->isExtVectorType()) {
John McCall2de56d12010-08-25 11:45:40 +00006292 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006293 return lhsType;
6294 }
6295
John McCall2de56d12010-08-25 11:45:40 +00006296 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006297 return rhsType;
Eric Christophere84f9eb2010-08-26 00:42:16 +00006298 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6299 // If we are allowing lax vector conversions, and LHS and RHS are both
6300 // vectors, the total size only needs to be the same. This is a
6301 // bitcast; no bits are changed but the result type is different.
6302 ImpCastExprToType(rex, lhsType, CK_BitCast);
6303 return lhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006304 }
Eric Christophere84f9eb2010-08-26 00:42:16 +00006305 }
Chandler Carruth629f9e42010-08-30 07:36:24 +00006306 }
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006307 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006308
Douglas Gregor255210e2010-08-06 10:14:59 +00006309 // Handle the case of equivalent AltiVec and GCC vector types
6310 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6311 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCall2de56d12010-08-25 11:45:40 +00006312 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00006313 return rhsType;
6314 }
6315
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006316 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6317 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6318 bool swapped = false;
6319 if (rhsType->isExtVectorType()) {
6320 swapped = true;
6321 std::swap(rex, lex);
6322 std::swap(rhsType, lhsType);
6323 }
Mike Stump1eb44332009-09-09 15:08:12 +00006324
Nate Begemandde25982009-06-28 19:12:57 +00006325 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00006326 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006327 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00006328 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006329 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6330 if (order > 0)
6331 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
6332 if (order >= 0) {
6333 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006334 if (swapped) std::swap(rex, lex);
6335 return lhsType;
6336 }
6337 }
6338 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6339 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006340 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6341 if (order > 0)
6342 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
6343 if (order >= 0) {
6344 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006345 if (swapped) std::swap(rex, lex);
6346 return lhsType;
6347 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006348 }
6349 }
Mike Stump1eb44332009-09-09 15:08:12 +00006350
Nate Begemandde25982009-06-28 19:12:57 +00006351 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006352 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00006353 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006354 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006355 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006356}
6357
Chris Lattner7ef655a2010-01-12 21:23:57 +00006358QualType Sema::CheckMultiplyDivideOperands(
6359 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00006360 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006361 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006362
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006363 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006364
Chris Lattner7ef655a2010-01-12 21:23:57 +00006365 if (!lex->getType()->isArithmeticType() ||
6366 !rex->getType()->isArithmeticType())
6367 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006368
Chris Lattner7ef655a2010-01-12 21:23:57 +00006369 // Check for division by zero.
6370 if (isDiv &&
6371 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Ted Kremenek762696f2011-02-23 01:51:43 +00006372 DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_division_by_zero)
6373 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006374
Chris Lattner7ef655a2010-01-12 21:23:57 +00006375 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006376}
6377
Chris Lattner7ef655a2010-01-12 21:23:57 +00006378QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00006379 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00006380 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006381 if (lex->getType()->hasIntegerRepresentation() &&
6382 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar523aa602009-01-05 22:55:36 +00006383 return CheckVectorOperands(Loc, lex, rex);
6384 return InvalidOperands(Loc, lex, rex);
6385 }
Steve Naroff90045e82007-07-13 23:32:42 +00006386
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006387 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006388
Chris Lattner7ef655a2010-01-12 21:23:57 +00006389 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6390 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006391
Chris Lattner7ef655a2010-01-12 21:23:57 +00006392 // Check for remainder by zero.
6393 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Ted Kremenek762696f2011-02-23 01:51:43 +00006394 DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_remainder_by_zero)
6395 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006396
Chris Lattner7ef655a2010-01-12 21:23:57 +00006397 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006398}
6399
Chris Lattner7ef655a2010-01-12 21:23:57 +00006400QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00006401 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006402 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6403 QualType compType = CheckVectorOperands(Loc, lex, rex);
6404 if (CompLHSTy) *CompLHSTy = compType;
6405 return compType;
6406 }
Steve Naroff49b45262007-07-13 16:58:59 +00006407
Eli Friedmanab3a8522009-03-28 01:22:36 +00006408 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006409
Reid Spencer5f016e22007-07-11 17:01:13 +00006410 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00006411 if (lex->getType()->isArithmeticType() &&
6412 rex->getType()->isArithmeticType()) {
6413 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006414 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006415 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006416
Eli Friedmand72d16e2008-05-18 18:08:51 +00006417 // Put any potential pointer into PExp
6418 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006419 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006420 std::swap(PExp, IExp);
6421
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006422 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006423
Eli Friedmand72d16e2008-05-18 18:08:51 +00006424 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00006425 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00006426
Chris Lattnerb5f15622009-04-24 23:50:08 +00006427 // Check for arithmetic on pointers to incomplete types.
6428 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006429 if (getLangOptions().CPlusPlus) {
6430 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006431 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006432 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006433 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006434
6435 // GNU extension: arithmetic on pointer to void
6436 Diag(Loc, diag::ext_gnu_void_ptr)
6437 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00006438 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006439 if (getLangOptions().CPlusPlus) {
6440 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6441 << lex->getType() << lex->getSourceRange();
6442 return QualType();
6443 }
6444
6445 // GNU extension: arithmetic on pointer to function
6446 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6447 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00006448 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00006449 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00006450 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00006451 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00006452 PExp->getType()->isObjCObjectPointerType()) &&
6453 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00006454 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6455 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006456 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00006457 return QualType();
6458 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00006459 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006460 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006461 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6462 << PointeeTy << PExp->getSourceRange();
6463 return QualType();
6464 }
Mike Stump1eb44332009-09-09 15:08:12 +00006465
Eli Friedmanab3a8522009-03-28 01:22:36 +00006466 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00006467 QualType LHSTy = Context.isPromotableBitField(lex);
6468 if (LHSTy.isNull()) {
6469 LHSTy = lex->getType();
6470 if (LHSTy->isPromotableIntegerType())
6471 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00006472 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00006473 *CompLHSTy = LHSTy;
6474 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00006475 return PExp->getType();
6476 }
6477 }
6478
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006479 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006480}
6481
Chris Lattnereca7be62008-04-07 05:30:13 +00006482// C99 6.5.6
6483QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006484 SourceLocation Loc, QualType* CompLHSTy) {
6485 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6486 QualType compType = CheckVectorOperands(Loc, lex, rex);
6487 if (CompLHSTy) *CompLHSTy = compType;
6488 return compType;
6489 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006490
Eli Friedmanab3a8522009-03-28 01:22:36 +00006491 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006492
Chris Lattner6e4ab612007-12-09 21:53:25 +00006493 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006494
Chris Lattner6e4ab612007-12-09 21:53:25 +00006495 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00006496 if (lex->getType()->isArithmeticType()
6497 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006498 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006499 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006500 }
Mike Stump1eb44332009-09-09 15:08:12 +00006501
Chris Lattner6e4ab612007-12-09 21:53:25 +00006502 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006503 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00006504 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006505
Douglas Gregore7450f52009-03-24 19:52:54 +00006506 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00006507
Douglas Gregore7450f52009-03-24 19:52:54 +00006508 bool ComplainAboutVoid = false;
6509 Expr *ComplainAboutFunc = 0;
6510 if (lpointee->isVoidType()) {
6511 if (getLangOptions().CPlusPlus) {
6512 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6513 << lex->getSourceRange() << rex->getSourceRange();
6514 return QualType();
6515 }
6516
6517 // GNU C extension: arithmetic on pointer to void
6518 ComplainAboutVoid = true;
6519 } else if (lpointee->isFunctionType()) {
6520 if (getLangOptions().CPlusPlus) {
6521 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00006522 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006523 return QualType();
6524 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006525
6526 // GNU C extension: arithmetic on pointer to function
6527 ComplainAboutFunc = lex;
6528 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006529 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00006530 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00006531 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006532 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00006533 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006534
Chris Lattnerb5f15622009-04-24 23:50:08 +00006535 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006536 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006537 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6538 << lpointee << lex->getSourceRange();
6539 return QualType();
6540 }
Mike Stump1eb44332009-09-09 15:08:12 +00006541
Chris Lattner6e4ab612007-12-09 21:53:25 +00006542 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00006543 if (rex->getType()->isIntegerType()) {
6544 if (ComplainAboutVoid)
6545 Diag(Loc, diag::ext_gnu_void_ptr)
6546 << lex->getSourceRange() << rex->getSourceRange();
6547 if (ComplainAboutFunc)
6548 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00006549 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00006550 << ComplainAboutFunc->getSourceRange();
6551
Eli Friedmanab3a8522009-03-28 01:22:36 +00006552 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006553 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006554 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006555
Chris Lattner6e4ab612007-12-09 21:53:25 +00006556 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006557 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006558 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006559
Douglas Gregore7450f52009-03-24 19:52:54 +00006560 // RHS must be a completely-type object type.
6561 // Handle the GNU void* extension.
6562 if (rpointee->isVoidType()) {
6563 if (getLangOptions().CPlusPlus) {
6564 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6565 << lex->getSourceRange() << rex->getSourceRange();
6566 return QualType();
6567 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006568
Douglas Gregore7450f52009-03-24 19:52:54 +00006569 ComplainAboutVoid = true;
6570 } else if (rpointee->isFunctionType()) {
6571 if (getLangOptions().CPlusPlus) {
6572 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00006573 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006574 return QualType();
6575 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006576
6577 // GNU extension: arithmetic on pointer to function
6578 if (!ComplainAboutFunc)
6579 ComplainAboutFunc = rex;
6580 } else if (!rpointee->isDependentType() &&
6581 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00006582 PDiag(diag::err_typecheck_sub_ptr_object)
6583 << rex->getSourceRange()
6584 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00006585 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006586
Eli Friedman88d936b2009-05-16 13:54:38 +00006587 if (getLangOptions().CPlusPlus) {
6588 // Pointee types must be the same: C++ [expr.add]
6589 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6590 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6591 << lex->getType() << rex->getType()
6592 << lex->getSourceRange() << rex->getSourceRange();
6593 return QualType();
6594 }
6595 } else {
6596 // Pointee types must be compatible C99 6.5.6p3
6597 if (!Context.typesAreCompatible(
6598 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6599 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6600 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6601 << lex->getType() << rex->getType()
6602 << lex->getSourceRange() << rex->getSourceRange();
6603 return QualType();
6604 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006605 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006606
Douglas Gregore7450f52009-03-24 19:52:54 +00006607 if (ComplainAboutVoid)
6608 Diag(Loc, diag::ext_gnu_void_ptr)
6609 << lex->getSourceRange() << rex->getSourceRange();
6610 if (ComplainAboutFunc)
6611 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00006612 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00006613 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006614
6615 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006616 return Context.getPointerDiffType();
6617 }
6618 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006619
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006620 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006621}
6622
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006623static bool isScopedEnumerationType(QualType T) {
6624 if (const EnumType *ET = dyn_cast<EnumType>(T))
6625 return ET->getDecl()->isScoped();
6626 return false;
6627}
6628
Chandler Carruth21206d52011-02-23 23:34:11 +00006629static void DiagnoseBadShiftValues(Sema& S, Expr *&lex, Expr *&rex,
6630 SourceLocation Loc, unsigned Opc,
6631 QualType LHSTy) {
6632 llvm::APSInt Right;
6633 // Check right/shifter operand
6634 if (rex->isValueDependent() || !rex->isIntegerConstantExpr(Right, S.Context))
6635 return;
6636
6637 if (Right.isNegative()) {
6638 S.Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6639 return;
6640 }
6641 llvm::APInt LeftBits(Right.getBitWidth(),
6642 S.Context.getTypeSize(lex->getType()));
6643 if (Right.uge(LeftBits)) {
6644 S.Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6645 return;
6646 }
6647 if (Opc != BO_Shl)
6648 return;
6649
6650 // When left shifting an ICE which is signed, we can check for overflow which
6651 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6652 // integers have defined behavior modulo one more than the maximum value
6653 // representable in the result type, so never warn for those.
6654 llvm::APSInt Left;
Chandler Carruth6c3c3f52011-02-24 00:03:53 +00006655 if (lex->isValueDependent() || !lex->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth21206d52011-02-23 23:34:11 +00006656 LHSTy->hasUnsignedIntegerRepresentation())
6657 return;
6658 llvm::APInt ResultBits =
6659 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6660 if (LeftBits.uge(ResultBits))
6661 return;
6662 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6663 Result = Result.shl(Right);
6664
6665 // If we are only missing a sign bit, this is less likely to result in actual
6666 // bugs -- if the result is cast back to an unsigned type, it will have the
6667 // expected value. Thus we place this behind a different warning that can be
6668 // turned off separately if needed.
6669 if (LeftBits == ResultBits - 1) {
6670 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
6671 << Result.toString(10) << LHSTy
6672 << lex->getSourceRange() << rex->getSourceRange();
6673 return;
6674 }
6675
6676 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6677 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
6678 << Left.getBitWidth() << lex->getSourceRange() << rex->getSourceRange();
6679}
6680
Chris Lattnereca7be62008-04-07 05:30:13 +00006681// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006682QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chandler Carruth21206d52011-02-23 23:34:11 +00006683 unsigned Opc, bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00006684 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregorf6094622010-07-23 15:58:24 +00006685 if (!lex->getType()->hasIntegerRepresentation() ||
6686 !rex->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006687 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006688
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006689 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6690 // hasIntegerRepresentation() above instead of this.
6691 if (isScopedEnumerationType(lex->getType()) ||
6692 isScopedEnumerationType(rex->getType())) {
6693 return InvalidOperands(Loc, lex, rex);
6694 }
6695
Nate Begeman2207d792009-10-25 02:26:48 +00006696 // Vector shifts promote their scalar inputs to vector type.
6697 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6698 return CheckVectorOperands(Loc, lex, rex);
6699
Chris Lattnerca5eede2007-12-12 05:47:28 +00006700 // Shifts don't perform usual arithmetic conversions, they just do integer
6701 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006702
John McCall1bc80af2010-12-16 19:28:59 +00006703 // For the LHS, do usual unary conversions, but then reset them away
6704 // if this is a compound assignment.
6705 Expr *old_lex = lex;
6706 UsualUnaryConversions(lex);
6707 QualType LHSTy = lex->getType();
6708 if (isCompAssign) lex = old_lex;
6709
6710 // The RHS is simpler.
Chris Lattnerca5eede2007-12-12 05:47:28 +00006711 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006712
Ryan Flynnd0439682009-08-07 16:20:20 +00006713 // Sanity-check shift operands
Chandler Carruth21206d52011-02-23 23:34:11 +00006714 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnd0439682009-08-07 16:20:20 +00006715
Chris Lattnerca5eede2007-12-12 05:47:28 +00006716 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00006717 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006718}
6719
Chandler Carruth99919472010-07-10 12:30:03 +00006720static bool IsWithinTemplateSpecialization(Decl *D) {
6721 if (DeclContext *DC = D->getDeclContext()) {
6722 if (isa<ClassTemplateSpecializationDecl>(DC))
6723 return true;
6724 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6725 return FD->isFunctionTemplateSpecialization();
6726 }
6727 return false;
6728}
6729
Douglas Gregor0c6db942009-05-04 06:07:12 +00006730// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006731QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00006732 unsigned OpaqueOpc, bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00006733 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006734
Chris Lattner02dd4b12009-12-05 05:40:13 +00006735 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00006736 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006737 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006738
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006739 QualType lType = lex->getType();
6740 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006741
Chandler Carruth543cb652011-02-17 08:37:06 +00006742 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6743 Expr *RHSStripped = rex->IgnoreParenImpCasts();
6744 QualType LHSStrippedType = LHSStripped->getType();
6745 QualType RHSStrippedType = RHSStripped->getType();
6746
6747 // Two different enums will raise a warning when compared.
6748 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6749 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6750 if (LHSEnumType->getDecl()->getIdentifier() &&
6751 RHSEnumType->getDecl()->getIdentifier() &&
6752 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6753 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6754 << LHSStrippedType << RHSStrippedType
6755 << lex->getSourceRange() << rex->getSourceRange();
6756 }
6757 }
6758 }
6759
Douglas Gregor8eee1192010-06-22 22:12:46 +00006760 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006761 !(lType->isBlockPointerType() && isRelational) &&
6762 !lex->getLocStart().isMacroID() &&
6763 !rex->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006764 // For non-floating point types, check for self-comparisons of the form
6765 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6766 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006767 //
6768 // NOTE: Don't warn about comparison expressions resulting from macro
6769 // expansion. Also don't warn about comparisons which are only self
6770 // comparisons within a template specialization. The warnings should catch
6771 // obvious cases in the definition of the template anyways. The idea is to
6772 // warn when the typed comparison operator will always evaluate to the same
6773 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006774 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006775 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006776 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006777 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006778 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006779 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006780 << (Opc == BO_EQ
6781 || Opc == BO_LE
6782 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00006783 } else if (lType->isArrayType() && rType->isArrayType() &&
6784 !DRL->getDecl()->getType()->isReferenceType() &&
6785 !DRR->getDecl()->getType()->isReferenceType()) {
6786 // what is it always going to eval to?
6787 char always_evals_to;
6788 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006789 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006790 always_evals_to = 0; // false
6791 break;
John McCall2de56d12010-08-25 11:45:40 +00006792 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006793 always_evals_to = 1; // true
6794 break;
6795 default:
6796 // best we can say is 'a constant'
6797 always_evals_to = 2; // e.g. array1 <= array2
6798 break;
6799 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006800 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006801 << 1 // array
6802 << always_evals_to);
6803 }
6804 }
Chandler Carruth99919472010-07-10 12:30:03 +00006805 }
Mike Stump1eb44332009-09-09 15:08:12 +00006806
Chris Lattner55660a72009-03-08 19:39:53 +00006807 if (isa<CastExpr>(LHSStripped))
6808 LHSStripped = LHSStripped->IgnoreParenCasts();
6809 if (isa<CastExpr>(RHSStripped))
6810 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006811
Chris Lattner55660a72009-03-08 19:39:53 +00006812 // Warn about comparisons against a string constant (unless the other
6813 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006814 Expr *literalString = 0;
6815 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006816 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006817 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006818 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00006819 literalString = lex;
6820 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006821 } else if ((isa<StringLiteral>(RHSStripped) ||
6822 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006823 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006824 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00006825 literalString = rex;
6826 literalStringStripped = RHSStripped;
6827 }
6828
6829 if (literalString) {
6830 std::string resultComparison;
6831 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006832 case BO_LT: resultComparison = ") < 0"; break;
6833 case BO_GT: resultComparison = ") > 0"; break;
6834 case BO_LE: resultComparison = ") <= 0"; break;
6835 case BO_GE: resultComparison = ") >= 0"; break;
6836 case BO_EQ: resultComparison = ") == 0"; break;
6837 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00006838 default: assert(false && "Invalid comparison operator");
6839 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006840
Ted Kremenek351ba912011-02-23 01:52:04 +00006841 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006842 PDiag(diag::warn_stringcompare)
6843 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006844 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006845 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006846 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006847
Douglas Gregord64fdd02010-06-08 19:50:34 +00006848 // C99 6.5.8p3 / C99 6.5.9p4
6849 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6850 UsualArithmeticConversions(lex, rex);
6851 else {
6852 UsualUnaryConversions(lex);
6853 UsualUnaryConversions(rex);
6854 }
6855
6856 lType = lex->getType();
6857 rType = rex->getType();
6858
Douglas Gregor447b69e2008-11-19 03:25:36 +00006859 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006860 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006861
Chris Lattnera5937dd2007-08-26 01:18:55 +00006862 if (isRelational) {
6863 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006864 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006865 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006866 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006867 if (lType->hasFloatingRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006868 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006869
Chris Lattnera5937dd2007-08-26 01:18:55 +00006870 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006871 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006872 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006873
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006874 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006875 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006876 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006877 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006878
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006879 // All of the following pointer-related warnings are GCC extensions, except
6880 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00006881 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006882 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006883 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00006884 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006885 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006886
Douglas Gregor0c6db942009-05-04 06:07:12 +00006887 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006888 if (LCanPointeeTy == RCanPointeeTy)
6889 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006890 if (!isRelational &&
6891 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6892 // Valid unless comparison between non-null pointer and function pointer
6893 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006894 // In a SFINAE context, we treat this as a hard error to maintain
6895 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006896 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6897 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006898 Diag(Loc,
6899 isSFINAEContext()?
6900 diag::err_typecheck_comparison_of_fptr_to_void
6901 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006902 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006903
6904 if (isSFINAEContext())
6905 return QualType();
6906
John McCall2de56d12010-08-25 11:45:40 +00006907 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006908 return ResultTy;
6909 }
6910 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006911
Douglas Gregor0c6db942009-05-04 06:07:12 +00006912 // C++ [expr.rel]p2:
6913 // [...] Pointer conversions (4.10) and qualification
6914 // conversions (4.4) are performed on pointer operands (or on
6915 // a pointer operand and a null pointer constant) to bring
6916 // them to their composite pointer type. [...]
6917 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00006918 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00006919 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006920 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006921 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006922 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006923 if (T.isNull()) {
6924 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6925 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6926 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006927 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006928 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006929 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006930 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006931 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00006932 }
6933
John McCall2de56d12010-08-25 11:45:40 +00006934 ImpCastExprToType(lex, T, CK_BitCast);
6935 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006936 return ResultTy;
6937 }
Eli Friedman3075e762009-08-23 00:27:47 +00006938 // C99 6.5.9p2 and C99 6.5.8p2
6939 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6940 RCanPointeeTy.getUnqualifiedType())) {
6941 // Valid unless a relational comparison of function pointers
6942 if (isRelational && LCanPointeeTy->isFunctionType()) {
6943 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6944 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6945 }
6946 } else if (!isRelational &&
6947 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6948 // Valid unless comparison between non-null pointer and function pointer
6949 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6950 && !LHSIsNull && !RHSIsNull) {
6951 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6952 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6953 }
6954 } else {
6955 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006956 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00006957 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006958 }
Eli Friedman3075e762009-08-23 00:27:47 +00006959 if (LCanPointeeTy != RCanPointeeTy)
John McCall2de56d12010-08-25 11:45:40 +00006960 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006961 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00006962 }
Mike Stump1eb44332009-09-09 15:08:12 +00006963
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006964 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006965 // Comparison of nullptr_t with itself.
6966 if (lType->isNullPtrType() && rType->isNullPtrType())
6967 return ResultTy;
6968
Mike Stump1eb44332009-09-09 15:08:12 +00006969 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00006970 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00006971 if (RHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006972 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00006973 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregor443c2122010-08-07 13:36:37 +00006974 ImpCastExprToType(rex, lType,
6975 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006976 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006977 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006978 return ResultTy;
6979 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006980 if (LHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006981 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00006982 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregor443c2122010-08-07 13:36:37 +00006983 ImpCastExprToType(lex, rType,
6984 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006985 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006986 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006987 return ResultTy;
6988 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006989
6990 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00006991 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00006992 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6993 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006994 // In addition, pointers to members can be compared, or a pointer to
6995 // member and a null pointer constant. Pointer to member conversions
6996 // (4.11) and qualification conversions (4.4) are performed to bring
6997 // them to a common type. If one operand is a null pointer constant,
6998 // the common type is the type of the other operand. Otherwise, the
6999 // common type is a pointer to member type similar (4.4) to the type
7000 // of one of the operands, with a cv-qualification signature (4.4)
7001 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00007002 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007003 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00007004 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007005 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00007006 if (T.isNull()) {
7007 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007008 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00007009 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007010 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007011 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007012 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007013 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007014 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00007015 }
Mike Stump1eb44332009-09-09 15:08:12 +00007016
John McCall2de56d12010-08-25 11:45:40 +00007017 ImpCastExprToType(lex, T, CK_BitCast);
7018 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00007019 return ResultTy;
7020 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007021 }
Mike Stump1eb44332009-09-09 15:08:12 +00007022
Steve Naroff1c7d0672008-09-04 15:10:53 +00007023 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007024 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00007025 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7026 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007027
Steve Naroff1c7d0672008-09-04 15:10:53 +00007028 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007029 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007030 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00007031 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007032 }
John McCall2de56d12010-08-25 11:45:40 +00007033 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007034 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007035 }
Steve Naroff59f53942008-09-28 01:11:11 +00007036 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007037 if (!isRelational
7038 && ((lType->isBlockPointerType() && rType->isPointerType())
7039 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007040 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00007041 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007042 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00007043 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007044 ->getPointeeType()->isVoidType())))
7045 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7046 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007047 }
John McCall2de56d12010-08-25 11:45:40 +00007048 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007049 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007050 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007051
Steve Naroff14108da2009-07-10 23:34:53 +00007052 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00007053 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00007054 const PointerType *LPT = lType->getAs<PointerType>();
7055 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007056 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00007057 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007058 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00007059 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007060
Steve Naroffa8069f12008-11-17 19:49:16 +00007061 if (!LPtrToVoid && !RPtrToVoid &&
7062 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007063 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00007064 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00007065 }
John McCall2de56d12010-08-25 11:45:40 +00007066 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007067 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007068 }
Steve Naroff14108da2009-07-10 23:34:53 +00007069 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007070 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00007071 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
7072 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00007073 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007074 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007075 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007076 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007077 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7078 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007079 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007080 bool isError = false;
7081 if ((LHSIsNull && lType->isIntegerType()) ||
7082 (RHSIsNull && rType->isIntegerType())) {
7083 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007084 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007085 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007086 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007087 else if (getLangOptions().CPlusPlus) {
7088 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7089 isError = true;
7090 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007091 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007092
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007093 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007094 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00007095 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007096 if (isError)
7097 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007098 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007099
7100 if (lType->isIntegerType())
John McCall404cd162010-11-13 01:35:44 +00007101 ImpCastExprToType(lex, rType,
7102 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007103 else
John McCall404cd162010-11-13 01:35:44 +00007104 ImpCastExprToType(rex, lType,
7105 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007106 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007107 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007108
Steve Naroff39218df2008-09-04 16:56:14 +00007109 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00007110 if (!isRelational && RHSIsNull
7111 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCall404cd162010-11-13 01:35:44 +00007112 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007113 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007114 }
Mike Stumpaf199f32009-05-07 18:43:07 +00007115 if (!isRelational && LHSIsNull
7116 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCall404cd162010-11-13 01:35:44 +00007117 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007118 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007119 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007120 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007121}
7122
Nate Begemanbe2341d2008-07-14 18:02:46 +00007123/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007124/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007125/// like a scalar comparison, a vector comparison produces a vector of integer
7126/// types.
7127QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007128 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007129 bool isRelational) {
7130 // Check to make sure we're operating on vectors of the same type and width,
7131 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007132 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007133 if (vType.isNull())
7134 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007135
Anton Yartsevaa4fe052010-11-18 03:19:30 +00007136 // If AltiVec, the comparison results in a numeric type, i.e.
7137 // bool for C++, int for C
7138 if (getLangOptions().AltiVec)
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007139 return Context.getLogicalOperationType();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00007140
Nate Begemanbe2341d2008-07-14 18:02:46 +00007141 QualType lType = lex->getType();
7142 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007143
Nate Begemanbe2341d2008-07-14 18:02:46 +00007144 // For non-floating point types, check for self-comparisons of the form
7145 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7146 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007147 if (!lType->hasFloatingRepresentation()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007148 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
7149 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
7150 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007151 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007152 PDiag(diag::warn_comparison_always)
7153 << 0 // self-
7154 << 2 // "a constant"
7155 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007156 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007157
Nate Begemanbe2341d2008-07-14 18:02:46 +00007158 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007159 if (!isRelational && lType->hasFloatingRepresentation()) {
7160 assert (rType->hasFloatingRepresentation());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007161 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007162 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007163
Nate Begemanbe2341d2008-07-14 18:02:46 +00007164 // Return the type for the comparison, which is the same as vector type for
7165 // integer vectors, or an integer type of identical size and number of
7166 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00007167 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00007168 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007169
John McCall183700f2009-09-21 23:43:11 +00007170 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00007171 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00007172 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007173 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00007174 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00007175 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7176
Mike Stumpeed9cac2009-02-19 03:04:26 +00007177 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00007178 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00007179 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7180}
7181
Reid Spencer5f016e22007-07-11 17:01:13 +00007182inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00007183 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregorf6094622010-07-23 15:58:24 +00007184 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
7185 if (lex->getType()->hasIntegerRepresentation() &&
7186 rex->getType()->hasIntegerRepresentation())
7187 return CheckVectorOperands(Loc, lex, rex);
7188
7189 return InvalidOperands(Loc, lex, rex);
7190 }
Steve Naroff90045e82007-07-13 23:32:42 +00007191
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007192 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007193
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007194 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
7195 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007196 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007197 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007198}
7199
7200inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner90a8f272010-07-13 19:41:32 +00007201 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
7202
7203 // Diagnose cases where the user write a logical and/or but probably meant a
7204 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7205 // is a constant.
7206 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman787b0942010-07-27 19:14:53 +00007207 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattner23ef3e42010-07-15 00:26:43 +00007208 // Don't warn in macros.
Chris Lattnerb7690b42010-07-24 01:10:11 +00007209 !Loc.isMacroID()) {
7210 // If the RHS can be constant folded, and if it constant folds to something
7211 // that isn't 0 or 1 (which indicate a potential logical operation that
7212 // happened to fold to true/false) then warn.
7213 Expr::EvalResult Result;
7214 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
7215 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7216 Diag(Loc, diag::warn_logical_instead_of_bitwise)
7217 << rex->getSourceRange()
John McCall2de56d12010-08-25 11:45:40 +00007218 << (Opc == BO_LAnd ? "&&" : "||")
7219 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattnerb7690b42010-07-24 01:10:11 +00007220 }
7221 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007222
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007223 if (!Context.getLangOptions().CPlusPlus) {
7224 UsualUnaryConversions(lex);
7225 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007226
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007227 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
7228 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007229
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007230 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007231 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007232
John McCall75f7c0f2010-06-04 00:29:51 +00007233 // The following is safe because we only use this method for
7234 // non-overloadable operands.
7235
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007236 // C++ [expr.log.and]p1
7237 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007238 // The operands are both contextually converted to type bool.
7239 if (PerformContextuallyConvertToBool(lex) ||
7240 PerformContextuallyConvertToBool(rex))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007241 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007242
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007243 // C++ [expr.log.and]p2
7244 // C++ [expr.log.or]p2
7245 // The result is a bool.
7246 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007247}
7248
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007249/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7250/// is a read-only property; return true if so. A readonly property expression
7251/// depends on various declarations and thus must be treated specially.
7252///
Mike Stump1eb44332009-09-09 15:08:12 +00007253static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007254 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7255 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00007256 if (PropExpr->isImplicitProperty()) return false;
7257
7258 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7259 QualType BaseType = PropExpr->isSuperReceiver() ?
7260 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007261 PropExpr->getBase()->getType();
7262
John McCall12f78a62010-12-02 01:19:52 +00007263 if (const ObjCObjectPointerType *OPT =
7264 BaseType->getAsObjCInterfacePointerType())
7265 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7266 if (S.isPropertyReadonly(PDecl, IFace))
7267 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007268 }
7269 return false;
7270}
7271
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007272/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7273/// emit an error and return true. If so, return false.
7274static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007275 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007276 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007277 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007278 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7279 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007280 if (IsLV == Expr::MLV_Valid)
7281 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007282
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007283 unsigned Diag = 0;
7284 bool NeedType = false;
7285 switch (IsLV) { // C99 6.5.16p2
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007286 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007287 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007288 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7289 NeedType = true;
7290 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007291 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007292 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7293 NeedType = true;
7294 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007295 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007296 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7297 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007298 case Expr::MLV_Valid:
7299 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007300 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007301 case Expr::MLV_MemberFunction:
7302 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007303 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7304 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007305 case Expr::MLV_IncompleteType:
7306 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007307 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007308 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00007309 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00007310 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007311 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7312 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00007313 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007314 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7315 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007316 case Expr::MLV_ReadonlyProperty:
7317 Diag = diag::error_readonly_property_assignment;
7318 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007319 case Expr::MLV_NoSetterProperty:
7320 Diag = diag::error_nosetter_property_assignment;
7321 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007322 case Expr::MLV_SubObjCPropertySetting:
7323 Diag = diag::error_no_subobject_property_setting;
7324 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007325 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007326
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007327 SourceRange Assign;
7328 if (Loc != OrigLoc)
7329 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007330 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007331 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007332 else
Mike Stump1eb44332009-09-09 15:08:12 +00007333 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007334 return true;
7335}
7336
7337
7338
7339// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007340QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
7341 SourceLocation Loc,
7342 QualType CompoundType) {
7343 // Verify that LHS is a modifiable lvalue, and emit error if not.
7344 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007345 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007346
7347 QualType LHSType = LHS->getType();
7348 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007349 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007350 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007351 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007352 // Simple assignment "x = y".
John McCallf6a16482010-12-04 03:47:34 +00007353 if (LHS->getObjectKind() == OK_ObjCProperty)
7354 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007355 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007356 // Special case of NSObject attributes on c-style pointer types.
7357 if (ConvTy == IncompatiblePointer &&
7358 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007359 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007360 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007361 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007362 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007363
John McCallf89e55a2010-11-18 06:31:45 +00007364 if (ConvTy == Compatible &&
7365 getLangOptions().ObjCNonFragileABI &&
7366 LHSType->isObjCObjectType())
7367 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7368 << LHSType;
7369
Chris Lattner2c156472008-08-21 18:04:13 +00007370 // If the RHS is a unary plus or minus, check to see if they = and + are
7371 // right next to each other. If so, the user may have typo'd "x =+ 4"
7372 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007373 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00007374 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7375 RHSCheck = ICE->getSubExpr();
7376 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007377 if ((UO->getOpcode() == UO_Plus ||
7378 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007379 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007380 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00007381 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7382 // And there is a space or other character before the subexpr of the
7383 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00007384 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7385 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007386 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007387 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007388 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007389 }
Chris Lattner2c156472008-08-21 18:04:13 +00007390 }
7391 } else {
7392 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007393 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007394 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007395
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007396 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00007397 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007398 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007399
Chris Lattner8b5dec32010-07-07 06:14:23 +00007400
7401 // Check to see if the destination operand is a dereferenced null pointer. If
7402 // so, and if not volatile-qualified, this is undefined behavior that the
7403 // optimizer will delete, so warn about it. People sometimes try to use this
7404 // to get a deterministic trap and are surprised by clang's behavior. This
7405 // only handles the pattern "*null = whatever", which is a very syntactic
7406 // check.
7407 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCall2de56d12010-08-25 11:45:40 +00007408 if (UO->getOpcode() == UO_Deref &&
Chris Lattner8b5dec32010-07-07 06:14:23 +00007409 UO->getSubExpr()->IgnoreParenCasts()->
7410 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7411 !UO->getType().isVolatileQualified()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00007412 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7413 PDiag(diag::warn_indirection_through_null)
7414 << UO->getSubExpr()->getSourceRange());
7415 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7416 PDiag(diag::note_indirection_through_null));
Chris Lattner8b5dec32010-07-07 06:14:23 +00007417 }
7418
Ted Kremeneka0125d82011-02-16 01:57:07 +00007419 // Check for trivial buffer overflows.
7420 if (const ArraySubscriptExpr *ae
7421 = dyn_cast<ArraySubscriptExpr>(LHS->IgnoreParenCasts()))
7422 CheckArrayAccess(ae);
7423
Reid Spencer5f016e22007-07-11 17:01:13 +00007424 // C99 6.5.16p3: The type of an assignment expression is the type of the
7425 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007426 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007427 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7428 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007429 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007430 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00007431 return (getLangOptions().CPlusPlus
7432 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007433}
7434
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007435// C99 6.5.17
John McCallf6a16482010-12-04 03:47:34 +00007436static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall09431682010-11-18 19:01:18 +00007437 SourceLocation Loc) {
7438 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00007439
John McCall09431682010-11-18 19:01:18 +00007440 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007441 if (LHSResult.isInvalid())
7442 return QualType();
7443
John McCall09431682010-11-18 19:01:18 +00007444 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007445 if (RHSResult.isInvalid())
7446 return QualType();
7447 RHS = RHSResult.take();
7448
John McCallcf2e5062010-10-12 07:14:40 +00007449 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7450 // operands, but not unary promotions.
7451 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007452
John McCallf6a16482010-12-04 03:47:34 +00007453 // So we treat the LHS as a ignored value, and in C++ we allow the
7454 // containing site to determine what should be done with the RHS.
7455 S.IgnoredValueConversions(LHS);
7456
7457 if (!S.getLangOptions().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007458 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCallcf2e5062010-10-12 07:14:40 +00007459 if (!RHS->getType()->isVoidType())
John McCall09431682010-11-18 19:01:18 +00007460 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007461 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007462
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007463 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007464}
7465
Steve Naroff49b45262007-07-13 16:58:59 +00007466/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7467/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007468static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7469 ExprValueKind &VK,
7470 SourceLocation OpLoc,
7471 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007472 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007473 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007474
Chris Lattner3528d352008-11-21 07:05:48 +00007475 QualType ResType = Op->getType();
7476 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007477
John McCall09431682010-11-18 19:01:18 +00007478 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007479 // Decrement of bool is not allowed.
7480 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00007481 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007482 return QualType();
7483 }
7484 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007485 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007486 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007487 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007488 } else if (ResType->isAnyPointerType()) {
7489 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00007490
Chris Lattner3528d352008-11-21 07:05:48 +00007491 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00007492 if (PointeeTy->isVoidType()) {
John McCall09431682010-11-18 19:01:18 +00007493 if (S.getLangOptions().CPlusPlus) {
7494 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00007495 << Op->getSourceRange();
7496 return QualType();
7497 }
7498
7499 // Pointer to void is a GNU extension in C.
John McCall09431682010-11-18 19:01:18 +00007500 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00007501 } else if (PointeeTy->isFunctionType()) {
John McCall09431682010-11-18 19:01:18 +00007502 if (S.getLangOptions().CPlusPlus) {
7503 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00007504 << Op->getType() << Op->getSourceRange();
7505 return QualType();
7506 }
7507
John McCall09431682010-11-18 19:01:18 +00007508 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00007509 << ResType << Op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007510 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7511 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00007512 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00007513 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007514 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007515 // Diagnose bad cases where we step over interface counts.
John McCall09431682010-11-18 19:01:18 +00007516 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7517 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007518 << PointeeTy << Op->getSourceRange();
7519 return QualType();
7520 }
Eli Friedman5b088a12010-01-03 00:20:48 +00007521 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007522 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007523 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007524 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007525 } else if (ResType->isPlaceholderType()) {
John McCall09431682010-11-18 19:01:18 +00007526 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007527 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007528 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7529 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00007530 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7531 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007532 } else {
John McCall09431682010-11-18 19:01:18 +00007533 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00007534 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007535 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007536 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007537 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007538 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007539 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007540 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007541 // In C++, a prefix increment is the same type as the operand. Otherwise
7542 // (in C or with postfix), the increment is the unqualified type of the
7543 // operand.
John McCall09431682010-11-18 19:01:18 +00007544 if (isPrefix && S.getLangOptions().CPlusPlus) {
7545 VK = VK_LValue;
7546 return ResType;
7547 } else {
7548 VK = VK_RValue;
7549 return ResType.getUnqualifiedType();
7550 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007551}
7552
John McCallf6a16482010-12-04 03:47:34 +00007553void Sema::ConvertPropertyForRValue(Expr *&E) {
7554 assert(E->getValueKind() == VK_LValue &&
7555 E->getObjectKind() == OK_ObjCProperty);
7556 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7557
7558 ExprValueKind VK = VK_RValue;
7559 if (PRE->isImplicitProperty()) {
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007560 if (const ObjCMethodDecl *GetterMethod =
7561 PRE->getImplicitPropertyGetter()) {
7562 QualType Result = GetterMethod->getResultType();
7563 VK = Expr::getValueKindForType(Result);
7564 }
7565 else {
7566 Diag(PRE->getLocation(), diag::err_getter_not_found)
7567 << PRE->getBase()->getType();
7568 }
John McCallf6a16482010-12-04 03:47:34 +00007569 }
7570
7571 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7572 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00007573
7574 ExprResult Result = MaybeBindToTemporary(E);
7575 if (!Result.isInvalid())
7576 E = Result.take();
John McCallf6a16482010-12-04 03:47:34 +00007577}
7578
7579void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7580 assert(LHS->getValueKind() == VK_LValue &&
7581 LHS->getObjectKind() == OK_ObjCProperty);
7582 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7583
7584 if (PRE->isImplicitProperty()) {
7585 // If using property-dot syntax notation for assignment, and there is a
7586 // setter, RHS expression is being passed to the setter argument. So,
7587 // type conversion (and comparison) is RHS to setter's argument type.
7588 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7589 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7590 LHSTy = (*P)->getType();
7591
7592 // Otherwise, if the getter returns an l-value, just call that.
7593 } else {
7594 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7595 ExprValueKind VK = Expr::getValueKindForType(Result);
7596 if (VK == VK_LValue) {
7597 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7598 CK_GetObjCProperty, LHS, 0, VK);
7599 return;
John McCall12f78a62010-12-02 01:19:52 +00007600 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007601 }
John McCallf6a16482010-12-04 03:47:34 +00007602 }
7603
7604 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007605 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007606 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007607 Expr *Arg = RHS;
7608 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7609 Owned(Arg));
7610 if (!ArgE.isInvalid())
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007611 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007612 }
7613}
7614
7615
Anders Carlsson369dee42008-02-01 07:15:58 +00007616/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007617/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007618/// where the declaration is needed for type checking. We only need to
7619/// handle cases when the expression references a function designator
7620/// or is an lvalue. Here are some examples:
7621/// - &(x) => x
7622/// - &*****f => f for f a function designator.
7623/// - &s.xx => s
7624/// - &s.zz[1].yy -> s, if zz is an array
7625/// - *(x + 1) -> x, if x is an array
7626/// - &"123"[2] -> 0
7627/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007628static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007629 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007630 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007631 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007632 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007633 // If this is an arrow operator, the address is an offset from
7634 // the base's value, so the object the base refers to is
7635 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007636 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007637 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007638 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007639 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007640 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007641 // FIXME: This code shouldn't be necessary! We should catch the implicit
7642 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007643 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7644 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7645 if (ICE->getSubExpr()->getType()->isArrayType())
7646 return getPrimaryDecl(ICE->getSubExpr());
7647 }
7648 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007649 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007650 case Stmt::UnaryOperatorClass: {
7651 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007652
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007653 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007654 case UO_Real:
7655 case UO_Imag:
7656 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007657 return getPrimaryDecl(UO->getSubExpr());
7658 default:
7659 return 0;
7660 }
7661 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007662 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007663 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007664 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007665 // If the result of an implicit cast is an l-value, we care about
7666 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007667 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007668 default:
7669 return 0;
7670 }
7671}
7672
7673/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007674/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007675/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007676/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007677/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007678/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007679/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00007680static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7681 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00007682 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007683 return S.Context.DependentTy;
7684 if (OrigOp->getType() == S.Context.OverloadTy)
7685 return S.Context.OverloadTy;
John McCall9c72c602010-08-27 09:08:28 +00007686
John McCall09431682010-11-18 19:01:18 +00007687 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007688 if (PR.isInvalid()) return QualType();
7689 OrigOp = PR.take();
7690
John McCall9c72c602010-08-27 09:08:28 +00007691 // Make sure to ignore parentheses in subsequent checks
7692 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007693
John McCall09431682010-11-18 19:01:18 +00007694 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007695 // Implement C99-only parts of addressof rules.
7696 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007697 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007698 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7699 // (assuming the deref expression is valid).
7700 return uOp->getSubExpr()->getType();
7701 }
7702 // Technically, there should be a check for array subscript
7703 // expressions here, but the result of one is always an lvalue anyway.
7704 }
John McCall5808ce42011-02-03 08:15:49 +00007705 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007706 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007707
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007708 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007709 bool sfinae = S.isSFINAEContext();
7710 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7711 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007712 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007713 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007714 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007715 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007716 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007717 } else if (lval == Expr::LV_MemberFunction) {
7718 // If it's an instance method, make a member pointer.
7719 // The expression must have exactly the form &A::foo.
7720
7721 // If the underlying expression isn't a decl ref, give up.
7722 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007723 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007724 << OrigOp->getSourceRange();
7725 return QualType();
7726 }
7727 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7728 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7729
7730 // The id-expression was parenthesized.
7731 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00007732 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007733 << OrigOp->getSourceRange();
7734
7735 // The method was named without a qualifier.
7736 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007737 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007738 << op->getSourceRange();
7739 }
7740
John McCall09431682010-11-18 19:01:18 +00007741 return S.Context.getMemberPointerType(op->getType(),
7742 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007743 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007744 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007745 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007746 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00007747 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00007748 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00007749 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007750 return QualType();
7751 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007752 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007753 // The operand cannot be a bit-field
John McCall09431682010-11-18 19:01:18 +00007754 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman23d58ce2009-04-20 08:23:18 +00007755 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00007756 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007757 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007758 // The operand cannot be an element of a vector
John McCall09431682010-11-18 19:01:18 +00007759 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00007760 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007761 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007762 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007763 // cannot take address of a property expression.
John McCall09431682010-11-18 19:01:18 +00007764 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007765 << "property expression" << op->getSourceRange();
7766 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007767 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007768 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007769 // with the register storage-class specifier.
7770 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007771 // in C++ it is not error to take address of a register
7772 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007773 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007774 !S.getLangOptions().CPlusPlus) {
7775 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007776 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007777 return QualType();
7778 }
John McCallba135432009-11-21 08:51:07 +00007779 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007780 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007781 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007782 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007783 // Could be a pointer to member, though, if there is an explicit
7784 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007785 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007786 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007787 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007788 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007789 S.Diag(OpLoc,
7790 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007791 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007792 return QualType();
7793 }
Mike Stump1eb44332009-09-09 15:08:12 +00007794
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007795 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7796 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007797 return S.Context.getMemberPointerType(op->getType(),
7798 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007799 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007800 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00007801 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00007802 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007803 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007804
Eli Friedman441cf102009-05-16 23:27:50 +00007805 if (lval == Expr::LV_IncompleteVoidType) {
7806 // Taking the address of a void variable is technically illegal, but we
7807 // allow it in cases which are otherwise valid.
7808 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007809 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007810 }
7811
Reid Spencer5f016e22007-07-11 17:01:13 +00007812 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007813 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007814 return S.Context.getObjCObjectPointerType(op->getType());
7815 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007816}
7817
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007818/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007819static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7820 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007821 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007822 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007823
John McCall09431682010-11-18 19:01:18 +00007824 S.UsualUnaryConversions(Op);
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007825 QualType OpTy = Op->getType();
7826 QualType Result;
7827
7828 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7829 // is an incomplete type or void. It would be possible to warn about
7830 // dereferencing a void pointer, but it's completely well-defined, and such a
7831 // warning is unlikely to catch any mistakes.
7832 if (const PointerType *PT = OpTy->getAs<PointerType>())
7833 Result = PT->getPointeeType();
7834 else if (const ObjCObjectPointerType *OPT =
7835 OpTy->getAs<ObjCObjectPointerType>())
7836 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007837 else {
John McCall09431682010-11-18 19:01:18 +00007838 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007839 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007840 if (PR.take() != Op)
7841 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007842 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007843
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007844 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007845 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007846 << OpTy << Op->getSourceRange();
7847 return QualType();
7848 }
John McCall09431682010-11-18 19:01:18 +00007849
7850 // Dereferences are usually l-values...
7851 VK = VK_LValue;
7852
7853 // ...except that certain expressions are never l-values in C.
7854 if (!S.getLangOptions().CPlusPlus &&
7855 IsCForbiddenLValueType(S.Context, Result))
7856 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007857
7858 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007859}
7860
John McCall2de56d12010-08-25 11:45:40 +00007861static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007862 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007863 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007864 switch (Kind) {
7865 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007866 case tok::periodstar: Opc = BO_PtrMemD; break;
7867 case tok::arrowstar: Opc = BO_PtrMemI; break;
7868 case tok::star: Opc = BO_Mul; break;
7869 case tok::slash: Opc = BO_Div; break;
7870 case tok::percent: Opc = BO_Rem; break;
7871 case tok::plus: Opc = BO_Add; break;
7872 case tok::minus: Opc = BO_Sub; break;
7873 case tok::lessless: Opc = BO_Shl; break;
7874 case tok::greatergreater: Opc = BO_Shr; break;
7875 case tok::lessequal: Opc = BO_LE; break;
7876 case tok::less: Opc = BO_LT; break;
7877 case tok::greaterequal: Opc = BO_GE; break;
7878 case tok::greater: Opc = BO_GT; break;
7879 case tok::exclaimequal: Opc = BO_NE; break;
7880 case tok::equalequal: Opc = BO_EQ; break;
7881 case tok::amp: Opc = BO_And; break;
7882 case tok::caret: Opc = BO_Xor; break;
7883 case tok::pipe: Opc = BO_Or; break;
7884 case tok::ampamp: Opc = BO_LAnd; break;
7885 case tok::pipepipe: Opc = BO_LOr; break;
7886 case tok::equal: Opc = BO_Assign; break;
7887 case tok::starequal: Opc = BO_MulAssign; break;
7888 case tok::slashequal: Opc = BO_DivAssign; break;
7889 case tok::percentequal: Opc = BO_RemAssign; break;
7890 case tok::plusequal: Opc = BO_AddAssign; break;
7891 case tok::minusequal: Opc = BO_SubAssign; break;
7892 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7893 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7894 case tok::ampequal: Opc = BO_AndAssign; break;
7895 case tok::caretequal: Opc = BO_XorAssign; break;
7896 case tok::pipeequal: Opc = BO_OrAssign; break;
7897 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007898 }
7899 return Opc;
7900}
7901
John McCall2de56d12010-08-25 11:45:40 +00007902static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007903 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007904 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007905 switch (Kind) {
7906 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007907 case tok::plusplus: Opc = UO_PreInc; break;
7908 case tok::minusminus: Opc = UO_PreDec; break;
7909 case tok::amp: Opc = UO_AddrOf; break;
7910 case tok::star: Opc = UO_Deref; break;
7911 case tok::plus: Opc = UO_Plus; break;
7912 case tok::minus: Opc = UO_Minus; break;
7913 case tok::tilde: Opc = UO_Not; break;
7914 case tok::exclaim: Opc = UO_LNot; break;
7915 case tok::kw___real: Opc = UO_Real; break;
7916 case tok::kw___imag: Opc = UO_Imag; break;
7917 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007918 }
7919 return Opc;
7920}
7921
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007922/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7923/// This warning is only emitted for builtin assignment operations. It is also
7924/// suppressed in the event of macro expansions.
7925static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7926 SourceLocation OpLoc) {
7927 if (!S.ActiveTemplateInstantiations.empty())
7928 return;
7929 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7930 return;
7931 lhs = lhs->IgnoreParenImpCasts();
7932 rhs = rhs->IgnoreParenImpCasts();
7933 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7934 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7935 if (!LeftDeclRef || !RightDeclRef ||
7936 LeftDeclRef->getLocation().isMacroID() ||
7937 RightDeclRef->getLocation().isMacroID())
7938 return;
7939 const ValueDecl *LeftDecl =
7940 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7941 const ValueDecl *RightDecl =
7942 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7943 if (LeftDecl != RightDecl)
7944 return;
7945 if (LeftDecl->getType().isVolatileQualified())
7946 return;
7947 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7948 if (RefTy->getPointeeType().isVolatileQualified())
7949 return;
7950
7951 S.Diag(OpLoc, diag::warn_self_assignment)
7952 << LeftDeclRef->getType()
7953 << lhs->getSourceRange() << rhs->getSourceRange();
7954}
7955
Douglas Gregoreaebc752008-11-06 23:29:22 +00007956/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7957/// operator @p Opc at location @c TokLoc. This routine only supports
7958/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00007959ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007960 BinaryOperatorKind Opc,
John McCall2de56d12010-08-25 11:45:40 +00007961 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00007962 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00007963 // The following two variables are used for compound assignment operators
7964 QualType CompLHSTy; // Type of LHS after promotions for computation
7965 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00007966 ExprValueKind VK = VK_RValue;
7967 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00007968
7969 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007970 case BO_Assign:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007971 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00007972 if (getLangOptions().CPlusPlus &&
7973 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall09431682010-11-18 19:01:18 +00007974 VK = lhs->getValueKind();
7975 OK = lhs->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007976 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007977 if (!ResultTy.isNull())
7978 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007979 break;
John McCall2de56d12010-08-25 11:45:40 +00007980 case BO_PtrMemD:
7981 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00007982 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007983 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00007984 break;
John McCall2de56d12010-08-25 11:45:40 +00007985 case BO_Mul:
7986 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007987 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00007988 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007989 break;
John McCall2de56d12010-08-25 11:45:40 +00007990 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007991 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7992 break;
John McCall2de56d12010-08-25 11:45:40 +00007993 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007994 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7995 break;
John McCall2de56d12010-08-25 11:45:40 +00007996 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007997 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7998 break;
John McCall2de56d12010-08-25 11:45:40 +00007999 case BO_Shl:
8000 case BO_Shr:
Chandler Carruth21206d52011-02-23 23:34:11 +00008001 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008002 break;
John McCall2de56d12010-08-25 11:45:40 +00008003 case BO_LE:
8004 case BO_LT:
8005 case BO_GE:
8006 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00008007 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008008 break;
John McCall2de56d12010-08-25 11:45:40 +00008009 case BO_EQ:
8010 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00008011 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008012 break;
John McCall2de56d12010-08-25 11:45:40 +00008013 case BO_And:
8014 case BO_Xor:
8015 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008016 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8017 break;
John McCall2de56d12010-08-25 11:45:40 +00008018 case BO_LAnd:
8019 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00008020 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008021 break;
John McCall2de56d12010-08-25 11:45:40 +00008022 case BO_MulAssign:
8023 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00008024 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008025 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008026 CompLHSTy = CompResultTy;
8027 if (!CompResultTy.isNull())
8028 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008029 break;
John McCall2de56d12010-08-25 11:45:40 +00008030 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008031 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8032 CompLHSTy = CompResultTy;
8033 if (!CompResultTy.isNull())
8034 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008035 break;
John McCall2de56d12010-08-25 11:45:40 +00008036 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008037 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8038 if (!CompResultTy.isNull())
8039 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008040 break;
John McCall2de56d12010-08-25 11:45:40 +00008041 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008042 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8043 if (!CompResultTy.isNull())
8044 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008045 break;
John McCall2de56d12010-08-25 11:45:40 +00008046 case BO_ShlAssign:
8047 case BO_ShrAssign:
Chandler Carruth21206d52011-02-23 23:34:11 +00008048 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008049 CompLHSTy = CompResultTy;
8050 if (!CompResultTy.isNull())
8051 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008052 break;
John McCall2de56d12010-08-25 11:45:40 +00008053 case BO_AndAssign:
8054 case BO_XorAssign:
8055 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008056 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8057 CompLHSTy = CompResultTy;
8058 if (!CompResultTy.isNull())
8059 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008060 break;
John McCall2de56d12010-08-25 11:45:40 +00008061 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00008062 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCallf89e55a2010-11-18 06:31:45 +00008063 if (getLangOptions().CPlusPlus) {
8064 VK = rhs->getValueKind();
8065 OK = rhs->getObjectKind();
8066 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008067 break;
8068 }
8069 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008070 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00008071 if (CompResultTy.isNull())
John McCallf89e55a2010-11-18 06:31:45 +00008072 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
8073 VK, OK, OpLoc));
8074
John McCallf6a16482010-12-04 03:47:34 +00008075 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008076 VK = VK_LValue;
8077 OK = lhs->getObjectKind();
8078 }
8079 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
8080 VK, OK, CompLHSTy,
8081 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008082}
8083
Sebastian Redlaee3c932009-10-27 12:10:02 +00008084/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8085/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008086static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8087 const PartialDiagnostic &PD,
Douglas Gregor55b38842010-04-14 16:09:52 +00008088 const PartialDiagnostic &FirstNote,
8089 SourceRange FirstParenRange,
8090 const PartialDiagnostic &SecondNote,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008091 SourceRange SecondParenRange) {
Douglas Gregor55b38842010-04-14 16:09:52 +00008092 Self.Diag(Loc, PD);
8093
8094 if (!FirstNote.getDiagID())
8095 return;
8096
8097 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8098 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8099 // We can't display the parentheses, so just return.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008100 return;
8101 }
8102
Douglas Gregor55b38842010-04-14 16:09:52 +00008103 Self.Diag(Loc, FirstNote)
8104 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregor849b2432010-03-31 17:46:05 +00008105 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008106
Douglas Gregor55b38842010-04-14 16:09:52 +00008107 if (!SecondNote.getDiagID())
Douglas Gregor827feec2010-01-08 00:20:23 +00008108 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008109
Douglas Gregor827feec2010-01-08 00:20:23 +00008110 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8111 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8112 // We can't display the parentheses, so just dig the
8113 // warning/error and return.
Douglas Gregor55b38842010-04-14 16:09:52 +00008114 Self.Diag(Loc, SecondNote);
Douglas Gregor827feec2010-01-08 00:20:23 +00008115 return;
8116 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008117
Douglas Gregor55b38842010-04-14 16:09:52 +00008118 Self.Diag(Loc, SecondNote)
Douglas Gregor849b2432010-03-31 17:46:05 +00008119 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8120 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008121}
8122
Sebastian Redlaee3c932009-10-27 12:10:02 +00008123/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8124/// operators are mixed in a way that suggests that the programmer forgot that
8125/// comparison operators have higher precedence. The most typical example of
8126/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008127static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008128 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00008129 typedef BinaryOperator BinOp;
8130 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8131 rhsopc = static_cast<BinOp::Opcode>(-1);
8132 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008133 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00008134 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008135 rhsopc = BO->getOpcode();
8136
8137 // Subs are not binary operators.
8138 if (lhsopc == -1 && rhsopc == -1)
8139 return;
8140
8141 // Bitwise operations are sometimes used as eager logical ops.
8142 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00008143 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8144 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008145 return;
8146
Sebastian Redlaee3c932009-10-27 12:10:02 +00008147 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008148 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008149 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00008150 << SourceRange(lhs->getLocStart(), OpLoc)
8151 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008152 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00008153 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00008154 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
8155 Self.PDiag(diag::note_precedence_bitwise_silence)
8156 << BinOp::getOpcodeStr(lhsopc),
8157 lhs->getSourceRange());
Sebastian Redlaee3c932009-10-27 12:10:02 +00008158 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008159 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008160 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00008161 << SourceRange(OpLoc, rhs->getLocEnd())
8162 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008163 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00008164 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00008165 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
8166 Self.PDiag(diag::note_precedence_bitwise_silence)
8167 << BinOp::getOpcodeStr(rhsopc),
8168 rhs->getSourceRange());
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008169}
8170
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008171/// \brief It accepts a '&&' expr that is inside a '||' one.
8172/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8173/// in parentheses.
8174static void
8175EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8176 Expr *E) {
8177 assert(isa<BinaryOperator>(E) &&
8178 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
8179 SuggestParentheses(Self, OpLoc,
8180 Self.PDiag(diag::warn_logical_and_in_logical_or)
8181 << E->getSourceRange(),
8182 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8183 E->getSourceRange(),
8184 Self.PDiag(0), SourceRange());
8185}
8186
8187/// \brief Returns true if the given expression can be evaluated as a constant
8188/// 'true'.
8189static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8190 bool Res;
8191 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8192}
8193
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008194/// \brief Returns true if the given expression can be evaluated as a constant
8195/// 'false'.
8196static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8197 bool Res;
8198 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8199}
8200
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008201/// \brief Look for '&&' in the left hand of a '||' expr.
8202static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008203 Expr *OrLHS, Expr *OrRHS) {
8204 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008205 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008206 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8207 if (EvaluatesAsFalse(S, OrRHS))
8208 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008209 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8210 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8211 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8212 } else if (Bop->getOpcode() == BO_LOr) {
8213 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8214 // If it's "a || b && 1 || c" we didn't warn earlier for
8215 // "a || b && 1", but warn now.
8216 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8217 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8218 }
8219 }
8220 }
8221}
8222
8223/// \brief Look for '&&' in the right hand of a '||' expr.
8224static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008225 Expr *OrLHS, Expr *OrRHS) {
8226 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008227 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008228 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8229 if (EvaluatesAsFalse(S, OrLHS))
8230 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008231 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8232 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8233 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008234 }
8235 }
8236}
8237
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008238/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008239/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008240static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008241 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008242 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008243 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008244 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8245
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008246 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8247 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008248 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008249 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8250 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008251 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008252}
8253
Reid Spencer5f016e22007-07-11 17:01:13 +00008254// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008255ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008256 tok::TokenKind Kind,
8257 Expr *lhs, Expr *rhs) {
8258 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00008259 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8260 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008261
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008262 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8263 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8264
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008265 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8266}
8267
John McCall60d7b3a2010-08-24 06:29:42 +00008268ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008269 BinaryOperatorKind Opc,
8270 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00008271 if (getLangOptions().CPlusPlus) {
8272 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008273
John McCall01b2e4e2010-12-06 05:26:58 +00008274 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8275 UseBuiltinOperator = false;
8276 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8277 UseBuiltinOperator = true;
8278 } else {
8279 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8280 !rhs->getType()->isOverloadableType();
8281 }
8282
8283 if (!UseBuiltinOperator) {
8284 // Find all of the overloaded operators visible from this
8285 // point. We perform both an operator-name lookup from the local
8286 // scope and an argument-dependent lookup based on the types of
8287 // the arguments.
8288 UnresolvedSet<16> Functions;
8289 OverloadedOperatorKind OverOp
8290 = BinaryOperator::getOverloadedOperator(Opc);
8291 if (S && OverOp != OO_None)
8292 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8293 Functions);
8294
8295 // Build the (potentially-overloaded, potentially-dependent)
8296 // binary operation.
8297 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8298 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008299 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008300
Douglas Gregoreaebc752008-11-06 23:29:22 +00008301 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008302 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00008303}
8304
John McCall60d7b3a2010-08-24 06:29:42 +00008305ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008306 UnaryOperatorKind Opc,
John McCall2cd11fe2010-10-12 02:09:17 +00008307 Expr *Input) {
John McCallf89e55a2010-11-18 06:31:45 +00008308 ExprValueKind VK = VK_RValue;
8309 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008310 QualType resultType;
8311 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008312 case UO_PreInc:
8313 case UO_PreDec:
8314 case UO_PostInc:
8315 case UO_PostDec:
John McCall09431682010-11-18 19:01:18 +00008316 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008317 Opc == UO_PreInc ||
8318 Opc == UO_PostInc,
8319 Opc == UO_PreInc ||
8320 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008321 break;
John McCall2de56d12010-08-25 11:45:40 +00008322 case UO_AddrOf:
John McCall09431682010-11-18 19:01:18 +00008323 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008324 break;
John McCall2de56d12010-08-25 11:45:40 +00008325 case UO_Deref:
Douglas Gregora873dfc2010-02-03 00:27:59 +00008326 DefaultFunctionArrayLvalueConversion(Input);
John McCall09431682010-11-18 19:01:18 +00008327 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008328 break;
John McCall2de56d12010-08-25 11:45:40 +00008329 case UO_Plus:
8330 case UO_Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00008331 UsualUnaryConversions(Input);
8332 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008333 if (resultType->isDependentType())
8334 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008335 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8336 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008337 break;
8338 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8339 resultType->isEnumeralType())
8340 break;
8341 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008342 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008343 resultType->isPointerType())
8344 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008345 else if (resultType->isPlaceholderType()) {
8346 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8347 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008348 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008349 }
Douglas Gregor74253732008-11-19 15:42:04 +00008350
Sebastian Redl0eb23302009-01-19 00:08:26 +00008351 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8352 << resultType << Input->getSourceRange());
John McCall2de56d12010-08-25 11:45:40 +00008353 case UO_Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00008354 UsualUnaryConversions(Input);
8355 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008356 if (resultType->isDependentType())
8357 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008358 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8359 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8360 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008361 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00008362 << resultType << Input->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008363 else if (resultType->hasIntegerRepresentation())
8364 break;
8365 else if (resultType->isPlaceholderType()) {
8366 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8367 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008368 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008369 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008370 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8371 << resultType << Input->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008372 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008373 break;
John McCall2de56d12010-08-25 11:45:40 +00008374 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008375 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregora873dfc2010-02-03 00:27:59 +00008376 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00008377 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008378 if (resultType->isDependentType())
8379 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008380 if (resultType->isScalarType()) { // C99 6.5.3.3p1
8381 // ok, fallthrough
8382 } else if (resultType->isPlaceholderType()) {
8383 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8384 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008385 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008386 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008387 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8388 << resultType << Input->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008389 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008390
Reid Spencer5f016e22007-07-11 17:01:13 +00008391 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008392 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008393 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008394 break;
John McCall2de56d12010-08-25 11:45:40 +00008395 case UO_Real:
8396 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008397 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008398 // _Real and _Imag map ordinary l-values into ordinary l-values.
8399 if (Input->getValueKind() != VK_RValue &&
8400 Input->getObjectKind() == OK_Ordinary)
8401 VK = Input->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00008402 break;
John McCall2de56d12010-08-25 11:45:40 +00008403 case UO_Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00008404 resultType = Input->getType();
John McCallf89e55a2010-11-18 06:31:45 +00008405 VK = Input->getValueKind();
8406 OK = Input->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008407 break;
8408 }
8409 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008410 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008411
John McCallf89e55a2010-11-18 06:31:45 +00008412 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
8413 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008414}
8415
John McCall60d7b3a2010-08-24 06:29:42 +00008416ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008417 UnaryOperatorKind Opc,
8418 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00008419 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00008420 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008421 // Find all of the overloaded operators visible from this
8422 // point. We perform both an operator-name lookup from the local
8423 // scope and an argument-dependent lookup based on the types of
8424 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008425 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008426 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008427 if (S && OverOp != OO_None)
8428 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8429 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008430
John McCall9ae2f072010-08-23 23:25:46 +00008431 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008432 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008433
John McCall9ae2f072010-08-23 23:25:46 +00008434 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008435}
8436
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008437// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008438ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008439 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008440 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008441}
8442
Steve Naroff1b273c42007-09-16 14:56:35 +00008443/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008444ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008445 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008446 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008447 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008448 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008449 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008450}
8451
John McCall60d7b3a2010-08-24 06:29:42 +00008452ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008453Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008454 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008455 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8456 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8457
Douglas Gregordd8f5692010-03-10 04:54:39 +00008458 bool isFileScope
8459 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008460 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008461 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008462
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008463 // FIXME: there are a variety of strange constraints to enforce here, for
8464 // example, it is not possible to goto into a stmt expression apparently.
8465 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008466
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008467 // If there are sub stmts in the compound stmt, take the type of the last one
8468 // as the type of the stmtexpr.
8469 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008470 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008471 if (!Compound->body_empty()) {
8472 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008473 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008474 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008475 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8476 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008477 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008478 }
8479 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008480 // Do function/array conversion on the last expression, but not
8481 // lvalue-to-rvalue. However, initialize an unqualified type.
8482 DefaultFunctionArrayConversion(LastExpr);
8483 Ty = LastExpr->getType().getUnqualifiedType();
8484
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008485 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8486 ExprResult Res = PerformCopyInitialization(
8487 InitializedEntity::InitializeResult(LPLoc,
8488 Ty,
8489 false),
8490 SourceLocation(),
8491 Owned(LastExpr));
8492 if (Res.isInvalid())
8493 return ExprError();
8494 if ((LastExpr = Res.takeAs<Expr>())) {
8495 if (!LastLabelStmt)
8496 Compound->setLastStmt(LastExpr);
8497 else
8498 LastLabelStmt->setSubStmt(LastExpr);
8499 StmtExprMayBindToTemp = true;
8500 }
8501 }
8502 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008503 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008504
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008505 // FIXME: Check that expression type is complete/non-abstract; statement
8506 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008507 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8508 if (StmtExprMayBindToTemp)
8509 return MaybeBindToTemporary(ResStmtExpr);
8510 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008511}
Steve Naroffd34e9152007-08-01 22:05:33 +00008512
John McCall60d7b3a2010-08-24 06:29:42 +00008513ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008514 TypeSourceInfo *TInfo,
8515 OffsetOfComponent *CompPtr,
8516 unsigned NumComponents,
8517 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008518 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008519 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008520 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008521
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008522 // We must have at least one component that refers to the type, and the first
8523 // one is known to be a field designator. Verify that the ArgTy represents
8524 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008525 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008526 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8527 << ArgTy << TypeRange);
8528
8529 // Type must be complete per C99 7.17p3 because a declaring a variable
8530 // with an incomplete type would be ill-formed.
8531 if (!Dependent
8532 && RequireCompleteType(BuiltinLoc, ArgTy,
8533 PDiag(diag::err_offsetof_incomplete_type)
8534 << TypeRange))
8535 return ExprError();
8536
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008537 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8538 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008539 // FIXME: This diagnostic isn't actually visible because the location is in
8540 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008541 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008542 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8543 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008544
8545 bool DidWarnAboutNonPOD = false;
8546 QualType CurrentType = ArgTy;
8547 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8548 llvm::SmallVector<OffsetOfNode, 4> Comps;
8549 llvm::SmallVector<Expr*, 4> Exprs;
8550 for (unsigned i = 0; i != NumComponents; ++i) {
8551 const OffsetOfComponent &OC = CompPtr[i];
8552 if (OC.isBrackets) {
8553 // Offset of an array sub-field. TODO: Should we allow vector elements?
8554 if (!CurrentType->isDependentType()) {
8555 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8556 if(!AT)
8557 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8558 << CurrentType);
8559 CurrentType = AT->getElementType();
8560 } else
8561 CurrentType = Context.DependentTy;
8562
8563 // The expression must be an integral expression.
8564 // FIXME: An integral constant expression?
8565 Expr *Idx = static_cast<Expr*>(OC.U.E);
8566 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8567 !Idx->getType()->isIntegerType())
8568 return ExprError(Diag(Idx->getLocStart(),
8569 diag::err_typecheck_subscript_not_integer)
8570 << Idx->getSourceRange());
8571
8572 // Record this array index.
8573 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8574 Exprs.push_back(Idx);
8575 continue;
8576 }
8577
8578 // Offset of a field.
8579 if (CurrentType->isDependentType()) {
8580 // We have the offset of a field, but we can't look into the dependent
8581 // type. Just record the identifier of the field.
8582 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8583 CurrentType = Context.DependentTy;
8584 continue;
8585 }
8586
8587 // We need to have a complete type to look into.
8588 if (RequireCompleteType(OC.LocStart, CurrentType,
8589 diag::err_offsetof_incomplete_type))
8590 return ExprError();
8591
8592 // Look for the designated field.
8593 const RecordType *RC = CurrentType->getAs<RecordType>();
8594 if (!RC)
8595 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8596 << CurrentType);
8597 RecordDecl *RD = RC->getDecl();
8598
8599 // C++ [lib.support.types]p5:
8600 // The macro offsetof accepts a restricted set of type arguments in this
8601 // International Standard. type shall be a POD structure or a POD union
8602 // (clause 9).
8603 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8604 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00008605 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008606 PDiag(diag::warn_offsetof_non_pod_type)
8607 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8608 << CurrentType))
8609 DidWarnAboutNonPOD = true;
8610 }
8611
8612 // Look for the field.
8613 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8614 LookupQualifiedName(R, RD);
8615 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008616 IndirectFieldDecl *IndirectMemberDecl = 0;
8617 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008618 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008619 MemberDecl = IndirectMemberDecl->getAnonField();
8620 }
8621
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008622 if (!MemberDecl)
8623 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8624 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8625 OC.LocEnd));
8626
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008627 // C99 7.17p3:
8628 // (If the specified member is a bit-field, the behavior is undefined.)
8629 //
8630 // We diagnose this as an error.
8631 if (MemberDecl->getBitWidth()) {
8632 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8633 << MemberDecl->getDeclName()
8634 << SourceRange(BuiltinLoc, RParenLoc);
8635 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8636 return ExprError();
8637 }
Eli Friedman19410a72010-08-05 10:11:36 +00008638
8639 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008640 if (IndirectMemberDecl)
8641 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008642
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008643 // If the member was found in a base class, introduce OffsetOfNodes for
8644 // the base class indirections.
8645 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8646 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008647 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008648 CXXBasePath &Path = Paths.front();
8649 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8650 B != BEnd; ++B)
8651 Comps.push_back(OffsetOfNode(B->Base));
8652 }
Eli Friedman19410a72010-08-05 10:11:36 +00008653
Francois Pichet87c2e122010-11-21 06:08:52 +00008654 if (IndirectMemberDecl) {
8655 for (IndirectFieldDecl::chain_iterator FI =
8656 IndirectMemberDecl->chain_begin(),
8657 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8658 assert(isa<FieldDecl>(*FI));
8659 Comps.push_back(OffsetOfNode(OC.LocStart,
8660 cast<FieldDecl>(*FI), OC.LocEnd));
8661 }
8662 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008663 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008664
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008665 CurrentType = MemberDecl->getType().getNonReferenceType();
8666 }
8667
8668 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8669 TInfo, Comps.data(), Comps.size(),
8670 Exprs.data(), Exprs.size(), RParenLoc));
8671}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008672
John McCall60d7b3a2010-08-24 06:29:42 +00008673ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008674 SourceLocation BuiltinLoc,
8675 SourceLocation TypeLoc,
8676 ParsedType argty,
8677 OffsetOfComponent *CompPtr,
8678 unsigned NumComponents,
8679 SourceLocation RPLoc) {
8680
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008681 TypeSourceInfo *ArgTInfo;
8682 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8683 if (ArgTy.isNull())
8684 return ExprError();
8685
Eli Friedman5a15dc12010-08-05 10:15:45 +00008686 if (!ArgTInfo)
8687 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8688
8689 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8690 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008691}
8692
8693
John McCall60d7b3a2010-08-24 06:29:42 +00008694ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008695 Expr *CondExpr,
8696 Expr *LHSExpr, Expr *RHSExpr,
8697 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008698 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8699
John McCallf89e55a2010-11-18 06:31:45 +00008700 ExprValueKind VK = VK_RValue;
8701 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008702 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008703 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008704 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008705 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008706 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008707 } else {
8708 // The conditional expression is required to be a constant expression.
8709 llvm::APSInt condEval(32);
8710 SourceLocation ExpLoc;
8711 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008712 return ExprError(Diag(ExpLoc,
8713 diag::err_typecheck_choose_expr_requires_constant)
8714 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008715
Sebastian Redl28507842009-02-26 14:39:58 +00008716 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008717 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8718
8719 resType = ActiveExpr->getType();
8720 ValueDependent = ActiveExpr->isValueDependent();
8721 VK = ActiveExpr->getValueKind();
8722 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008723 }
8724
Sebastian Redlf53597f2009-03-15 17:47:39 +00008725 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008726 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008727 resType->isDependentType(),
8728 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008729}
8730
Steve Naroff4eb206b2008-09-03 18:15:37 +00008731//===----------------------------------------------------------------------===//
8732// Clang Extensions.
8733//===----------------------------------------------------------------------===//
8734
8735/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00008736void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008737 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8738 PushBlockScope(BlockScope, Block);
8739 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008740 if (BlockScope)
8741 PushDeclContext(BlockScope, Block);
8742 else
8743 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00008744}
8745
Mike Stump98eb8a72009-02-04 22:31:32 +00008746void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008747 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008748 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008749 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008750
John McCallbf1a0282010-06-04 23:28:52 +00008751 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008752 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008753
John McCall711c52b2011-01-05 12:14:39 +00008754 // GetTypeForDeclarator always produces a function type for a block
8755 // literal signature. Furthermore, it is always a FunctionProtoType
8756 // unless the function was written with a typedef.
8757 assert(T->isFunctionType() &&
8758 "GetTypeForDeclarator made a non-function block signature");
8759
8760 // Look for an explicit signature in that function type.
8761 FunctionProtoTypeLoc ExplicitSignature;
8762
8763 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8764 if (isa<FunctionProtoTypeLoc>(tmp)) {
8765 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8766
8767 // Check whether that explicit signature was synthesized by
8768 // GetTypeForDeclarator. If so, don't save that as part of the
8769 // written signature.
8770 if (ExplicitSignature.getLParenLoc() ==
8771 ExplicitSignature.getRParenLoc()) {
8772 // This would be much cheaper if we stored TypeLocs instead of
8773 // TypeSourceInfos.
8774 TypeLoc Result = ExplicitSignature.getResultLoc();
8775 unsigned Size = Result.getFullDataSize();
8776 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8777 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8778
8779 ExplicitSignature = FunctionProtoTypeLoc();
8780 }
John McCall82dc0092010-06-04 11:21:44 +00008781 }
Mike Stump1eb44332009-09-09 15:08:12 +00008782
John McCall711c52b2011-01-05 12:14:39 +00008783 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8784 CurBlock->FunctionType = T;
8785
8786 const FunctionType *Fn = T->getAs<FunctionType>();
8787 QualType RetTy = Fn->getResultType();
8788 bool isVariadic =
8789 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8790
John McCallc71a4912010-06-04 19:02:56 +00008791 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008792
John McCall82dc0092010-06-04 11:21:44 +00008793 // Don't allow returning a objc interface by value.
8794 if (RetTy->isObjCObjectType()) {
8795 Diag(ParamInfo.getSourceRange().getBegin(),
8796 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8797 return;
8798 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008799
John McCall82dc0092010-06-04 11:21:44 +00008800 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008801 // return type. TODO: what should we do with declarators like:
8802 // ^ * { ... }
8803 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00008804 if (RetTy != Context.DependentTy)
8805 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008806
John McCall82dc0092010-06-04 11:21:44 +00008807 // Push block parameters from the declarator if we had them.
John McCallc71a4912010-06-04 19:02:56 +00008808 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008809 if (ExplicitSignature) {
8810 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8811 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008812 if (Param->getIdentifier() == 0 &&
8813 !Param->isImplicit() &&
8814 !Param->isInvalidDecl() &&
8815 !getLangOptions().CPlusPlus)
8816 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008817 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008818 }
John McCall82dc0092010-06-04 11:21:44 +00008819
8820 // Fake up parameter variables if we have a typedef, like
8821 // ^ fntype { ... }
8822 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8823 for (FunctionProtoType::arg_type_iterator
8824 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8825 ParmVarDecl *Param =
8826 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8827 ParamInfo.getSourceRange().getBegin(),
8828 *I);
John McCallc71a4912010-06-04 19:02:56 +00008829 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008830 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008831 }
John McCall82dc0092010-06-04 11:21:44 +00008832
John McCallc71a4912010-06-04 19:02:56 +00008833 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008834 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00008835 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00008836 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8837 CurBlock->TheDecl->param_end(),
8838 /*CheckParameterNames=*/false);
8839 }
8840
John McCall82dc0092010-06-04 11:21:44 +00008841 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008842 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008843
John McCallc71a4912010-06-04 19:02:56 +00008844 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008845 Diag(ParamInfo.getAttributes()->getLoc(),
8846 diag::warn_attribute_sentinel_not_variadic) << 1;
8847 // FIXME: remove the attribute.
8848 }
8849
8850 // Put the parameter variables in scope. We can bail out immediately
8851 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008852 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008853 return;
8854
Steve Naroff090276f2008-10-10 01:28:17 +00008855 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008856 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8857 (*AI)->setOwningFunction(CurBlock->TheDecl);
8858
Steve Naroff090276f2008-10-10 01:28:17 +00008859 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008860 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008861 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008862
Steve Naroff090276f2008-10-10 01:28:17 +00008863 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008864 }
John McCall7a9813c2010-01-22 00:28:27 +00008865 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008866}
8867
8868/// ActOnBlockError - If there is an error parsing a block, this callback
8869/// is invoked to pop the information about the block from the action impl.
8870void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00008871 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008872 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008873 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008874}
8875
8876/// ActOnBlockStmtExpr - This is called when the body of a block statement
8877/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008878ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00008879 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008880 // If blocks are disabled, emit an error.
8881 if (!LangOpts.Blocks)
8882 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008883
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008884 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008885
Steve Naroff090276f2008-10-10 01:28:17 +00008886 PopDeclContext();
8887
Steve Naroff4eb206b2008-09-03 18:15:37 +00008888 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008889 if (!BSI->ReturnType.isNull())
8890 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008891
Mike Stump56925862009-07-28 22:04:01 +00008892 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008893 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008894
John McCall469a1eb2011-02-02 13:00:07 +00008895 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00008896 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8897 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00008898
John McCallc71a4912010-06-04 19:02:56 +00008899 // If the user wrote a function type in some form, try to use that.
8900 if (!BSI->FunctionType.isNull()) {
8901 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8902
8903 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8904 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8905
8906 // Turn protoless block types into nullary block types.
8907 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00008908 FunctionProtoType::ExtProtoInfo EPI;
8909 EPI.ExtInfo = Ext;
8910 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008911
8912 // Otherwise, if we don't need to change anything about the function type,
8913 // preserve its sugar structure.
8914 } else if (FTy->getResultType() == RetTy &&
8915 (!NoReturn || FTy->getNoReturnAttr())) {
8916 BlockTy = BSI->FunctionType;
8917
8918 // Otherwise, make the minimal modifications to the function type.
8919 } else {
8920 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00008921 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8922 EPI.TypeQuals = 0; // FIXME: silently?
8923 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00008924 BlockTy = Context.getFunctionType(RetTy,
8925 FPT->arg_type_begin(),
8926 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00008927 EPI);
John McCallc71a4912010-06-04 19:02:56 +00008928 }
8929
8930 // If we don't have a function type, just build one from nothing.
8931 } else {
John McCalle23cf432010-12-14 08:05:40 +00008932 FunctionProtoType::ExtProtoInfo EPI;
8933 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
8934 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008935 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008936
John McCallc71a4912010-06-04 19:02:56 +00008937 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8938 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00008939 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008940
Chris Lattner17a78302009-04-19 05:28:12 +00008941 // If needed, diagnose invalid gotos and switches in the block.
John McCall781472f2010-08-25 08:40:02 +00008942 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00008943 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00008944
Chris Lattnere476bdc2011-02-17 23:58:47 +00008945 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008946
John McCall469a1eb2011-02-02 13:00:07 +00008947 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCalle0054f62010-08-25 05:56:39 +00008948
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00008949 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8950 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008951 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00008952}
8953
John McCall60d7b3a2010-08-24 06:29:42 +00008954ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00008955 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008956 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008957 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008958 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00008959 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008960}
8961
John McCall60d7b3a2010-08-24 06:29:42 +00008962ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00008963 Expr *E, TypeSourceInfo *TInfo,
8964 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008965 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00008966
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008967 // Get the va_list type
8968 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008969 if (VaListType->isArrayType()) {
8970 // Deal with implicit array decay; for example, on x86-64,
8971 // va_list is an array, but it's supposed to decay to
8972 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008973 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00008974 // Make sure the input expression also decays appropriately.
8975 UsualUnaryConversions(E);
8976 } else {
8977 // Otherwise, the va_list argument must be an l-value because
8978 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00008979 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00008980 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00008981 return ExprError();
8982 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008983
Douglas Gregordd027302009-05-19 23:10:31 +00008984 if (!E->isTypeDependent() &&
8985 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00008986 return ExprError(Diag(E->getLocStart(),
8987 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008988 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00008989 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008990
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008991 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008992 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008993
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008994 QualType T = TInfo->getType().getNonLValueExprType(Context);
8995 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008996}
8997
John McCall60d7b3a2010-08-24 06:29:42 +00008998ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008999 // The type of __null will be int or long, depending on the size of
9000 // pointers on the target.
9001 QualType Ty;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009002 unsigned pw = Context.Target.getPointerWidth(0);
9003 if (pw == Context.Target.getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009004 Ty = Context.IntTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009005 else if (pw == Context.Target.getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009006 Ty = Context.LongTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009007 else if (pw == Context.Target.getLongLongWidth())
9008 Ty = Context.LongLongTy;
9009 else {
9010 assert(!"I don't know size of pointer!");
9011 Ty = Context.IntTy;
9012 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009013
Sebastian Redlf53597f2009-03-15 17:47:39 +00009014 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009015}
9016
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009017static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009018 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009019 if (!SemaRef.getLangOptions().ObjC1)
9020 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009021
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009022 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9023 if (!PT)
9024 return;
9025
9026 // Check if the destination is of type 'id'.
9027 if (!PT->isObjCIdType()) {
9028 // Check if the destination is the 'NSString' interface.
9029 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9030 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9031 return;
9032 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009033
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009034 // Strip off any parens and casts.
9035 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9036 if (!SL || SL->isWide())
9037 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009038
Douglas Gregor849b2432010-03-31 17:46:05 +00009039 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009040}
9041
Chris Lattner5cf216b2008-01-04 18:04:52 +00009042bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9043 SourceLocation Loc,
9044 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009045 Expr *SrcExpr, AssignmentAction Action,
9046 bool *Complained) {
9047 if (Complained)
9048 *Complained = false;
9049
Chris Lattner5cf216b2008-01-04 18:04:52 +00009050 // Decode the result (notice that AST's are still created for extensions).
9051 bool isInvalid = false;
9052 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00009053 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009054
Chris Lattner5cf216b2008-01-04 18:04:52 +00009055 switch (ConvTy) {
9056 default: assert(0 && "Unknown conversion type");
9057 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009058 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009059 DiagKind = diag::ext_typecheck_convert_pointer_int;
9060 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009061 case IntToPointer:
9062 DiagKind = diag::ext_typecheck_convert_int_pointer;
9063 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009064 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009065 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009066 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9067 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009068 case IncompatiblePointerSign:
9069 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9070 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009071 case FunctionVoidPointer:
9072 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9073 break;
John McCall86c05f32011-02-01 00:10:29 +00009074 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009075 // Perform array-to-pointer decay if necessary.
9076 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9077
John McCall86c05f32011-02-01 00:10:29 +00009078 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9079 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9080 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9081 DiagKind = diag::err_typecheck_incompatible_address_space;
9082 break;
9083 }
9084
9085 llvm_unreachable("unknown error case for discarding qualifiers!");
9086 // fallthrough
9087 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009088 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009089 // If the qualifiers lost were because we were applying the
9090 // (deprecated) C++ conversion from a string literal to a char*
9091 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9092 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009093 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009094 // bit of refactoring (so that the second argument is an
9095 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009096 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009097 // C++ semantics.
9098 if (getLangOptions().CPlusPlus &&
9099 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9100 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009101 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9102 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009103 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009104 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009105 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009106 case IntToBlockPointer:
9107 DiagKind = diag::err_int_to_block_pointer;
9108 break;
9109 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009110 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009111 break;
Steve Naroff39579072008-10-14 22:18:38 +00009112 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009113 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009114 // it can give a more specific diagnostic.
9115 DiagKind = diag::warn_incompatible_qualified_id;
9116 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009117 case IncompatibleVectors:
9118 DiagKind = diag::warn_incompatible_vectors;
9119 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009120 case Incompatible:
9121 DiagKind = diag::err_typecheck_convert_incompatible;
9122 isInvalid = true;
9123 break;
9124 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009125
Douglas Gregord4eea832010-04-09 00:35:39 +00009126 QualType FirstType, SecondType;
9127 switch (Action) {
9128 case AA_Assigning:
9129 case AA_Initializing:
9130 // The destination type comes first.
9131 FirstType = DstType;
9132 SecondType = SrcType;
9133 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009134
Douglas Gregord4eea832010-04-09 00:35:39 +00009135 case AA_Returning:
9136 case AA_Passing:
9137 case AA_Converting:
9138 case AA_Sending:
9139 case AA_Casting:
9140 // The source type comes first.
9141 FirstType = SrcType;
9142 SecondType = DstType;
9143 break;
9144 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009145
Douglas Gregord4eea832010-04-09 00:35:39 +00009146 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009147 << SrcExpr->getSourceRange() << Hint;
Douglas Gregora41a8c52010-04-22 00:20:18 +00009148 if (Complained)
9149 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009150 return isInvalid;
9151}
Anders Carlssone21555e2008-11-30 19:50:32 +00009152
Chris Lattner3bf68932009-04-25 21:59:05 +00009153bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009154 llvm::APSInt ICEResult;
9155 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9156 if (Result)
9157 *Result = ICEResult;
9158 return false;
9159 }
9160
Anders Carlssone21555e2008-11-30 19:50:32 +00009161 Expr::EvalResult EvalResult;
9162
Mike Stumpeed9cac2009-02-19 03:04:26 +00009163 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009164 EvalResult.HasSideEffects) {
9165 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9166
9167 if (EvalResult.Diag) {
9168 // We only show the note if it's not the usual "invalid subexpression"
9169 // or if it's actually in a subexpression.
9170 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9171 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9172 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9173 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009174
Anders Carlssone21555e2008-11-30 19:50:32 +00009175 return true;
9176 }
9177
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009178 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9179 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009180
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009181 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009182 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9183 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009184 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009185
Anders Carlssone21555e2008-11-30 19:50:32 +00009186 if (Result)
9187 *Result = EvalResult.Val.getInt();
9188 return false;
9189}
Douglas Gregore0762c92009-06-19 23:52:42 +00009190
Douglas Gregor2afce722009-11-26 00:44:06 +00009191void
Mike Stump1eb44332009-09-09 15:08:12 +00009192Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009193 ExprEvalContexts.push_back(
9194 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00009195}
9196
Mike Stump1eb44332009-09-09 15:08:12 +00009197void
Douglas Gregor2afce722009-11-26 00:44:06 +00009198Sema::PopExpressionEvaluationContext() {
9199 // Pop the current expression evaluation context off the stack.
9200 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9201 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009202
Douglas Gregor06d33692009-12-12 07:57:52 +00009203 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9204 if (Rec.PotentiallyReferenced) {
9205 // Mark any remaining declarations in the current position of the stack
9206 // as "referenced". If they were not meant to be referenced, semantic
9207 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009208 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009209 I = Rec.PotentiallyReferenced->begin(),
9210 IEnd = Rec.PotentiallyReferenced->end();
9211 I != IEnd; ++I)
9212 MarkDeclarationReferenced(I->first, I->second);
9213 }
9214
9215 if (Rec.PotentiallyDiagnosed) {
9216 // Emit any pending diagnostics.
9217 for (PotentiallyEmittedDiagnostics::iterator
9218 I = Rec.PotentiallyDiagnosed->begin(),
9219 IEnd = Rec.PotentiallyDiagnosed->end();
9220 I != IEnd; ++I)
9221 Diag(I->first, I->second);
9222 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009223 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009224
9225 // When are coming out of an unevaluated context, clear out any
9226 // temporaries that we may have created as part of the evaluation of
9227 // the expression in that context: they aren't relevant because they
9228 // will never be constructed.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009229 if (Rec.Context == Unevaluated &&
Douglas Gregor2afce722009-11-26 00:44:06 +00009230 ExprTemporaries.size() > Rec.NumTemporaries)
9231 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9232 ExprTemporaries.end());
9233
9234 // Destroy the popped expression evaluation record.
9235 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009236}
Douglas Gregore0762c92009-06-19 23:52:42 +00009237
9238/// \brief Note that the given declaration was referenced in the source code.
9239///
9240/// This routine should be invoke whenever a given declaration is referenced
9241/// in the source code, and where that reference occurred. If this declaration
9242/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9243/// C99 6.9p3), then the declaration will be marked as used.
9244///
9245/// \param Loc the location where the declaration was referenced.
9246///
9247/// \param D the declaration that has been referenced by the source code.
9248void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9249 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009250
Douglas Gregorc070cc62010-06-17 23:14:26 +00009251 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009252 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009253
Douglas Gregorb5352cf2009-10-08 21:35:42 +00009254 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9255 // template or not. The reason for this is that unevaluated expressions
9256 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9257 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009258 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009259 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009260 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009261 return;
9262 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009263
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009264 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9265 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009266
Douglas Gregore0762c92009-06-19 23:52:42 +00009267 // Do not mark anything as "used" within a dependent context; wait for
9268 // an instantiation.
9269 if (CurContext->isDependentContext())
9270 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009271
Douglas Gregor2afce722009-11-26 00:44:06 +00009272 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009273 case Unevaluated:
9274 // We are in an expression that is not potentially evaluated; do nothing.
9275 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009276
Douglas Gregorac7610d2009-06-22 20:57:11 +00009277 case PotentiallyEvaluated:
9278 // We are in a potentially-evaluated expression, so this declaration is
9279 // "used"; handle this below.
9280 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009281
Douglas Gregorac7610d2009-06-22 20:57:11 +00009282 case PotentiallyPotentiallyEvaluated:
9283 // We are in an expression that may be potentially evaluated; queue this
9284 // declaration reference until we know whether the expression is
9285 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009286 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009287 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009288
9289 case PotentiallyEvaluatedIfUsed:
9290 // Referenced declarations will only be used if the construct in the
9291 // containing expression is used.
9292 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009293 }
Mike Stump1eb44332009-09-09 15:08:12 +00009294
Douglas Gregore0762c92009-06-19 23:52:42 +00009295 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009296 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009297 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00009298 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00009299 if (Constructor->getParent()->hasTrivialConstructor())
9300 return;
9301 if (!Constructor->isUsed(false))
9302 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00009303 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00009304 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009305 if (!Constructor->isUsed(false))
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009306 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9307 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009308
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009309 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009310 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009311 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009312 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009313 if (Destructor->isVirtual())
9314 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009315 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9316 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9317 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009318 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +00009319 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009320 } else if (MethodDecl->isVirtual())
9321 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009322 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009323 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009324 // Recursive functions should be marked when used from another function.
9325 if (CurContext == Function) return;
9326
Mike Stump1eb44332009-09-09 15:08:12 +00009327 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009328 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009329 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009330 bool AlreadyInstantiated = false;
9331 if (FunctionTemplateSpecializationInfo *SpecInfo
9332 = Function->getTemplateSpecializationInfo()) {
9333 if (SpecInfo->getPointOfInstantiation().isInvalid())
9334 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009335 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009336 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009337 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009338 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009339 = Function->getMemberSpecializationInfo()) {
9340 if (MSInfo->getPointOfInstantiation().isInvalid())
9341 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009342 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009343 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009344 AlreadyInstantiated = true;
9345 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009346
Douglas Gregor60406be2010-01-16 22:29:39 +00009347 if (!AlreadyInstantiated) {
9348 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9349 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9350 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9351 Loc));
9352 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009353 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009354 }
John McCall15e310a2011-02-19 02:53:41 +00009355 } else {
9356 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00009357 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9358 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009359 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009360 MarkDeclarationReferenced(Loc, *i);
9361 }
John McCall15e310a2011-02-19 02:53:41 +00009362 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009363
John McCall15e310a2011-02-19 02:53:41 +00009364 // Keep track of used but undefined functions.
9365 if (!Function->isPure() && !Function->hasBody() &&
9366 Function->getLinkage() != ExternalLinkage) {
9367 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9368 if (old.isInvalid()) old = Loc;
9369 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009370
John McCall15e310a2011-02-19 02:53:41 +00009371 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00009372 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009373 }
Mike Stump1eb44332009-09-09 15:08:12 +00009374
Douglas Gregore0762c92009-06-19 23:52:42 +00009375 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009376 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009377 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009378 Var->getInstantiatedFromStaticDataMember()) {
9379 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9380 assert(MSInfo && "Missing member specialization information?");
9381 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9382 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9383 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009384 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009385 }
9386 }
Mike Stump1eb44332009-09-09 15:08:12 +00009387
John McCall77efc682011-02-21 19:25:48 +00009388 // Keep track of used but undefined variables. We make a hole in
9389 // the warning for static const data members with in-line
9390 // initializers.
John McCall15e310a2011-02-19 02:53:41 +00009391 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +00009392 && Var->getLinkage() != ExternalLinkage
9393 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +00009394 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9395 if (old.isInvalid()) old = Loc;
9396 }
Douglas Gregor7caa6822009-07-24 20:34:43 +00009397
Douglas Gregore0762c92009-06-19 23:52:42 +00009398 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00009399 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00009400 }
Douglas Gregore0762c92009-06-19 23:52:42 +00009401}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009402
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009403namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009404 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009405 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009406 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009407 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9408 Sema &S;
9409 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009410
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009411 public:
9412 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009413
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009414 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009415
9416 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9417 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009418 };
9419}
9420
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009421bool MarkReferencedDecls::TraverseTemplateArgument(
9422 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009423 if (Arg.getKind() == TemplateArgument::Declaration) {
9424 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9425 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009426
9427 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009428}
9429
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009430bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009431 if (ClassTemplateSpecializationDecl *Spec
9432 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9433 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00009434 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009435 }
9436
Chandler Carruthe3e210c2010-06-10 10:31:57 +00009437 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009438}
9439
9440void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9441 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009442 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009443}
9444
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009445namespace {
9446 /// \brief Helper class that marks all of the declarations referenced by
9447 /// potentially-evaluated subexpressions as "referenced".
9448 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9449 Sema &S;
9450
9451 public:
9452 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9453
9454 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9455
9456 void VisitDeclRefExpr(DeclRefExpr *E) {
9457 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9458 }
9459
9460 void VisitMemberExpr(MemberExpr *E) {
9461 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009462 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009463 }
9464
9465 void VisitCXXNewExpr(CXXNewExpr *E) {
9466 if (E->getConstructor())
9467 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9468 if (E->getOperatorNew())
9469 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9470 if (E->getOperatorDelete())
9471 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009472 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009473 }
9474
9475 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9476 if (E->getOperatorDelete())
9477 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009478 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9479 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9480 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9481 S.MarkDeclarationReferenced(E->getLocStart(),
9482 S.LookupDestructor(Record));
9483 }
9484
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009485 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009486 }
9487
9488 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9489 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009490 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009491 }
9492
9493 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9494 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9495 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009496
9497 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9498 Visit(E->getExpr());
9499 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009500 };
9501}
9502
9503/// \brief Mark any declarations that appear within this expression or any
9504/// potentially-evaluated subexpressions as "referenced".
9505void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9506 EvaluatedExprMarker(*this).Visit(E);
9507}
9508
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009509/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9510/// of the program being compiled.
9511///
9512/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009513/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009514/// possibility that the code will actually be executable. Code in sizeof()
9515/// expressions, code used only during overload resolution, etc., are not
9516/// potentially evaluated. This routine will suppress such diagnostics or,
9517/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009518/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009519/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009520///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009521/// This routine should be used for all diagnostics that describe the run-time
9522/// behavior of a program, such as passing a non-POD value through an ellipsis.
9523/// Failure to do so will likely result in spurious diagnostics or failures
9524/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek762696f2011-02-23 01:51:43 +00009525bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009526 const PartialDiagnostic &PD) {
9527 switch (ExprEvalContexts.back().Context ) {
9528 case Unevaluated:
9529 // The argument will never be evaluated, so don't complain.
9530 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009531
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009532 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009533 case PotentiallyEvaluatedIfUsed:
Ted Kremenek351ba912011-02-23 01:52:04 +00009534 if (stmt && getCurFunctionOrMethodDecl()) {
9535 FunctionScopes.back()->PossiblyUnreachableDiags.
9536 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9537 }
9538 else
9539 Diag(Loc, PD);
9540
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009541 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009542
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009543 case PotentiallyPotentiallyEvaluated:
9544 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9545 break;
9546 }
9547
9548 return false;
9549}
9550
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009551bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9552 CallExpr *CE, FunctionDecl *FD) {
9553 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9554 return false;
9555
9556 PartialDiagnostic Note =
9557 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9558 << FD->getDeclName() : PDiag();
9559 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009560
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009561 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009562 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009563 PDiag(diag::err_call_function_incomplete_return)
9564 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009565 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009566 << CE->getSourceRange(),
9567 std::make_pair(NoteLoc, Note)))
9568 return true;
9569
9570 return false;
9571}
9572
Douglas Gregor92c3a042011-01-19 16:50:08 +00009573// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +00009574// will prevent this condition from triggering, which is what we want.
9575void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9576 SourceLocation Loc;
9577
John McCalla52ef082009-11-11 02:41:58 +00009578 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +00009579 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +00009580
John McCall5a881bb2009-10-12 21:59:07 +00009581 if (isa<BinaryOperator>(E)) {
9582 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +00009583 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +00009584 return;
9585
Douglas Gregor92c3a042011-01-19 16:50:08 +00009586 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9587
John McCallc8d8ac52009-11-12 00:06:05 +00009588 // Greylist some idioms by putting them into a warning subcategory.
9589 if (ObjCMessageExpr *ME
9590 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9591 Selector Sel = ME->getSelector();
9592
John McCallc8d8ac52009-11-12 00:06:05 +00009593 // self = [<foo> init...]
Douglas Gregor813d8342011-02-18 22:29:55 +00009594 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +00009595 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9596
9597 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +00009598 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +00009599 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9600 }
John McCalla52ef082009-11-11 02:41:58 +00009601
John McCall5a881bb2009-10-12 21:59:07 +00009602 Loc = Op->getOperatorLoc();
9603 } else if (isa<CXXOperatorCallExpr>(E)) {
9604 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +00009605 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +00009606 return;
9607
Douglas Gregor92c3a042011-01-19 16:50:08 +00009608 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +00009609 Loc = Op->getOperatorLoc();
9610 } else {
9611 // Not an assignment.
9612 return;
9613 }
9614
John McCall5a881bb2009-10-12 21:59:07 +00009615 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00009616 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009617
Douglas Gregor55b38842010-04-14 16:09:52 +00009618 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +00009619
9620 if (IsOrAssign)
9621 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9622 << FixItHint::CreateReplacement(Loc, "!=");
9623 else
9624 Diag(Loc, diag::note_condition_assign_to_comparison)
9625 << FixItHint::CreateReplacement(Loc, "==");
9626
Douglas Gregor55b38842010-04-14 16:09:52 +00009627 Diag(Loc, diag::note_condition_assign_silence)
9628 << FixItHint::CreateInsertion(Open, "(")
9629 << FixItHint::CreateInsertion(Close, ")");
John McCall5a881bb2009-10-12 21:59:07 +00009630}
9631
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009632/// \brief Redundant parentheses over an equality comparison can indicate
9633/// that the user intended an assignment used as condition.
9634void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009635 // Don't warn if the parens came from a macro.
9636 SourceLocation parenLoc = parenE->getLocStart();
9637 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9638 return;
9639
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009640 Expr *E = parenE->IgnoreParens();
9641
9642 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +00009643 if (opE->getOpcode() == BO_EQ &&
9644 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9645 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009646 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +00009647
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009648 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9649 Diag(Loc, diag::note_equality_comparison_to_assign)
9650 << FixItHint::CreateReplacement(Loc, "=");
9651 Diag(Loc, diag::note_equality_comparison_silence)
9652 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9653 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009654 }
9655}
9656
John McCall5a881bb2009-10-12 21:59:07 +00009657bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9658 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009659 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9660 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +00009661
9662 if (!E->isTypeDependent()) {
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009663 if (E->isBoundMemberFunction(Context))
9664 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9665 << E->getSourceRange();
9666
John McCallf6a16482010-12-04 03:47:34 +00009667 if (getLangOptions().CPlusPlus)
9668 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9669
9670 DefaultFunctionArrayLvalueConversion(E);
John McCallabc56c72010-12-04 06:09:13 +00009671
9672 QualType T = E->getType();
John McCallf6a16482010-12-04 03:47:34 +00009673 if (!T->isScalarType()) // C99 6.8.4.1p1
9674 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9675 << T << E->getSourceRange();
John McCall5a881bb2009-10-12 21:59:07 +00009676 }
9677
9678 return false;
9679}
Douglas Gregor586596f2010-05-06 17:25:47 +00009680
John McCall60d7b3a2010-08-24 06:29:42 +00009681ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9682 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +00009683 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +00009684 return ExprError();
9685
Douglas Gregorff331c12010-07-25 18:17:45 +00009686 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregor586596f2010-05-06 17:25:47 +00009687 return ExprError();
Douglas Gregor586596f2010-05-06 17:25:47 +00009688
9689 return Owned(Sub);
9690}
John McCall2a984ca2010-10-12 00:20:44 +00009691
9692/// Check for operands with placeholder types and complain if found.
9693/// Returns true if there was an error and no recovery was possible.
9694ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9695 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9696 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9697
9698 // If this is overload, check for a single overload.
Richard Smith34b41d92011-02-20 03:19:35 +00009699 assert(BT->getKind() == BuiltinType::Overload);
John McCall2a984ca2010-10-12 00:20:44 +00009700
Richard Smith34b41d92011-02-20 03:19:35 +00009701 if (FunctionDecl *Specialization
9702 = ResolveSingleFunctionTemplateSpecialization(E)) {
9703 // The access doesn't really matter in this case.
9704 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9705 Specialization->getAccess());
9706 E = FixOverloadedFunctionReference(E, Found, Specialization);
9707 if (!E) return ExprError();
9708 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +00009709 }
9710
Richard Smith34b41d92011-02-20 03:19:35 +00009711 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
John McCall2a984ca2010-10-12 00:20:44 +00009712 return ExprError();
9713}