blob: 65b57c30cd7da6b688df2c68239df85077e2683b [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.
79 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
80 if (VD->isParsingAutoInit()) {
81 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
82 << D->getDeclName();
83 return true;
84 }
85 }
86
Chris Lattner76a642f2009-02-15 22:43:40 +000087 // See if the decl is deprecated.
Benjamin Kramerce2d1862010-10-09 15:49:00 +000088 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>())
Peter Collingbourne743b82b2011-01-02 19:53:12 +000089 EmitDeprecationWarning(D, DA->getMessage(), Loc, UnknownObjCClass);
Chris Lattner76a642f2009-02-15 22:43:40 +000090
Chris Lattnerffb93682009-10-25 17:21:40 +000091 // See if the decl is unavailable
Fariborz Jahanianc784dc12010-10-06 23:12:32 +000092 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) {
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000093 if (UA->getMessage().empty()) {
Peter Collingbourne743b82b2011-01-02 19:53:12 +000094 if (!UnknownObjCClass)
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000095 Diag(Loc, diag::err_unavailable) << D->getDeclName();
96 else
97 Diag(Loc, diag::warn_unavailable_fwdclass_message)
98 << D->getDeclName();
99 }
100 else
Fariborz Jahanianc784dc12010-10-06 23:12:32 +0000101 Diag(Loc, diag::err_unavailable_message)
Benjamin Kramerce2d1862010-10-09 15:49:00 +0000102 << D->getDeclName() << UA->getMessage();
Chris Lattnerffb93682009-10-25 17:21:40 +0000103 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
104 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000105
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000106 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000107 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000108 if (FD->isDeleted()) {
109 Diag(Loc, diag::err_deleted_function_use);
110 Diag(D->getLocation(), diag::note_unavailable_here) << true;
111 return true;
112 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000113 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000114
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000115 // Warn if this is used but marked unused.
116 if (D->hasAttr<UnusedAttr>())
117 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
118
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000119 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000120}
121
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000122/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +0000123/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000124/// attribute. It warns if call does not have the sentinel argument.
125///
126void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000127 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000128 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000129 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000130 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000131
132 // FIXME: In C++0x, if any of the arguments are parameter pack
133 // expansions, we can't check for the sentinel now.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000134 int sentinelPos = attr->getSentinel();
135 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +0000136
Mike Stump390b4cc2009-05-16 07:39:55 +0000137 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
138 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000139 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000140 bool warnNotEnoughArgs = false;
141 int isMethod = 0;
142 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
143 // skip over named parameters.
144 ObjCMethodDecl::param_iterator P, E = MD->param_end();
145 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
146 if (nullPos)
147 --nullPos;
148 else
149 ++i;
150 }
151 warnNotEnoughArgs = (P != E || i >= NumArgs);
152 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000153 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000154 // skip over named parameters.
155 ObjCMethodDecl::param_iterator P, E = FD->param_end();
156 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
157 if (nullPos)
158 --nullPos;
159 else
160 ++i;
161 }
162 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000163 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000164 // block or function pointer call.
165 QualType Ty = V->getType();
166 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000167 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000168 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
169 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000170 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
171 unsigned NumArgsInProto = Proto->getNumArgs();
172 unsigned k;
173 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
174 if (nullPos)
175 --nullPos;
176 else
177 ++i;
178 }
179 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
180 }
181 if (Ty->isBlockPointerType())
182 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000183 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000184 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000185 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000186 return;
187
188 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000189 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000190 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000191 return;
192 }
193 int sentinel = i;
194 while (sentinelPos > 0 && i < NumArgs-1) {
195 --sentinelPos;
196 ++i;
197 }
198 if (sentinelPos > 0) {
199 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000200 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000201 return;
202 }
203 while (i < NumArgs-1) {
204 ++i;
205 ++sentinel;
206 }
207 Expr *sentinelExpr = Args[sentinel];
John McCall8eb662e2010-05-06 23:53:00 +0000208 if (!sentinelExpr) return;
209 if (sentinelExpr->isTypeDependent()) return;
210 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000211
212 // nullptr_t is always treated as null.
213 if (sentinelExpr->getType()->isNullPtrType()) return;
214
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000215 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000216 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
217 Expr::NPC_ValueDependentIsNull))
218 return;
219
220 // Unfortunately, __null has type 'int'.
221 if (isa<GNUNullExpr>(sentinelExpr)) return;
222
223 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
224 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000225}
226
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000227SourceRange Sema::getExprRange(ExprTy *E) const {
228 Expr *Ex = (Expr *)E;
229 return Ex? Ex->getSourceRange() : SourceRange();
230}
231
Chris Lattnere7a2e912008-07-25 21:10:04 +0000232//===----------------------------------------------------------------------===//
233// Standard Promotions and Conversions
234//===----------------------------------------------------------------------===//
235
Chris Lattnere7a2e912008-07-25 21:10:04 +0000236/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
237void Sema::DefaultFunctionArrayConversion(Expr *&E) {
238 QualType Ty = E->getType();
239 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
240
Chris Lattnere7a2e912008-07-25 21:10:04 +0000241 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000242 ImpCastExprToType(E, Context.getPointerType(Ty),
John McCall2de56d12010-08-25 11:45:40 +0000243 CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000244 else if (Ty->isArrayType()) {
245 // In C90 mode, arrays only promote to pointers if the array expression is
246 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
247 // type 'array of type' is converted to an expression that has type 'pointer
248 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
249 // that has type 'array of type' ...". The relevant change is "an lvalue"
250 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000251 //
252 // C++ 4.2p1:
253 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
254 // T" can be converted to an rvalue of type "pointer to T".
255 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000256 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
Anders Carlsson112a0a82009-08-07 23:48:20 +0000257 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
John McCall2de56d12010-08-25 11:45:40 +0000258 CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000259 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000260}
261
John McCall409fa9a2010-12-06 20:48:59 +0000262void Sema::DefaultLvalueConversion(Expr *&E) {
John McCall0ae287a2010-12-01 04:43:34 +0000263 // C++ [conv.lval]p1:
264 // A glvalue of a non-function, non-array type T can be
265 // converted to a prvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000266 if (!E->isGLValue()) return;
John McCallf6a16482010-12-04 03:47:34 +0000267
John McCall409fa9a2010-12-06 20:48:59 +0000268 QualType T = E->getType();
269 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000270
John McCall409fa9a2010-12-06 20:48:59 +0000271 // Create a load out of an ObjCProperty l-value, if necessary.
272 if (E->getObjectKind() == OK_ObjCProperty) {
273 ConvertPropertyForRValue(E);
274 if (!E->isGLValue())
John McCallf6a16482010-12-04 03:47:34 +0000275 return;
Douglas Gregora873dfc2010-02-03 00:27:59 +0000276 }
John McCall409fa9a2010-12-06 20:48:59 +0000277
278 // We don't want to throw lvalue-to-rvalue casts on top of
279 // expressions of certain types in C++.
280 if (getLangOptions().CPlusPlus &&
281 (E->getType() == Context.OverloadTy ||
282 T->isDependentType() ||
283 T->isRecordType()))
284 return;
285
286 // The C standard is actually really unclear on this point, and
287 // DR106 tells us what the result should be but not why. It's
288 // generally best to say that void types just doesn't undergo
289 // lvalue-to-rvalue at all. Note that expressions of unqualified
290 // 'void' type are never l-values, but qualified void can be.
291 if (T->isVoidType())
292 return;
293
294 // C++ [conv.lval]p1:
295 // [...] If T is a non-class type, the type of the prvalue is the
296 // cv-unqualified version of T. Otherwise, the type of the
297 // rvalue is T.
298 //
299 // C99 6.3.2.1p2:
300 // If the lvalue has qualified type, the value has the unqualified
301 // version of the type of the lvalue; otherwise, the value has the
302 // type of the lvalue.
303 if (T.hasQualifiers())
304 T = T.getUnqualifiedType();
305
Ted Kremeneka0125d82011-02-16 01:57:07 +0000306 if (const ArraySubscriptExpr *ae = dyn_cast<ArraySubscriptExpr>(E))
307 CheckArrayAccess(ae);
308
John McCall409fa9a2010-12-06 20:48:59 +0000309 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
310 E, 0, VK_RValue);
311}
312
313void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
314 DefaultFunctionArrayConversion(E);
315 DefaultLvalueConversion(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000316}
317
318
Chris Lattnere7a2e912008-07-25 21:10:04 +0000319/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000320/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000321/// sometimes surpressed. For example, the array->pointer conversion doesn't
322/// apply if the array is an argument to the sizeof or address (&) operators.
323/// In these instances, this routine should *not* be called.
John McCall0ae287a2010-12-01 04:43:34 +0000324Expr *Sema::UsualUnaryConversions(Expr *&E) {
325 // First, convert to an r-value.
326 DefaultFunctionArrayLvalueConversion(E);
327
328 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000329 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000330
331 // Try to perform integral promotions if the object has a theoretically
332 // promotable type.
333 if (Ty->isIntegralOrUnscopedEnumerationType()) {
334 // C99 6.3.1.1p2:
335 //
336 // The following may be used in an expression wherever an int or
337 // unsigned int may be used:
338 // - an object or expression with an integer type whose integer
339 // conversion rank is less than or equal to the rank of int
340 // and unsigned int.
341 // - A bit-field of type _Bool, int, signed int, or unsigned int.
342 //
343 // If an int can represent all values of the original type, the
344 // value is converted to an int; otherwise, it is converted to an
345 // unsigned int. These are called the integer promotions. All
346 // other types are unchanged by the integer promotions.
347
348 QualType PTy = Context.isPromotableBitField(E);
349 if (!PTy.isNull()) {
350 ImpCastExprToType(E, PTy, CK_IntegralCast);
351 return E;
352 }
353 if (Ty->isPromotableIntegerType()) {
354 QualType PT = Context.getPromotedIntegerType(Ty);
355 ImpCastExprToType(E, PT, CK_IntegralCast);
356 return E;
357 }
Eli Friedman04e83572009-08-20 04:21:42 +0000358 }
359
John McCall0ae287a2010-12-01 04:43:34 +0000360 return E;
Chris Lattnere7a2e912008-07-25 21:10:04 +0000361}
362
Chris Lattner05faf172008-07-25 22:25:12 +0000363/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000364/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000365/// double. All other argument types are converted by UsualUnaryConversions().
366void Sema::DefaultArgumentPromotion(Expr *&Expr) {
367 QualType Ty = Expr->getType();
368 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000369
John McCall40c29132010-12-06 18:36:11 +0000370 UsualUnaryConversions(Expr);
371
Chris Lattner05faf172008-07-25 22:25:12 +0000372 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000373 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John McCall40c29132010-12-06 18:36:11 +0000374 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
Chris Lattner05faf172008-07-25 22:25:12 +0000375}
376
Chris Lattner312531a2009-04-12 08:11:20 +0000377/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
378/// will warn if the resulting type is not a POD type, and rejects ObjC
379/// interfaces passed by value. This returns true if the argument type is
380/// completely illegal.
Chris Lattner40378332010-05-16 04:01:30 +0000381bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
382 FunctionDecl *FDecl) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000383 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Chris Lattner40378332010-05-16 04:01:30 +0000385 // __builtin_va_start takes the second argument as a "varargs" argument, but
386 // it doesn't actually do anything with it. It doesn't need to be non-pod
387 // etc.
388 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
389 return false;
390
John McCallc12c5bb2010-05-15 11:32:37 +0000391 if (Expr->getType()->isObjCObjectType() &&
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000392 DiagRuntimeBehavior(Expr->getLocStart(),
393 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
394 << Expr->getType() << CT))
395 return true;
Douglas Gregor75b699a2009-12-12 07:25:49 +0000396
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000397 if (!Expr->getType()->isPODType() &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000398 DiagRuntimeBehavior(Expr->getLocStart(),
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000399 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
400 << Expr->getType() << CT))
401 return true;
Chris Lattner312531a2009-04-12 08:11:20 +0000402
403 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000404}
405
Chris Lattnere7a2e912008-07-25 21:10:04 +0000406/// UsualArithmeticConversions - Performs various conversions that are common to
407/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000408/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000409/// responsible for emitting appropriate error diagnostics.
410/// FIXME: verify the conversion rules for "complex int" are consistent with
411/// GCC.
412QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
413 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000414 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000415 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000416
417 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000418
Mike Stump1eb44332009-09-09 15:08:12 +0000419 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000420 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000421 QualType lhs =
422 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000423 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000424 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000425
426 // If both types are identical, no conversion is needed.
427 if (lhs == rhs)
428 return lhs;
429
430 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
431 // The caller can deal with this (e.g. pointer + int).
432 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
433 return lhs;
434
John McCallcf33b242010-11-13 08:17:45 +0000435 // Apply unary and bitfield promotions to the LHS's type.
436 QualType lhs_unpromoted = lhs;
437 if (lhs->isPromotableIntegerType())
438 lhs = Context.getPromotedIntegerType(lhs);
Eli Friedman04e83572009-08-20 04:21:42 +0000439 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000440 if (!LHSBitfieldPromoteTy.isNull())
441 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000442 if (lhs != lhs_unpromoted && !isCompAssign)
443 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000444
John McCallcf33b242010-11-13 08:17:45 +0000445 // If both types are identical, no conversion is needed.
446 if (lhs == rhs)
447 return lhs;
448
449 // At this point, we have two different arithmetic types.
450
451 // Handle complex types first (C99 6.3.1.8p1).
452 bool LHSComplexFloat = lhs->isComplexType();
453 bool RHSComplexFloat = rhs->isComplexType();
454 if (LHSComplexFloat || RHSComplexFloat) {
455 // if we have an integer operand, the result is the complex type.
456
John McCall2bb5d002010-11-13 09:02:35 +0000457 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
458 if (rhs->isIntegerType()) {
459 QualType fp = cast<ComplexType>(lhs)->getElementType();
460 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
461 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
462 } else {
463 assert(rhs->isComplexIntegerType());
John McCallf3ea8cf2010-11-14 08:17:51 +0000464 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000465 }
John McCallcf33b242010-11-13 08:17:45 +0000466 return lhs;
467 }
468
John McCall2bb5d002010-11-13 09:02:35 +0000469 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
470 if (!isCompAssign) {
471 // int -> float -> _Complex float
472 if (lhs->isIntegerType()) {
473 QualType fp = cast<ComplexType>(rhs)->getElementType();
474 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
475 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
476 } else {
477 assert(lhs->isComplexIntegerType());
John McCallf3ea8cf2010-11-14 08:17:51 +0000478 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000479 }
480 }
John McCallcf33b242010-11-13 08:17:45 +0000481 return rhs;
482 }
483
484 // This handles complex/complex, complex/float, or float/complex.
485 // When both operands are complex, the shorter operand is converted to the
486 // type of the longer, and that is the type of the result. This corresponds
487 // to what is done when combining two real floating-point operands.
488 // The fun begins when size promotion occur across type domains.
489 // From H&S 6.3.4: When one operand is complex and the other is a real
490 // floating-point type, the less precise type is converted, within it's
491 // real or complex domain, to the precision of the other type. For example,
492 // when combining a "long double" with a "double _Complex", the
493 // "double _Complex" is promoted to "long double _Complex".
494 int order = Context.getFloatingTypeOrder(lhs, rhs);
495
496 // If both are complex, just cast to the more precise type.
497 if (LHSComplexFloat && RHSComplexFloat) {
498 if (order > 0) {
499 // _Complex float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000500 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000501 return lhs;
502
503 } else if (order < 0) {
504 // _Complex float -> _Complex double
505 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000506 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000507 return rhs;
508 }
509 return lhs;
510 }
511
512 // If just the LHS is complex, the RHS needs to be converted,
513 // and the LHS might need to be promoted.
514 if (LHSComplexFloat) {
515 if (order > 0) { // LHS is wider
516 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000517 QualType fp = cast<ComplexType>(lhs)->getElementType();
518 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
519 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000520 return lhs;
521 }
522
523 // RHS is at least as wide. Find its corresponding complex type.
524 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
525
526 // double -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000527 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000528
529 // _Complex float -> _Complex double
530 if (!isCompAssign && order < 0)
John McCall2bb5d002010-11-13 09:02:35 +0000531 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000532
533 return result;
534 }
535
536 // Just the RHS is complex, so the LHS needs to be converted
537 // and the RHS might need to be promoted.
538 assert(RHSComplexFloat);
539
540 if (order < 0) { // RHS is wider
541 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000542 if (!isCompAssign) {
Argyrios Kyrtzidise1889332011-01-18 18:49:33 +0000543 QualType fp = cast<ComplexType>(rhs)->getElementType();
544 ImpCastExprToType(lhsExpr, fp, CK_FloatingCast);
John McCall2bb5d002010-11-13 09:02:35 +0000545 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
546 }
John McCallcf33b242010-11-13 08:17:45 +0000547 return rhs;
548 }
549
550 // LHS is at least as wide. Find its corresponding complex type.
551 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
552
553 // double -> _Complex double
554 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000555 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000556
557 // _Complex float -> _Complex double
558 if (order > 0)
John McCall2bb5d002010-11-13 09:02:35 +0000559 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000560
561 return result;
562 }
563
564 // Now handle "real" floating types (i.e. float, double, long double).
565 bool LHSFloat = lhs->isRealFloatingType();
566 bool RHSFloat = rhs->isRealFloatingType();
567 if (LHSFloat || RHSFloat) {
568 // If we have two real floating types, convert the smaller operand
569 // to the bigger result.
570 if (LHSFloat && RHSFloat) {
571 int order = Context.getFloatingTypeOrder(lhs, rhs);
572 if (order > 0) {
573 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
574 return lhs;
575 }
576
577 assert(order < 0 && "illegal float comparison");
578 if (!isCompAssign)
579 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
580 return rhs;
581 }
582
583 // If we have an integer operand, the result is the real floating type.
584 if (LHSFloat) {
585 if (rhs->isIntegerType()) {
586 // Convert rhs to the lhs floating point type.
587 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
588 return lhs;
589 }
590
591 // Convert both sides to the appropriate complex float.
592 assert(rhs->isComplexIntegerType());
593 QualType result = Context.getComplexType(lhs);
594
595 // _Complex int -> _Complex float
John McCallf3ea8cf2010-11-14 08:17:51 +0000596 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000597
598 // float -> _Complex float
599 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000600 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000601
602 return result;
603 }
604
605 assert(RHSFloat);
606 if (lhs->isIntegerType()) {
607 // Convert lhs to the rhs floating point type.
608 if (!isCompAssign)
609 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
610 return rhs;
611 }
612
613 // Convert both sides to the appropriate complex float.
614 assert(lhs->isComplexIntegerType());
615 QualType result = Context.getComplexType(rhs);
616
617 // _Complex int -> _Complex float
618 if (!isCompAssign)
John McCallf3ea8cf2010-11-14 08:17:51 +0000619 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000620
621 // float -> _Complex float
John McCall2bb5d002010-11-13 09:02:35 +0000622 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000623
624 return result;
625 }
626
627 // Handle GCC complex int extension.
628 // FIXME: if the operands are (int, _Complex long), we currently
629 // don't promote the complex. Also, signedness?
630 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
631 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
632 if (lhsComplexInt && rhsComplexInt) {
633 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
634 rhsComplexInt->getElementType());
635 assert(order && "inequal types with equal element ordering");
636 if (order > 0) {
637 // _Complex int -> _Complex long
John McCall2bb5d002010-11-13 09:02:35 +0000638 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000639 return lhs;
640 }
641
642 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000643 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000644 return rhs;
645 } else if (lhsComplexInt) {
646 // int -> _Complex int
John McCall2bb5d002010-11-13 09:02:35 +0000647 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000648 return lhs;
649 } else if (rhsComplexInt) {
650 // int -> _Complex int
651 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000652 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000653 return rhs;
654 }
655
656 // Finally, we have two differing integer types.
657 // The rules for this case are in C99 6.3.1.8
658 int compare = Context.getIntegerTypeOrder(lhs, rhs);
659 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
660 rhsSigned = rhs->hasSignedIntegerRepresentation();
661 if (lhsSigned == rhsSigned) {
662 // Same signedness; use the higher-ranked type
663 if (compare >= 0) {
664 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
665 return lhs;
666 } else if (!isCompAssign)
667 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
668 return rhs;
669 } else if (compare != (lhsSigned ? 1 : -1)) {
670 // The unsigned type has greater than or equal rank to the
671 // signed type, so use the unsigned type
672 if (rhsSigned) {
673 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
674 return lhs;
675 } else if (!isCompAssign)
676 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
677 return rhs;
678 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
679 // The two types are different widths; if we are here, that
680 // means the signed type is larger than the unsigned type, so
681 // use the signed type.
682 if (lhsSigned) {
683 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
684 return lhs;
685 } else if (!isCompAssign)
686 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
687 return rhs;
688 } else {
689 // The signed type is higher-ranked than the unsigned type,
690 // but isn't actually any bigger (like unsigned int and long
691 // on most 32-bit systems). Use the unsigned type corresponding
692 // to the signed type.
693 QualType result =
694 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
695 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
696 if (!isCompAssign)
697 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
698 return result;
699 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000700}
701
Chris Lattnere7a2e912008-07-25 21:10:04 +0000702//===----------------------------------------------------------------------===//
703// Semantic Analysis for various Expression Types
704//===----------------------------------------------------------------------===//
705
706
Steve Narofff69936d2007-09-16 03:34:24 +0000707/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000708/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
709/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
710/// multiple tokens. However, the common case is that StringToks points to one
711/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000712///
John McCall60d7b3a2010-08-24 06:29:42 +0000713ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +0000714Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 assert(NumStringToks && "Must have at least one string!");
716
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000717 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000718 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000719 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000720
721 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
722 for (unsigned i = 0; i != NumStringToks; ++i)
723 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000724
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000725 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000726 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000727 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000728
729 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +0000730 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +0000731 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000732
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000733 // Get an array type for the string, according to C99 6.4.5. This includes
734 // the nul terminator character as well as the string length for pascal
735 // strings.
736 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000737 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000738 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Reid Spencer5f016e22007-07-11 17:01:13 +0000740 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +0000741 return Owned(StringLiteral::Create(Context, Literal.GetString(),
742 Literal.GetStringLength(),
743 Literal.AnyWide, StrTy,
744 &StringTokLocs[0],
745 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000746}
747
John McCall469a1eb2011-02-02 13:00:07 +0000748enum CaptureResult {
749 /// No capture is required.
750 CR_NoCapture,
751
752 /// A capture is required.
753 CR_Capture,
754
John McCall6b5a61b2011-02-07 10:33:21 +0000755 /// A by-ref capture is required.
756 CR_CaptureByRef,
757
John McCall469a1eb2011-02-02 13:00:07 +0000758 /// An error occurred when trying to capture the given variable.
759 CR_Error
760};
761
762/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +0000763///
John McCall469a1eb2011-02-02 13:00:07 +0000764/// \param var - the variable referenced
765/// \param DC - the context which we couldn't capture through
766static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +0000767diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +0000768 VarDecl *var, DeclContext *DC) {
769 switch (S.ExprEvalContexts.back().Context) {
770 case Sema::Unevaluated:
771 // The argument will never be evaluated, so don't complain.
772 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +0000773
John McCall469a1eb2011-02-02 13:00:07 +0000774 case Sema::PotentiallyEvaluated:
775 case Sema::PotentiallyEvaluatedIfUsed:
776 break;
Chris Lattner639e2d32008-10-20 05:16:36 +0000777
John McCall469a1eb2011-02-02 13:00:07 +0000778 case Sema::PotentiallyPotentiallyEvaluated:
779 // FIXME: delay these!
780 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000781 }
Mike Stump1eb44332009-09-09 15:08:12 +0000782
John McCall469a1eb2011-02-02 13:00:07 +0000783 // Don't diagnose about capture if we're not actually in code right
784 // now; in general, there are more appropriate places that will
785 // diagnose this.
786 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
787
788 // This particular madness can happen in ill-formed default
789 // arguments; claim it's okay and let downstream code handle it.
790 if (isa<ParmVarDecl>(var) &&
791 S.CurContext == var->getDeclContext()->getParent())
792 return CR_NoCapture;
793
794 DeclarationName functionName;
795 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
796 functionName = fn->getDeclName();
797 // FIXME: variable from enclosing block that we couldn't capture from!
798
799 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
800 << var->getIdentifier() << functionName;
801 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
802 << var->getIdentifier();
803
804 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +0000805}
806
John McCall6b5a61b2011-02-07 10:33:21 +0000807/// There is a well-formed capture at a particular scope level;
808/// propagate it through all the nested blocks.
809static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
810 const BlockDecl::Capture &capture) {
811 VarDecl *var = capture.getVariable();
812
813 // Update all the inner blocks with the capture information.
814 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
815 i != e; ++i) {
816 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
817 innerBlock->Captures.push_back(
818 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
819 /*nested*/ true, capture.getCopyExpr()));
820 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
821 }
822
823 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
824}
825
826/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +0000827/// given value in the current context requires a variable capture.
828///
829/// This also keeps the captures set in the BlockScopeInfo records
830/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +0000831static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +0000832 ValueDecl *value) {
833 // Only variables ever require capture.
834 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +0000835 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +0000836
837 // Fast path: variables from the current context never require capture.
838 DeclContext *DC = S.CurContext;
839 if (var->getDeclContext() == DC) return CR_NoCapture;
840
841 // Only variables with local storage require capture.
842 // FIXME: What about 'const' variables in C++?
843 if (!var->hasLocalStorage()) return CR_NoCapture;
844
845 // Otherwise, we need to capture.
846
847 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +0000848 do {
849 // Only blocks (and eventually C++0x closures) can capture; other
850 // scopes don't work.
851 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +0000852 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +0000853
854 BlockScopeInfo *blockScope =
855 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
856 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
857
John McCall6b5a61b2011-02-07 10:33:21 +0000858 // Check whether we've already captured it in this block. If so,
859 // we're done.
860 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
861 return propagateCapture(S, functionScopesIndex,
862 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +0000863
864 functionScopesIndex--;
865 DC = cast<BlockDecl>(DC)->getDeclContext();
866 } while (var->getDeclContext() != DC);
867
John McCall6b5a61b2011-02-07 10:33:21 +0000868 // Okay, we descended all the way to the block that defines the variable.
869 // Actually try to capture it.
870 QualType type = var->getType();
871
872 // Prohibit variably-modified types.
873 if (type->isVariablyModifiedType()) {
874 S.Diag(loc, diag::err_ref_vm_type);
875 S.Diag(var->getLocation(), diag::note_declared_at);
876 return CR_Error;
877 }
878
879 // Prohibit arrays, even in __block variables, but not references to
880 // them.
881 if (type->isArrayType()) {
882 S.Diag(loc, diag::err_ref_array_type);
883 S.Diag(var->getLocation(), diag::note_declared_at);
884 return CR_Error;
885 }
886
887 S.MarkDeclarationReferenced(loc, var);
888
889 // The BlocksAttr indicates the variable is bound by-reference.
890 bool byRef = var->hasAttr<BlocksAttr>();
891
892 // Build a copy expression.
893 Expr *copyExpr = 0;
894 if (!byRef && S.getLangOptions().CPlusPlus &&
895 !type->isDependentType() && type->isStructureOrClassType()) {
896 // According to the blocks spec, the capture of a variable from
897 // the stack requires a const copy constructor. This is not true
898 // of the copy/move done to move a __block variable to the heap.
899 type.addConst();
900
901 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
902 ExprResult result =
903 S.PerformCopyInitialization(
904 InitializedEntity::InitializeBlock(var->getLocation(),
905 type, false),
906 loc, S.Owned(declRef));
907
908 // Build a full-expression copy expression if initialization
909 // succeeded and used a non-trivial constructor. Recover from
910 // errors by pretending that the copy isn't necessary.
911 if (!result.isInvalid() &&
912 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
913 result = S.MaybeCreateExprWithCleanups(result);
914 copyExpr = result.take();
915 }
916 }
917
918 // We're currently at the declarer; go back to the closure.
919 functionScopesIndex++;
920 BlockScopeInfo *blockScope =
921 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
922
923 // Build a valid capture in this scope.
924 blockScope->Captures.push_back(
925 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
926 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
927
928 // Propagate that to inner captures if necessary.
929 return propagateCapture(S, functionScopesIndex,
930 blockScope->Captures.back());
931}
932
933static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
934 const DeclarationNameInfo &NameInfo,
935 bool byRef) {
936 assert(isa<VarDecl>(vd) && "capturing non-variable");
937
938 VarDecl *var = cast<VarDecl>(vd);
939 assert(var->hasLocalStorage() && "capturing non-local");
940 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
941
942 QualType exprType = var->getType().getNonReferenceType();
943
944 BlockDeclRefExpr *BDRE;
945 if (!byRef) {
946 // The variable will be bound by copy; make it const within the
947 // closure, but record that this was done in the expression.
948 bool constAdded = !exprType.isConstQualified();
949 exprType.addConst();
950
951 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
952 NameInfo.getLoc(), false,
953 constAdded);
954 } else {
955 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
956 NameInfo.getLoc(), true);
957 }
958
959 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +0000960}
Chris Lattner639e2d32008-10-20 05:16:36 +0000961
John McCall60d7b3a2010-08-24 06:29:42 +0000962ExprResult
John McCallf89e55a2010-11-18 06:31:45 +0000963Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +0000964 SourceLocation Loc,
965 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000966 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +0000967 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +0000968}
969
John McCall76a40212011-02-09 01:13:10 +0000970/// BuildDeclRefExpr - Build an expression that references a
971/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +0000972ExprResult
John McCall76a40212011-02-09 01:13:10 +0000973Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +0000974 const DeclarationNameInfo &NameInfo,
975 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000976 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +0000977
John McCall7eb0a9e2010-11-24 05:12:34 +0000978 Expr *E = DeclRefExpr::Create(Context,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000979 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
John McCall7eb0a9e2010-11-24 05:12:34 +0000980 SS? SS->getRange() : SourceRange(),
981 D, NameInfo, Ty, VK);
982
983 // Just in case we're building an illegal pointer-to-member.
984 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
985 E->setObjectKind(OK_BitField);
986
987 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +0000988}
989
John McCalldfa1edb2010-11-23 20:48:44 +0000990static ExprResult
991BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
992 const CXXScopeSpec &SS, FieldDecl *Field,
993 DeclAccessPair FoundDecl,
994 const DeclarationNameInfo &MemberNameInfo);
995
John McCall60d7b3a2010-08-24 06:29:42 +0000996ExprResult
John McCall5808ce42011-02-03 08:15:49 +0000997Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
998 SourceLocation loc,
999 IndirectFieldDecl *indirectField,
1000 Expr *baseObjectExpr,
1001 SourceLocation opLoc) {
1002 // First, build the expression that refers to the base object.
1003
1004 bool baseObjectIsPointer = false;
1005 Qualifiers baseQuals;
1006
1007 // Case 1: the base of the indirect field is not a field.
1008 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregorf5848322011-02-18 02:44:58 +00001009 CXXScopeSpec EmptySS;
John McCall5808ce42011-02-03 08:15:49 +00001010 if (baseVariable) {
1011 assert(baseVariable->getType()->isRecordType());
1012
1013 // In principle we could have a member access expression that
1014 // accesses an anonymous struct/union that's a static member of
1015 // the base object's class. However, under the current standard,
1016 // static data members cannot be anonymous structs or unions.
1017 // Supporting this is as easy as building a MemberExpr here.
1018 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1019
1020 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1021
1022 ExprResult result =
Douglas Gregorf5848322011-02-18 02:44:58 +00001023 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCall5808ce42011-02-03 08:15:49 +00001024 if (result.isInvalid()) return ExprError();
1025
1026 baseObjectExpr = result.take();
1027 baseObjectIsPointer = false;
1028 baseQuals = baseObjectExpr->getType().getQualifiers();
1029
1030 // Case 2: the base of the indirect field is a field and the user
1031 // wrote a member expression.
1032 } else if (baseObjectExpr) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001033 // The caller provided the base object expression. Determine
1034 // whether its a pointer and whether it adds any qualifiers to the
1035 // anonymous struct/union fields we're looking into.
John McCall5808ce42011-02-03 08:15:49 +00001036 QualType objectType = baseObjectExpr->getType();
1037
1038 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1039 baseObjectIsPointer = true;
1040 objectType = ptr->getPointeeType();
1041 } else {
1042 baseObjectIsPointer = false;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001043 }
John McCall5808ce42011-02-03 08:15:49 +00001044 baseQuals = objectType.getQualifiers();
1045
1046 // Case 3: the base of the indirect field is a field and we should
1047 // build an implicit member access.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001048 } else {
1049 // We've found a member of an anonymous struct/union that is
1050 // inside a non-anonymous struct/union, so in a well-formed
1051 // program our base object expression is "this".
John McCall5808ce42011-02-03 08:15:49 +00001052 CXXMethodDecl *method = tryCaptureCXXThis();
1053 if (!method) {
1054 Diag(loc, diag::err_invalid_member_use_in_static_method)
1055 << indirectField->getDeclName();
1056 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001057 }
1058
John McCall5808ce42011-02-03 08:15:49 +00001059 // Our base object expression is "this".
1060 baseObjectExpr =
1061 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1062 /*isImplicit=*/ true);
1063 baseObjectIsPointer = true;
1064 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001065 }
1066
1067 // Build the implicit member references to the field of the
1068 // anonymous struct/union.
John McCall5808ce42011-02-03 08:15:49 +00001069 Expr *result = baseObjectExpr;
1070 IndirectFieldDecl::chain_iterator
1071 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCalldfa1edb2010-11-23 20:48:44 +00001072
John McCall5808ce42011-02-03 08:15:49 +00001073 // Build the first member access in the chain with full information.
1074 if (!baseVariable) {
1075 FieldDecl *field = cast<FieldDecl>(*FI);
John McCalldfa1edb2010-11-23 20:48:44 +00001076
John McCall5808ce42011-02-03 08:15:49 +00001077 // FIXME: use the real found-decl info!
1078 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall0953e762009-09-24 19:53:00 +00001079
John McCall5808ce42011-02-03 08:15:49 +00001080 // Make a nameInfo that properly uses the anonymous name.
1081 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall0953e762009-09-24 19:53:00 +00001082
John McCall5808ce42011-02-03 08:15:49 +00001083 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregorf5848322011-02-18 02:44:58 +00001084 EmptySS, field, foundDecl,
John McCall5808ce42011-02-03 08:15:49 +00001085 memberNameInfo).take();
1086 baseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +00001087
John McCall5808ce42011-02-03 08:15:49 +00001088 // FIXME: check qualified member access
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001089 }
1090
John McCall5808ce42011-02-03 08:15:49 +00001091 // In all cases, we should now skip the first declaration in the chain.
1092 ++FI;
1093
Douglas Gregorf5848322011-02-18 02:44:58 +00001094 while (FI != FEnd) {
1095 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCall5808ce42011-02-03 08:15:49 +00001096
1097 // FIXME: these are somewhat meaningless
1098 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1099 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall5808ce42011-02-03 08:15:49 +00001100
1101 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregorf5848322011-02-18 02:44:58 +00001102 (FI == FEnd? SS : EmptySS), field,
1103 foundDecl, memberNameInfo)
John McCall5808ce42011-02-03 08:15:49 +00001104 .take();
1105 }
1106
1107 return Owned(result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001108}
1109
Abramo Bagnara25777432010-08-11 22:01:17 +00001110/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001111/// possibly a list of template arguments.
1112///
1113/// If this produces template arguments, it is permitted to call
1114/// DecomposeTemplateName.
1115///
1116/// This actually loses a lot of source location information for
1117/// non-standard name kinds; we should consider preserving that in
1118/// some way.
1119static void DecomposeUnqualifiedId(Sema &SemaRef,
1120 const UnqualifiedId &Id,
1121 TemplateArgumentListInfo &Buffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00001122 DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00001123 const TemplateArgumentListInfo *&TemplateArgs) {
1124 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1125 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1126 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1127
1128 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1129 Id.TemplateId->getTemplateArgs(),
1130 Id.TemplateId->NumArgs);
1131 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1132 TemplateArgsPtr.release();
1133
John McCall2b5289b2010-08-23 07:28:44 +00001134 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001135 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1136 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001137 TemplateArgs = &Buffer;
1138 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001139 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001140 TemplateArgs = 0;
1141 }
1142}
1143
John McCallaa81e162009-12-01 22:10:20 +00001144/// Determines if the given class is provably not derived from all of
1145/// the prospective base classes.
1146static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1147 CXXRecordDecl *Record,
1148 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +00001149 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +00001150 return false;
1151
Douglas Gregor952b0172010-02-11 01:04:33 +00001152 RecordDecl *RD = Record->getDefinition();
John McCallb1b42562009-12-01 22:28:41 +00001153 if (!RD) return false;
1154 Record = cast<CXXRecordDecl>(RD);
1155
John McCallaa81e162009-12-01 22:10:20 +00001156 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1157 E = Record->bases_end(); I != E; ++I) {
1158 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1159 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1160 if (!BaseRT) return false;
1161
1162 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +00001163 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1164 return false;
1165 }
1166
1167 return true;
1168}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001169
John McCallaa81e162009-12-01 22:10:20 +00001170enum IMAKind {
1171 /// The reference is definitely not an instance member access.
1172 IMA_Static,
1173
1174 /// The reference may be an implicit instance member access.
1175 IMA_Mixed,
1176
1177 /// The reference may be to an instance member, but it is invalid if
1178 /// so, because the context is not an instance method.
1179 IMA_Mixed_StaticContext,
1180
1181 /// The reference may be to an instance member, but it is invalid if
1182 /// so, because the context is from an unrelated class.
1183 IMA_Mixed_Unrelated,
1184
1185 /// The reference is definitely an implicit instance member access.
1186 IMA_Instance,
1187
1188 /// The reference may be to an unresolved using declaration.
1189 IMA_Unresolved,
1190
1191 /// The reference may be to an unresolved using declaration and the
1192 /// context is not an instance method.
1193 IMA_Unresolved_StaticContext,
1194
John McCallaa81e162009-12-01 22:10:20 +00001195 /// All possible referrents are instance members and the current
1196 /// context is not an instance method.
1197 IMA_Error_StaticContext,
1198
1199 /// All possible referrents are instance members of an unrelated
1200 /// class.
1201 IMA_Error_Unrelated
1202};
1203
1204/// The given lookup names class member(s) and is not being used for
1205/// an address-of-member expression. Classify the type of access
1206/// according to whether it's possible that this reference names an
1207/// instance member. This is best-effort; it is okay to
1208/// conservatively answer "yes", in which case some errors will simply
1209/// not be caught until template-instantiation.
1210static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1211 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +00001212 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +00001213
John McCallea1471e2010-05-20 01:18:31 +00001214 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCallaa81e162009-12-01 22:10:20 +00001215 bool isStaticContext =
John McCallea1471e2010-05-20 01:18:31 +00001216 (!isa<CXXMethodDecl>(DC) ||
1217 cast<CXXMethodDecl>(DC)->isStatic());
John McCallaa81e162009-12-01 22:10:20 +00001218
1219 if (R.isUnresolvableResult())
1220 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1221
1222 // Collect all the declaring classes of instance members we find.
1223 bool hasNonInstance = false;
Sebastian Redlf9780002010-11-26 16:28:07 +00001224 bool hasField = false;
John McCallaa81e162009-12-01 22:10:20 +00001225 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1226 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall161755a2010-04-06 21:38:20 +00001227 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00001228
John McCall161755a2010-04-06 21:38:20 +00001229 if (D->isCXXInstanceMember()) {
Sebastian Redlf9780002010-11-26 16:28:07 +00001230 if (dyn_cast<FieldDecl>(D))
1231 hasField = true;
1232
John McCallaa81e162009-12-01 22:10:20 +00001233 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCallaa81e162009-12-01 22:10:20 +00001234 Classes.insert(R->getCanonicalDecl());
1235 }
1236 else
1237 hasNonInstance = true;
1238 }
1239
1240 // If we didn't find any instance members, it can't be an implicit
1241 // member reference.
1242 if (Classes.empty())
1243 return IMA_Static;
1244
1245 // If the current context is not an instance method, it can't be
1246 // an implicit member reference.
Sebastian Redlf9780002010-11-26 16:28:07 +00001247 if (isStaticContext) {
1248 if (hasNonInstance)
1249 return IMA_Mixed_StaticContext;
1250
1251 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1252 // C++0x [expr.prim.general]p10:
1253 // An id-expression that denotes a non-static data member or non-static
1254 // member function of a class can only be used:
1255 // (...)
1256 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1257 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1258 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1259 if (isUnevaluatedExpression)
1260 return IMA_Mixed_StaticContext;
1261 }
1262
1263 return IMA_Error_StaticContext;
1264 }
John McCallaa81e162009-12-01 22:10:20 +00001265
1266 // If we can prove that the current context is unrelated to all the
1267 // declaring classes, it can't be an implicit member reference (in
1268 // which case it's an error if any of those members are selected).
1269 if (IsProvablyNotDerivedFrom(SemaRef,
John McCallea1471e2010-05-20 01:18:31 +00001270 cast<CXXMethodDecl>(DC)->getParent(),
John McCallaa81e162009-12-01 22:10:20 +00001271 Classes))
1272 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1273
1274 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1275}
1276
1277/// Diagnose a reference to a field with no object available.
1278static void DiagnoseInstanceReference(Sema &SemaRef,
1279 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00001280 NamedDecl *rep,
1281 const DeclarationNameInfo &nameInfo) {
1282 SourceLocation Loc = nameInfo.getLoc();
John McCallaa81e162009-12-01 22:10:20 +00001283 SourceRange Range(Loc);
1284 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1285
John McCall5808ce42011-02-03 08:15:49 +00001286 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCallaa81e162009-12-01 22:10:20 +00001287 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1288 if (MD->isStatic()) {
1289 // "invalid use of member 'x' in static member function"
1290 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCall5808ce42011-02-03 08:15:49 +00001291 << Range << nameInfo.getName();
John McCallaa81e162009-12-01 22:10:20 +00001292 return;
1293 }
1294 }
1295
1296 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCall5808ce42011-02-03 08:15:49 +00001297 << nameInfo.getName() << Range;
John McCallaa81e162009-12-01 22:10:20 +00001298 return;
1299 }
1300
1301 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +00001302}
1303
John McCall578b69b2009-12-16 08:11:27 +00001304/// Diagnose an empty lookup.
1305///
1306/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001307bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1308 CorrectTypoContext CTC) {
John McCall578b69b2009-12-16 08:11:27 +00001309 DeclarationName Name = R.getLookupName();
1310
John McCall578b69b2009-12-16 08:11:27 +00001311 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001312 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001313 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1314 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001315 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001316 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001317 diagnostic_suggest = diag::err_undeclared_use_suggest;
1318 }
John McCall578b69b2009-12-16 08:11:27 +00001319
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001320 // If the original lookup was an unqualified lookup, fake an
1321 // unqualified lookup. This is useful when (for example) the
1322 // original lookup would not have found something because it was a
1323 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001324 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001325 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001326 if (isa<CXXRecordDecl>(DC)) {
1327 LookupQualifiedName(R, DC);
1328
1329 if (!R.empty()) {
1330 // Don't give errors about ambiguities in this lookup.
1331 R.suppressDiagnostics();
1332
1333 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1334 bool isInstance = CurMethod &&
1335 CurMethod->isInstance() &&
1336 DC == CurMethod->getParent();
1337
1338 // Give a code modification hint to insert 'this->'.
1339 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1340 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001341 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001342 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1343 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001344 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001345 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001346 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001347 Diag(R.getNameLoc(), diagnostic) << Name
1348 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1349 QualType DepThisType = DepMethod->getThisType(Context);
1350 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1351 R.getNameLoc(), DepThisType, false);
1352 TemplateArgumentListInfo TList;
1353 if (ULE->hasExplicitTemplateArgs())
1354 ULE->copyTemplateArgumentsInto(TList);
1355 CXXDependentScopeMemberExpr *DepExpr =
1356 CXXDependentScopeMemberExpr::Create(
1357 Context, DepThis, DepThisType, true, SourceLocation(),
1358 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
1359 R.getLookupNameInfo(), &TList);
1360 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001361 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001362 // FIXME: we should be able to handle this case too. It is correct
1363 // to add this-> here. This is a workaround for PR7947.
1364 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001365 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001366 } else {
John McCall578b69b2009-12-16 08:11:27 +00001367 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001368 }
John McCall578b69b2009-12-16 08:11:27 +00001369
1370 // Do we really want to note all of these?
1371 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1372 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1373
1374 // Tell the callee to try to recover.
1375 return false;
1376 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001377
1378 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001379 }
1380 }
1381
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001382 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001383 DeclarationName Corrected;
Daniel Dunbardc32cdf2010-06-02 15:46:52 +00001384 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001385 if (!R.empty()) {
1386 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1387 if (SS.isEmpty())
1388 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1389 << FixItHint::CreateReplacement(R.getNameLoc(),
1390 R.getLookupName().getAsString());
1391 else
1392 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1393 << Name << computeDeclContext(SS, false) << R.getLookupName()
1394 << SS.getRange()
1395 << FixItHint::CreateReplacement(R.getNameLoc(),
1396 R.getLookupName().getAsString());
1397 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1398 Diag(ND->getLocation(), diag::note_previous_decl)
1399 << ND->getDeclName();
1400
1401 // Tell the callee to try to recover.
1402 return false;
1403 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001404
Douglas Gregoraaf87162010-04-14 20:04:41 +00001405 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1406 // FIXME: If we ended up with a typo for a type name or
1407 // Objective-C class name, we're in trouble because the parser
1408 // is in the wrong place to recover. Suggest the typo
1409 // correction, but don't make it a fix-it since we're not going
1410 // to recover well anyway.
1411 if (SS.isEmpty())
1412 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1413 else
1414 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1415 << Name << computeDeclContext(SS, false) << R.getLookupName()
1416 << SS.getRange();
1417
1418 // Don't try to recover; it won't work.
1419 return true;
1420 }
1421 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001422 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001423 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001424 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +00001425 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001426 else
Douglas Gregord203a162010-01-01 00:15:04 +00001427 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001428 << Name << computeDeclContext(SS, false) << Corrected
1429 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001430 return true;
1431 }
Douglas Gregord203a162010-01-01 00:15:04 +00001432 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001433 }
1434
1435 // Emit a special diagnostic for failed member lookups.
1436 // FIXME: computing the declaration context might fail here (?)
1437 if (!SS.isEmpty()) {
1438 Diag(R.getNameLoc(), diag::err_no_member)
1439 << Name << computeDeclContext(SS, false)
1440 << SS.getRange();
1441 return true;
1442 }
1443
John McCall578b69b2009-12-16 08:11:27 +00001444 // Give up, we can't recover.
1445 Diag(R.getNameLoc(), diagnostic) << Name;
1446 return true;
1447}
1448
Douglas Gregorca45da02010-11-02 20:36:02 +00001449ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1450 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001451 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1452 if (!IDecl)
1453 return 0;
1454 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1455 if (!ClassImpDecl)
1456 return 0;
Douglas Gregorca45da02010-11-02 20:36:02 +00001457 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001458 if (!property)
1459 return 0;
1460 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregorca45da02010-11-02 20:36:02 +00001461 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1462 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001463 return 0;
1464 return property;
1465}
1466
Douglas Gregorca45da02010-11-02 20:36:02 +00001467bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1468 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1469 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1470 if (!IDecl)
1471 return false;
1472 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1473 if (!ClassImpDecl)
1474 return false;
1475 if (ObjCPropertyImplDecl *PIDecl
1476 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1477 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1478 PIDecl->getPropertyIvarDecl())
1479 return false;
1480
1481 return true;
1482}
1483
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001484static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001485 LookupResult &Lookup,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001486 IdentifierInfo *II,
1487 SourceLocation NameLoc) {
1488 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001489 bool LookForIvars;
1490 if (Lookup.empty())
1491 LookForIvars = true;
1492 else if (CurMeth->isClassMethod())
1493 LookForIvars = false;
1494 else
1495 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahaniand0fbadd2011-01-26 00:57:01 +00001496 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1497 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001498 if (!LookForIvars)
1499 return 0;
1500
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001501 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1502 if (!IDecl)
1503 return 0;
1504 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001505 if (!ClassImpDecl)
1506 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001507 bool DynamicImplSeen = false;
1508 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1509 if (!property)
1510 return 0;
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001511 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001512 DynamicImplSeen =
1513 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001514 // property implementation has a designated ivar. No need to assume a new
1515 // one.
1516 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1517 return 0;
1518 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001519 if (!DynamicImplSeen) {
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001520 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1521 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001522 NameLoc,
1523 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian75049662010-12-15 23:29:04 +00001524 ObjCIvarDecl::Private,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001525 (Expr *)0, true);
1526 ClassImpDecl->addDecl(Ivar);
1527 IDecl->makeDeclVisibleInContext(Ivar, false);
1528 property->setPropertyIvarDecl(Ivar);
1529 return Ivar;
1530 }
1531 return 0;
1532}
1533
John McCall60d7b3a2010-08-24 06:29:42 +00001534ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001535 CXXScopeSpec &SS,
1536 UnqualifiedId &Id,
1537 bool HasTrailingLParen,
1538 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001539 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1540 "cannot be direct & operand and have a trailing lparen");
1541
1542 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001543 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001544
John McCall129e2df2009-11-30 22:42:35 +00001545 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001546
1547 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001548 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001549 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnara25777432010-08-11 22:01:17 +00001550 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001551
Abramo Bagnara25777432010-08-11 22:01:17 +00001552 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001553 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001554 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001555
John McCallf7a1a742009-11-24 19:00:30 +00001556 // C++ [temp.dep.expr]p3:
1557 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001558 // -- an identifier that was declared with a dependent type,
1559 // (note: handled after lookup)
1560 // -- a template-id that is dependent,
1561 // (note: handled in BuildTemplateIdExpr)
1562 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001563 // -- a nested-name-specifier that contains a class-name that
1564 // names a dependent type.
1565 // Determine whether this is a member of an unknown specialization;
1566 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001567 bool DependentID = false;
1568 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1569 Name.getCXXNameType()->isDependentType()) {
1570 DependentID = true;
1571 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001572 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001573 if (RequireCompleteDeclContext(SS, DC))
1574 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001575 } else {
1576 DependentID = true;
1577 }
1578 }
1579
Chris Lattner337e5502011-02-18 01:27:55 +00001580 if (DependentID)
Abramo Bagnara25777432010-08-11 22:01:17 +00001581 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001582 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001583
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001584 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001585 // Perform the required lookup.
Abramo Bagnara25777432010-08-11 22:01:17 +00001586 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001587 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001588 // Lookup the template name again to correctly establish the context in
1589 // which it was found. This is really unfortunate as we already did the
1590 // lookup to determine that it was a template name in the first place. If
1591 // this becomes a performance hit, we can work harder to preserve those
1592 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001593 bool MemberOfUnknownSpecialization;
1594 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1595 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001596
1597 if (MemberOfUnknownSpecialization ||
1598 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1599 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1600 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001601 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001602 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001603 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001605 // If the result might be in a dependent base class, this is a dependent
1606 // id-expression.
1607 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1608 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1609 TemplateArgs);
1610
John McCallf7a1a742009-11-24 19:00:30 +00001611 // If this reference is in an Objective-C method, then we need to do
1612 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001613 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001614 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001615 if (E.isInvalid())
1616 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Chris Lattner337e5502011-02-18 01:27:55 +00001618 if (Expr *Ex = E.takeAs<Expr>())
1619 return Owned(Ex);
1620
1621 // Synthesize ivars lazily.
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001622 if (getLangOptions().ObjCDefaultSynthProperties &&
1623 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahaniande267602010-11-17 19:41:23 +00001624 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1625 if (const ObjCPropertyDecl *Property =
1626 canSynthesizeProvisionalIvar(II)) {
1627 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1628 Diag(Property->getLocation(), diag::note_property_declare);
1629 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001630 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1631 isAddressOfOperand);
Fariborz Jahaniande267602010-11-17 19:41:23 +00001632 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001633 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001634 // for further use, this must be set to false if in class method.
1635 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001636 }
Chris Lattner8a934232008-03-31 00:36:02 +00001637 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001638
John McCallf7a1a742009-11-24 19:00:30 +00001639 if (R.isAmbiguous())
1640 return ExprError();
1641
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001642 // Determine whether this name might be a candidate for
1643 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001644 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001645
John McCallf7a1a742009-11-24 19:00:30 +00001646 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001648 // in C90, extension in C99, forbidden in C++).
1649 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1650 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1651 if (D) R.addDecl(D);
1652 }
1653
1654 // If this name wasn't predeclared and if this is not a function
1655 // call, diagnose the problem.
1656 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001657 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001658 return ExprError();
1659
1660 assert(!R.empty() &&
1661 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001662
1663 // If we found an Objective-C instance variable, let
1664 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001665 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001666 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1667 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001668 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001669 assert(E.isInvalid() || E.get());
1670 return move(E);
1671 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 }
1673 }
Mike Stump1eb44332009-09-09 15:08:12 +00001674
John McCallf7a1a742009-11-24 19:00:30 +00001675 // This is guaranteed from this point on.
1676 assert(!R.empty() || ADL);
1677
1678 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001679 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001680 !(getLangOptions().ObjCDefaultSynthProperties &&
1681 getLangOptions().ObjCNonFragileABI2) &&
Fariborz Jahanianb1d58e32010-07-29 16:53:53 +00001682 Var->isFileVarDecl()) {
Douglas Gregorca45da02010-11-02 20:36:02 +00001683 ObjCPropertyDecl *Property = canSynthesizeProvisionalIvar(II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001684 if (Property) {
1685 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1686 Diag(Property->getLocation(), diag::note_property_declare);
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001687 Diag(Var->getLocation(), diag::note_global_declared_at);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001688 }
1689 }
Douglas Gregor751f9a42009-06-30 15:47:41 +00001690 }
Mike Stump1eb44332009-09-09 15:08:12 +00001691
John McCallaa81e162009-12-01 22:10:20 +00001692 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001693 // C++ [class.mfct.non-static]p3:
1694 // When an id-expression that is not part of a class member access
1695 // syntax and not used to form a pointer to member is used in the
1696 // body of a non-static member function of class X, if name lookup
1697 // resolves the name in the id-expression to a non-static non-type
1698 // member of some class C, the id-expression is transformed into a
1699 // class member access expression using (*this) as the
1700 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001701 //
1702 // But we don't actually need to do this for '&' operands if R
1703 // resolved to a function or overloaded function set, because the
1704 // expression is ill-formed if it actually works out to be a
1705 // non-static member function:
1706 //
1707 // C++ [expr.ref]p4:
1708 // Otherwise, if E1.E2 refers to a non-static member function. . .
1709 // [t]he expression can be used only as the left-hand operand of a
1710 // member function call.
1711 //
1712 // There are other safeguards against such uses, but it's important
1713 // to get this right here so that we don't end up making a
1714 // spuriously dependent expression if we're inside a dependent
1715 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001716 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001717 bool MightBeImplicitMember;
1718 if (!isAddressOfOperand)
1719 MightBeImplicitMember = true;
1720 else if (!SS.isEmpty())
1721 MightBeImplicitMember = false;
1722 else if (R.isOverloadedResult())
1723 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001724 else if (R.isUnresolvableResult())
1725 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001726 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001727 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1728 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001729
1730 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001731 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001732 }
1733
John McCallf7a1a742009-11-24 19:00:30 +00001734 if (TemplateArgs)
1735 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001736
John McCallf7a1a742009-11-24 19:00:30 +00001737 return BuildDeclarationNameExpr(SS, R, ADL);
1738}
1739
John McCall3b4294e2009-12-16 12:17:52 +00001740/// Builds an expression which might be an implicit member expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001741ExprResult
John McCall3b4294e2009-12-16 12:17:52 +00001742Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1743 LookupResult &R,
1744 const TemplateArgumentListInfo *TemplateArgs) {
1745 switch (ClassifyImplicitMemberAccess(*this, R)) {
1746 case IMA_Instance:
1747 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1748
John McCall3b4294e2009-12-16 12:17:52 +00001749 case IMA_Mixed:
1750 case IMA_Mixed_Unrelated:
1751 case IMA_Unresolved:
1752 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1753
1754 case IMA_Static:
1755 case IMA_Mixed_StaticContext:
1756 case IMA_Unresolved_StaticContext:
1757 if (TemplateArgs)
1758 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1759 return BuildDeclarationNameExpr(SS, R, false);
1760
1761 case IMA_Error_StaticContext:
1762 case IMA_Error_Unrelated:
John McCall5808ce42011-02-03 08:15:49 +00001763 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1764 R.getLookupNameInfo());
John McCall3b4294e2009-12-16 12:17:52 +00001765 return ExprError();
1766 }
1767
1768 llvm_unreachable("unexpected instance member access kind");
1769 return ExprError();
1770}
1771
John McCall129e2df2009-11-30 22:42:35 +00001772/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1773/// declaration name, generally during template instantiation.
1774/// There's a large number of things which don't need to be done along
1775/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001776ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001777Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001778 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001779 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001780 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001781 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001782
John McCall77bb1aa2010-05-01 00:40:08 +00001783 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001784 return ExprError();
1785
Abramo Bagnara25777432010-08-11 22:01:17 +00001786 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001787 LookupQualifiedName(R, DC);
1788
1789 if (R.isAmbiguous())
1790 return ExprError();
1791
1792 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001793 Diag(NameInfo.getLoc(), diag::err_no_member)
1794 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001795 return ExprError();
1796 }
1797
1798 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1799}
1800
1801/// LookupInObjCMethod - The parser has read a name in, and Sema has
1802/// detected that we're currently inside an ObjC method. Perform some
1803/// additional lookup.
1804///
1805/// Ideally, most of this would be done by lookup, but there's
1806/// actually quite a lot of extra work involved.
1807///
1808/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001809ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001810Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001811 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001812 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001813 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001814
John McCallf7a1a742009-11-24 19:00:30 +00001815 // There are two cases to handle here. 1) scoped lookup could have failed,
1816 // in which case we should look for an ivar. 2) scoped lookup could have
1817 // found a decl, but that decl is outside the current instance method (i.e.
1818 // a global variable). In these two cases, we do a lookup for an ivar with
1819 // this name, if the lookup sucedes, we replace it our current decl.
1820
1821 // If we're in a class method, we don't normally want to look for
1822 // ivars. But if we don't find anything else, and there's an
1823 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001824 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001825
1826 bool LookForIvars;
1827 if (Lookup.empty())
1828 LookForIvars = true;
1829 else if (IsClassMethod)
1830 LookForIvars = false;
1831 else
1832 LookForIvars = (Lookup.isSingleResult() &&
1833 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001834 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001835 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001836 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001837 ObjCInterfaceDecl *ClassDeclared;
1838 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1839 // Diagnose using an ivar in a class method.
1840 if (IsClassMethod)
1841 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1842 << IV->getDeclName());
1843
1844 // If we're referencing an invalid decl, just return this as a silent
1845 // error node. The error diagnostic was already emitted on the decl.
1846 if (IV->isInvalidDecl())
1847 return ExprError();
1848
1849 // Check if referencing a field with __attribute__((deprecated)).
1850 if (DiagnoseUseOfDecl(IV, Loc))
1851 return ExprError();
1852
1853 // Diagnose the use of an ivar outside of the declaring class.
1854 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1855 ClassDeclared != IFace)
1856 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1857
1858 // FIXME: This should use a new expr for a direct reference, don't
1859 // turn this into Self->ivar, just return a BareIVarExpr or something.
1860 IdentifierInfo &II = Context.Idents.get("self");
1861 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001862 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00001863 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001864 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001865 SelfName, false, false);
1866 if (SelfExpr.isInvalid())
1867 return ExprError();
1868
John McCall409fa9a2010-12-06 20:48:59 +00001869 Expr *SelfE = SelfExpr.take();
1870 DefaultLvalueConversion(SelfE);
1871
John McCallf7a1a742009-11-24 19:00:30 +00001872 MarkDeclarationReferenced(Loc, IV);
1873 return Owned(new (Context)
1874 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall409fa9a2010-12-06 20:48:59 +00001875 SelfE, true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001876 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001877 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001878 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001879 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001880 ObjCInterfaceDecl *ClassDeclared;
1881 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1882 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1883 IFace == ClassDeclared)
1884 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1885 }
1886 }
1887
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001888 if (Lookup.empty() && II && AllowBuiltinCreation) {
1889 // FIXME. Consolidate this with similar code in LookupName.
1890 if (unsigned BuiltinID = II->getBuiltinID()) {
1891 if (!(getLangOptions().CPlusPlus &&
1892 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1893 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1894 S, Lookup.isForRedeclaration(),
1895 Lookup.getNameLoc());
1896 if (D) Lookup.addDecl(D);
1897 }
1898 }
1899 }
John McCallf7a1a742009-11-24 19:00:30 +00001900 // Sentinel value saying that we didn't do anything special.
1901 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001902}
John McCallba135432009-11-21 08:51:07 +00001903
John McCall6bb80172010-03-30 21:47:33 +00001904/// \brief Cast a base object to a member's actual type.
1905///
1906/// Logically this happens in three phases:
1907///
1908/// * First we cast from the base type to the naming class.
1909/// The naming class is the class into which we were looking
1910/// when we found the member; it's the qualifier type if a
1911/// qualifier was provided, and otherwise it's the base type.
1912///
1913/// * Next we cast from the naming class to the declaring class.
1914/// If the member we found was brought into a class's scope by
1915/// a using declaration, this is that class; otherwise it's
1916/// the class declaring the member.
1917///
1918/// * Finally we cast from the declaring class to the "true"
1919/// declaring class of the member. This conversion does not
1920/// obey access control.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001921bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00001922Sema::PerformObjectMemberConversion(Expr *&From,
1923 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001924 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001925 NamedDecl *Member) {
1926 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1927 if (!RD)
1928 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001929
Douglas Gregor5fccd362010-03-03 23:55:11 +00001930 QualType DestRecordType;
1931 QualType DestType;
1932 QualType FromRecordType;
1933 QualType FromType = From->getType();
1934 bool PointerConversions = false;
1935 if (isa<FieldDecl>(Member)) {
1936 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001937
Douglas Gregor5fccd362010-03-03 23:55:11 +00001938 if (FromType->getAs<PointerType>()) {
1939 DestType = Context.getPointerType(DestRecordType);
1940 FromRecordType = FromType->getPointeeType();
1941 PointerConversions = true;
1942 } else {
1943 DestType = DestRecordType;
1944 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001945 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001946 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1947 if (Method->isStatic())
1948 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001949
Douglas Gregor5fccd362010-03-03 23:55:11 +00001950 DestType = Method->getThisType(Context);
1951 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001952
Douglas Gregor5fccd362010-03-03 23:55:11 +00001953 if (FromType->getAs<PointerType>()) {
1954 FromRecordType = FromType->getPointeeType();
1955 PointerConversions = true;
1956 } else {
1957 FromRecordType = FromType;
1958 DestType = DestRecordType;
1959 }
1960 } else {
1961 // No conversion necessary.
1962 return false;
1963 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001964
Douglas Gregor5fccd362010-03-03 23:55:11 +00001965 if (DestType->isDependentType() || FromType->isDependentType())
1966 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001967
Douglas Gregor5fccd362010-03-03 23:55:11 +00001968 // If the unqualified types are the same, no conversion is necessary.
1969 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1970 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001971
John McCall6bb80172010-03-30 21:47:33 +00001972 SourceRange FromRange = From->getSourceRange();
1973 SourceLocation FromLoc = FromRange.getBegin();
1974
John McCall5baba9d2010-08-25 10:28:54 +00001975 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00001976
Douglas Gregor5fccd362010-03-03 23:55:11 +00001977 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001978 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00001979 // class name.
1980 //
1981 // If the member was a qualified name and the qualified referred to a
1982 // specific base subobject type, we'll cast to that intermediate type
1983 // first and then to the object in which the member is declared. That allows
1984 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1985 //
1986 // class Base { public: int x; };
1987 // class Derived1 : public Base { };
1988 // class Derived2 : public Base { };
1989 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1990 //
1991 // void VeryDerived::f() {
1992 // x = 17; // error: ambiguous base subobjects
1993 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1994 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001995 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00001996 QualType QType = QualType(Qualifier->getAsType(), 0);
1997 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1998 assert(QType->isRecordType() && "lookup done with non-record type");
1999
2000 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2001
2002 // In C++98, the qualifier type doesn't actually have to be a base
2003 // type of the object type, in which case we just ignore it.
2004 // Otherwise build the appropriate casts.
2005 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002006 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002007 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002008 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00002009 return true;
2010
Douglas Gregor5fccd362010-03-03 23:55:11 +00002011 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002012 QType = Context.getPointerType(QType);
John McCall5baba9d2010-08-25 10:28:54 +00002013 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2014 VK, &BasePath);
John McCall6bb80172010-03-30 21:47:33 +00002015
2016 FromType = QType;
2017 FromRecordType = QRecordType;
2018
2019 // If the qualifier type was the same as the destination type,
2020 // we're done.
2021 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2022 return false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002023 }
2024 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002025
John McCall6bb80172010-03-30 21:47:33 +00002026 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002027
John McCall6bb80172010-03-30 21:47:33 +00002028 // If we actually found the member through a using declaration, cast
2029 // down to the using declaration's type.
2030 //
2031 // Pointer equality is fine here because only one declaration of a
2032 // class ever has member declarations.
2033 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2034 assert(isa<UsingShadowDecl>(FoundDecl));
2035 QualType URecordType = Context.getTypeDeclType(
2036 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2037
2038 // We only need to do this if the naming-class to declaring-class
2039 // conversion is non-trivial.
2040 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2041 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002042 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002043 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002044 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00002045 return true;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002046
John McCall6bb80172010-03-30 21:47:33 +00002047 QualType UType = URecordType;
2048 if (PointerConversions)
2049 UType = Context.getPointerType(UType);
John McCall2de56d12010-08-25 11:45:40 +00002050 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00002051 VK, &BasePath);
John McCall6bb80172010-03-30 21:47:33 +00002052 FromType = UType;
2053 FromRecordType = URecordType;
2054 }
2055
2056 // We don't do access control for the conversion from the
2057 // declaring class to the true declaring class.
2058 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002059 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002060
John McCallf871d0c2010-08-07 06:22:56 +00002061 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002062 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2063 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002064 IgnoreAccess))
Douglas Gregor5fccd362010-03-03 23:55:11 +00002065 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002066
John McCall2de56d12010-08-25 11:45:40 +00002067 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00002068 VK, &BasePath);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00002069 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002070}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002071
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002072/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00002073static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00002074 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00002075 DeclAccessPair FoundDecl,
Abramo Bagnara25777432010-08-11 22:01:17 +00002076 const DeclarationNameInfo &MemberNameInfo,
2077 QualType Ty,
John McCallf89e55a2010-11-18 06:31:45 +00002078 ExprValueKind VK, ExprObjectKind OK,
John McCallf7a1a742009-11-24 19:00:30 +00002079 const TemplateArgumentListInfo *TemplateArgs = 0) {
2080 NestedNameSpecifier *Qualifier = 0;
2081 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00002082 if (SS.isSet()) {
2083 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
2084 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002085 }
Mike Stump1eb44332009-09-09 15:08:12 +00002086
John McCallf7a1a742009-11-24 19:00:30 +00002087 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00002088 Member, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002089 TemplateArgs, Ty, VK, OK);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002090}
2091
John McCalldfa1edb2010-11-23 20:48:44 +00002092static ExprResult
2093BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2094 const CXXScopeSpec &SS, FieldDecl *Field,
2095 DeclAccessPair FoundDecl,
2096 const DeclarationNameInfo &MemberNameInfo) {
2097 // x.a is an l-value if 'a' has a reference type. Otherwise:
2098 // x.a is an l-value/x-value/pr-value if the base is (and note
2099 // that *x is always an l-value), except that if the base isn't
2100 // an ordinary object then we must have an rvalue.
2101 ExprValueKind VK = VK_LValue;
2102 ExprObjectKind OK = OK_Ordinary;
2103 if (!IsArrow) {
2104 if (BaseExpr->getObjectKind() == OK_Ordinary)
2105 VK = BaseExpr->getValueKind();
2106 else
2107 VK = VK_RValue;
2108 }
2109 if (VK != VK_RValue && Field->isBitField())
2110 OK = OK_BitField;
2111
2112 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2113 QualType MemberType = Field->getType();
2114 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2115 MemberType = Ref->getPointeeType();
2116 VK = VK_LValue;
2117 } else {
2118 QualType BaseType = BaseExpr->getType();
2119 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2120
2121 Qualifiers BaseQuals = BaseType.getQualifiers();
2122
2123 // GC attributes are never picked up by members.
2124 BaseQuals.removeObjCGCAttr();
2125
2126 // CVR attributes from the base are picked up by members,
2127 // except that 'mutable' members don't pick up 'const'.
2128 if (Field->isMutable()) BaseQuals.removeConst();
2129
2130 Qualifiers MemberQuals
2131 = S.Context.getCanonicalType(MemberType).getQualifiers();
2132
2133 // TR 18037 does not allow fields to be declared with address spaces.
2134 assert(!MemberQuals.hasAddressSpace());
2135
2136 Qualifiers Combined = BaseQuals + MemberQuals;
2137 if (Combined != MemberQuals)
2138 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2139 }
2140
2141 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2142 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2143 FoundDecl, Field))
2144 return ExprError();
2145 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2146 Field, FoundDecl, MemberNameInfo,
2147 MemberType, VK, OK));
2148}
2149
John McCallaa81e162009-12-01 22:10:20 +00002150/// Builds an implicit member access expression. The current context
2151/// is known to be an instance method, and the given unqualified lookup
2152/// set is known to contain only instance members, at least one of which
2153/// is from an appropriate type.
John McCall60d7b3a2010-08-24 06:29:42 +00002154ExprResult
John McCallaa81e162009-12-01 22:10:20 +00002155Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2156 LookupResult &R,
2157 const TemplateArgumentListInfo *TemplateArgs,
2158 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00002159 assert(!R.empty() && !R.isAmbiguous());
2160
John McCall5808ce42011-02-03 08:15:49 +00002161 SourceLocation loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00002162
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002163 // We may have found a field within an anonymous union or struct
2164 // (C++ [class.union]).
John McCallf7a1a742009-11-24 19:00:30 +00002165 // FIXME: template-ids inside anonymous structs?
Francois Pichet87c2e122010-11-21 06:08:52 +00002166 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCall5808ce42011-02-03 08:15:49 +00002167 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet87c2e122010-11-21 06:08:52 +00002168
John McCall5808ce42011-02-03 08:15:49 +00002169 // If this is known to be an instance access, go ahead and build an
2170 // implicit 'this' expression now.
John McCallaa81e162009-12-01 22:10:20 +00002171 // 'this' expression now.
John McCall5808ce42011-02-03 08:15:49 +00002172 CXXMethodDecl *method = tryCaptureCXXThis();
2173 assert(method && "didn't correctly pre-flight capture of 'this'");
2174
2175 QualType thisType = method->getThisType(Context);
2176 Expr *baseExpr = 0; // null signifies implicit access
John McCallaa81e162009-12-01 22:10:20 +00002177 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00002178 SourceLocation Loc = R.getNameLoc();
2179 if (SS.getRange().isValid())
2180 Loc = SS.getRange().getBegin();
John McCall5808ce42011-02-03 08:15:49 +00002181 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00002182 }
2183
John McCall5808ce42011-02-03 08:15:49 +00002184 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCallaa81e162009-12-01 22:10:20 +00002185 /*OpLoc*/ SourceLocation(),
2186 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00002187 SS,
2188 /*FirstQualifierInScope*/ 0,
2189 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00002190}
2191
John McCallf7a1a742009-11-24 19:00:30 +00002192bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002193 const LookupResult &R,
2194 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002195 // Only when used directly as the postfix-expression of a call.
2196 if (!HasTrailingLParen)
2197 return false;
2198
2199 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002200 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002201 return false;
2202
2203 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002204 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002205 return false;
2206
2207 // Turn off ADL when we find certain kinds of declarations during
2208 // normal lookup:
2209 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2210 NamedDecl *D = *I;
2211
2212 // C++0x [basic.lookup.argdep]p3:
2213 // -- a declaration of a class member
2214 // Since using decls preserve this property, we check this on the
2215 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002216 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002217 return false;
2218
2219 // C++0x [basic.lookup.argdep]p3:
2220 // -- a block-scope function declaration that is not a
2221 // using-declaration
2222 // NOTE: we also trigger this for function templates (in fact, we
2223 // don't check the decl type at all, since all other decl types
2224 // turn off ADL anyway).
2225 if (isa<UsingShadowDecl>(D))
2226 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2227 else if (D->getDeclContext()->isFunctionOrMethod())
2228 return false;
2229
2230 // C++0x [basic.lookup.argdep]p3:
2231 // -- a declaration that is neither a function or a function
2232 // template
2233 // And also for builtin functions.
2234 if (isa<FunctionDecl>(D)) {
2235 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2236
2237 // But also builtin functions.
2238 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2239 return false;
2240 } else if (!isa<FunctionTemplateDecl>(D))
2241 return false;
2242 }
2243
2244 return true;
2245}
2246
2247
John McCallba135432009-11-21 08:51:07 +00002248/// Diagnoses obvious problems with the use of the given declaration
2249/// as an expression. This is only actually called for lookups that
2250/// were not overloaded, and it doesn't promise that the declaration
2251/// will in fact be used.
2252static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2253 if (isa<TypedefDecl>(D)) {
2254 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2255 return true;
2256 }
2257
2258 if (isa<ObjCInterfaceDecl>(D)) {
2259 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2260 return true;
2261 }
2262
2263 if (isa<NamespaceDecl>(D)) {
2264 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2265 return true;
2266 }
2267
2268 return false;
2269}
2270
John McCall60d7b3a2010-08-24 06:29:42 +00002271ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002272Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002273 LookupResult &R,
2274 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002275 // If this is a single, fully-resolved result and we don't need ADL,
2276 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002277 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002278 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2279 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002280
2281 // We only need to check the declaration if there's exactly one
2282 // result, because in the overloaded case the results can only be
2283 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002284 if (R.isSingleResult() &&
2285 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002286 return ExprError();
2287
John McCallc373d482010-01-27 01:50:18 +00002288 // Otherwise, just build an unresolved lookup expression. Suppress
2289 // any lookup-related diagnostics; we'll hash these out later, when
2290 // we've picked a target.
2291 R.suppressDiagnostics();
2292
John McCallba135432009-11-21 08:51:07 +00002293 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002294 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00002295 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002296 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002297 NeedsADL, R.isOverloadedResult(),
2298 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002299
2300 return Owned(ULE);
2301}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002302
John McCallba135432009-11-21 08:51:07 +00002303/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002304ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002305Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002306 const DeclarationNameInfo &NameInfo,
2307 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002308 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002309 assert(!isa<FunctionTemplateDecl>(D) &&
2310 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002311
Abramo Bagnara25777432010-08-11 22:01:17 +00002312 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002313 if (CheckDeclInExpr(*this, Loc, D))
2314 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002315
Douglas Gregor9af2f522009-12-01 16:58:18 +00002316 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2317 // Specifically diagnose references to class templates that are missing
2318 // a template argument list.
2319 Diag(Loc, diag::err_template_decl_ref)
2320 << Template << SS.getRange();
2321 Diag(Template->getLocation(), diag::note_template_decl_here);
2322 return ExprError();
2323 }
2324
2325 // Make sure that we're referring to a value.
2326 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2327 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002328 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002329 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002330 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002331 return ExprError();
2332 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002333
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002334 // Check whether this declaration can be used. Note that we suppress
2335 // this check when we're going to perform argument-dependent lookup
2336 // on this function name, because this might not be the function
2337 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002338 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002339 return ExprError();
2340
Steve Naroffdd972f22008-09-05 22:11:13 +00002341 // Only create DeclRefExpr's for valid Decl's.
2342 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002343 return ExprError();
2344
John McCall5808ce42011-02-03 08:15:49 +00002345 // Handle members of anonymous structs and unions. If we got here,
2346 // and the reference is to a class member indirect field, then this
2347 // must be the subject of a pointer-to-member expression.
2348 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2349 if (!indirectField->isCXXClassMember())
2350 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2351 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002352
Chris Lattner639e2d32008-10-20 05:16:36 +00002353 // If the identifier reference is inside a block, and it refers to a value
2354 // that is outside the block, create a BlockDeclRefExpr instead of a
2355 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2356 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002357 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002358 // We do not do this for things like enum constants, global variables, etc,
2359 // as they do not get snapshotted.
2360 //
John McCall6b5a61b2011-02-07 10:33:21 +00002361 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002362 case CR_Error:
2363 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002364
John McCall469a1eb2011-02-02 13:00:07 +00002365 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002366 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2367 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2368
2369 case CR_CaptureByRef:
2370 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2371 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002372
2373 case CR_NoCapture: {
2374 // If this reference is not in a block or if the referenced
2375 // variable is within the block, create a normal DeclRefExpr.
2376
2377 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002378 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002379
2380 switch (D->getKind()) {
2381 // Ignore all the non-ValueDecl kinds.
2382#define ABSTRACT_DECL(kind)
2383#define VALUE(type, base)
2384#define DECL(type, base) \
2385 case Decl::type:
2386#include "clang/AST/DeclNodes.inc"
2387 llvm_unreachable("invalid value decl kind");
2388 return ExprError();
2389
2390 // These shouldn't make it here.
2391 case Decl::ObjCAtDefsField:
2392 case Decl::ObjCIvar:
2393 llvm_unreachable("forming non-member reference to ivar?");
2394 return ExprError();
2395
2396 // Enum constants are always r-values and never references.
2397 // Unresolved using declarations are dependent.
2398 case Decl::EnumConstant:
2399 case Decl::UnresolvedUsingValue:
2400 valueKind = VK_RValue;
2401 break;
2402
2403 // Fields and indirect fields that got here must be for
2404 // pointer-to-member expressions; we just call them l-values for
2405 // internal consistency, because this subexpression doesn't really
2406 // exist in the high-level semantics.
2407 case Decl::Field:
2408 case Decl::IndirectField:
2409 assert(getLangOptions().CPlusPlus &&
2410 "building reference to field in C?");
2411
2412 // These can't have reference type in well-formed programs, but
2413 // for internal consistency we do this anyway.
2414 type = type.getNonReferenceType();
2415 valueKind = VK_LValue;
2416 break;
2417
2418 // Non-type template parameters are either l-values or r-values
2419 // depending on the type.
2420 case Decl::NonTypeTemplateParm: {
2421 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2422 type = reftype->getPointeeType();
2423 valueKind = VK_LValue; // even if the parameter is an r-value reference
2424 break;
2425 }
2426
2427 // For non-references, we need to strip qualifiers just in case
2428 // the template parameter was declared as 'const int' or whatever.
2429 valueKind = VK_RValue;
2430 type = type.getUnqualifiedType();
2431 break;
2432 }
2433
2434 case Decl::Var:
2435 // In C, "extern void blah;" is valid and is an r-value.
2436 if (!getLangOptions().CPlusPlus &&
2437 !type.hasQualifiers() &&
2438 type->isVoidType()) {
2439 valueKind = VK_RValue;
2440 break;
2441 }
2442 // fallthrough
2443
2444 case Decl::ImplicitParam:
2445 case Decl::ParmVar:
2446 // These are always l-values.
2447 valueKind = VK_LValue;
2448 type = type.getNonReferenceType();
2449 break;
2450
2451 case Decl::Function: {
2452 // Functions are l-values in C++.
2453 if (getLangOptions().CPlusPlus) {
2454 valueKind = VK_LValue;
2455 break;
2456 }
2457
2458 // C99 DR 316 says that, if a function type comes from a
2459 // function definition (without a prototype), that type is only
2460 // used for checking compatibility. Therefore, when referencing
2461 // the function, we pretend that we don't have the full function
2462 // type.
2463 if (!cast<FunctionDecl>(VD)->hasPrototype())
2464 if (const FunctionProtoType *proto = type->getAs<FunctionProtoType>())
2465 type = Context.getFunctionNoProtoType(proto->getResultType(),
2466 proto->getExtInfo());
2467
2468 // Functions are r-values in C.
2469 valueKind = VK_RValue;
2470 break;
2471 }
2472
2473 case Decl::CXXMethod:
2474 // C++ methods are l-values if static, r-values if non-static.
2475 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2476 valueKind = VK_LValue;
2477 break;
2478 }
2479 // fallthrough
2480
2481 case Decl::CXXConversion:
2482 case Decl::CXXDestructor:
2483 case Decl::CXXConstructor:
2484 valueKind = VK_RValue;
2485 break;
2486 }
2487
2488 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2489 }
2490
John McCall469a1eb2011-02-02 13:00:07 +00002491 }
John McCallf89e55a2010-11-18 06:31:45 +00002492
John McCall6b5a61b2011-02-07 10:33:21 +00002493 llvm_unreachable("unknown capture result");
2494 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002495}
2496
John McCall60d7b3a2010-08-24 06:29:42 +00002497ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlcd965b92009-01-18 18:53:16 +00002498 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002499 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002500
Reid Spencer5f016e22007-07-11 17:01:13 +00002501 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002502 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002503 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2504 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2505 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002506 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002507
Chris Lattnerfa28b302008-01-12 08:14:25 +00002508 // Pre-defined identifiers are of type char[x], where x is the length of the
2509 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002510
Anders Carlsson3a082d82009-09-08 18:24:21 +00002511 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002512 if (!currentDecl && getCurBlock())
2513 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002514 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002515 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002516 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002517 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002518
Anders Carlsson773f3972009-09-11 01:22:35 +00002519 QualType ResTy;
2520 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2521 ResTy = Context.DependentTy;
2522 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002523 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002524
Anders Carlsson773f3972009-09-11 01:22:35 +00002525 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002526 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002527 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2528 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002529 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002530}
2531
John McCall60d7b3a2010-08-24 06:29:42 +00002532ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002533 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002534 bool Invalid = false;
2535 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2536 if (Invalid)
2537 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002538
Benjamin Kramerddeea562010-02-27 13:44:12 +00002539 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2540 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002541 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002542 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002543
Chris Lattnere8337df2009-12-30 21:19:39 +00002544 QualType Ty;
2545 if (!getLangOptions().CPlusPlus)
2546 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2547 else if (Literal.isWide())
2548 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002549 else if (Literal.isMultiChar())
2550 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002551 else
2552 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002553
Sebastian Redle91b3bc2009-01-20 22:23:13 +00002554 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2555 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00002556 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002557}
2558
John McCall60d7b3a2010-08-24 06:29:42 +00002559ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002560 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002561 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2562 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002563 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00002564 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002565 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002566 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002567 }
Ted Kremenek28396602009-01-13 23:19:12 +00002568
Reid Spencer5f016e22007-07-11 17:01:13 +00002569 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002570 // Add padding so that NumericLiteralParser can overread by one character.
2571 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002572 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002573
Reid Spencer5f016e22007-07-11 17:01:13 +00002574 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002575 bool Invalid = false;
2576 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2577 if (Invalid)
2578 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002579
Mike Stump1eb44332009-09-09 15:08:12 +00002580 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002581 Tok.getLocation(), PP);
2582 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002583 return ExprError();
2584
Chris Lattner5d661452007-08-26 03:42:43 +00002585 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002586
Chris Lattner5d661452007-08-26 03:42:43 +00002587 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002588 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002589 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002590 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002591 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002592 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002593 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002594 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002595
2596 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2597
John McCall94c939d2009-12-24 09:08:04 +00002598 using llvm::APFloat;
2599 APFloat Val(Format);
2600
2601 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002602
2603 // Overflow is always an error, but underflow is only an error if
2604 // we underflowed to zero (APFloat reports denormals as underflow).
2605 if ((result & APFloat::opOverflow) ||
2606 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002607 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002608 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002609 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002610 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002611 APFloat::getLargest(Format).toString(buffer);
2612 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002613 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002614 APFloat::getSmallest(Format).toString(buffer);
2615 }
2616
2617 Diag(Tok.getLocation(), diagnostic)
2618 << Ty
2619 << llvm::StringRef(buffer.data(), buffer.size());
2620 }
2621
2622 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002623 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002624
Peter Collingbourne09821362010-12-04 01:50:56 +00002625 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2626 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2627
Chris Lattner5d661452007-08-26 03:42:43 +00002628 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002629 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002630 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002631 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002632
Neil Boothb9449512007-08-29 22:00:19 +00002633 // long long is a C99 feature.
2634 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002635 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002636 Diag(Tok.getLocation(), diag::ext_longlong);
2637
Reid Spencer5f016e22007-07-11 17:01:13 +00002638 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00002639 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002640
Reid Spencer5f016e22007-07-11 17:01:13 +00002641 if (Literal.GetIntegerValue(ResultVal)) {
2642 // If this value didn't fit into uintmax_t, warn and force to ull.
2643 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002644 Ty = Context.UnsignedLongLongTy;
2645 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002646 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002647 } else {
2648 // If this value fits into a ULL, try to figure out what else it fits into
2649 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002650
Reid Spencer5f016e22007-07-11 17:01:13 +00002651 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2652 // be an unsigned int.
2653 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2654
2655 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002656 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002657 if (!Literal.isLong && !Literal.isLongLong) {
2658 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002659 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002660
Reid Spencer5f016e22007-07-11 17:01:13 +00002661 // Does it fit in a unsigned int?
2662 if (ResultVal.isIntN(IntSize)) {
2663 // Does it fit in a signed int?
2664 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002665 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002666 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002667 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002668 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002669 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002670 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002671
Reid Spencer5f016e22007-07-11 17:01:13 +00002672 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002673 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002674 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002675
Reid Spencer5f016e22007-07-11 17:01:13 +00002676 // Does it fit in a unsigned long?
2677 if (ResultVal.isIntN(LongSize)) {
2678 // Does it fit in a signed long?
2679 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002680 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002681 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002682 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002683 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002684 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002685 }
2686
Reid Spencer5f016e22007-07-11 17:01:13 +00002687 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002688 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002689 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002690
Reid Spencer5f016e22007-07-11 17:01:13 +00002691 // Does it fit in a unsigned long long?
2692 if (ResultVal.isIntN(LongLongSize)) {
2693 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002694 // To be compatible with MSVC, hex integer literals ending with the
2695 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002696 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2697 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002698 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002700 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002701 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002702 }
2703 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002704
Reid Spencer5f016e22007-07-11 17:01:13 +00002705 // If we still couldn't decide a type, we probably have something that
2706 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002707 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002708 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002709 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002710 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002711 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002712
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002713 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002714 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002715 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002716 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002717 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002718
Chris Lattner5d661452007-08-26 03:42:43 +00002719 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2720 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002721 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002722 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002723
2724 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002725}
2726
John McCall60d7b3a2010-08-24 06:29:42 +00002727ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00002728 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002729 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002730 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002731}
2732
2733/// The UsualUnaryConversions() function is *not* called by this routine.
2734/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00002735bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00002736 SourceLocation OpLoc,
John McCall2a984ca2010-10-12 00:20:44 +00002737 SourceRange ExprRange,
Sebastian Redl05189992008-11-11 17:56:53 +00002738 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00002739 if (exprType->isDependentType())
2740 return false;
2741
Sebastian Redl5d484e82009-11-23 17:18:46 +00002742 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2743 // the result is the size of the referenced type."
2744 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2745 // result shall be the alignment of the referenced type."
2746 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2747 exprType = Ref->getPointeeType();
2748
Reid Spencer5f016e22007-07-11 17:01:13 +00002749 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00002750 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002751 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002752 if (isSizeof)
2753 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2754 return false;
2755 }
Mike Stump1eb44332009-09-09 15:08:12 +00002756
Chris Lattner1efaa952009-04-24 00:30:45 +00002757 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002758 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002759 Diag(OpLoc, diag::ext_sizeof_void_type)
2760 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00002761 return false;
2762 }
Mike Stump1eb44332009-09-09 15:08:12 +00002763
Chris Lattner1efaa952009-04-24 00:30:45 +00002764 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002765 PDiag(diag::err_sizeof_alignof_incomplete_type)
2766 << int(!isSizeof) << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002767 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002768
Chris Lattner1efaa952009-04-24 00:30:45 +00002769 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCallc12c5bb2010-05-15 11:32:37 +00002770 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002771 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00002772 << exprType << isSizeof << ExprRange;
2773 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00002774 }
Mike Stump1eb44332009-09-09 15:08:12 +00002775
Chris Lattner1efaa952009-04-24 00:30:45 +00002776 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002777}
2778
John McCall2a984ca2010-10-12 00:20:44 +00002779static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2780 SourceRange ExprRange) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002781 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002782
Mike Stump1eb44332009-09-09 15:08:12 +00002783 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002784 if (isa<DeclRefExpr>(E))
2785 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002786
2787 // Cannot know anything else if the expression is dependent.
2788 if (E->isTypeDependent())
2789 return false;
2790
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002791 if (E->getBitField()) {
John McCall2a984ca2010-10-12 00:20:44 +00002792 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002793 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002794 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002795
2796 // Alignment of a field access is always okay, so long as it isn't a
2797 // bit-field.
2798 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002799 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002800 return false;
2801
John McCall2a984ca2010-10-12 00:20:44 +00002802 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
Chris Lattner31e21e02009-01-24 20:17:12 +00002803}
2804
Douglas Gregorba498172009-03-13 21:01:28 +00002805/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002806ExprResult
John McCalla93c9342009-12-07 02:54:59 +00002807Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00002808 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002809 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002810 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002811 return ExprError();
2812
John McCalla93c9342009-12-07 02:54:59 +00002813 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002814
Douglas Gregorba498172009-03-13 21:01:28 +00002815 if (!T->isDependentType() &&
2816 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2817 return ExprError();
2818
2819 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00002820 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00002821 Context.getSizeType(), OpLoc,
2822 R.getEnd()));
2823}
2824
2825/// \brief Build a sizeof or alignof expression given an expression
2826/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002827ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00002828Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002829 bool isSizeOf, SourceRange R) {
2830 // Verify that the operand is valid.
2831 bool isInvalid = false;
2832 if (E->isTypeDependent()) {
2833 // Delay type-checking for type-dependent expressions.
2834 } else if (!isSizeOf) {
John McCall2a984ca2010-10-12 00:20:44 +00002835 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002836 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00002837 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2838 isInvalid = true;
John McCall2cd11fe2010-10-12 02:09:17 +00002839 } else if (E->getType()->isPlaceholderType()) {
2840 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2841 if (PE.isInvalid()) return ExprError();
2842 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
Douglas Gregorba498172009-03-13 21:01:28 +00002843 } else {
2844 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2845 }
2846
2847 if (isInvalid)
2848 return ExprError();
2849
2850 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2851 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2852 Context.getSizeType(), OpLoc,
2853 R.getEnd()));
2854}
2855
Sebastian Redl05189992008-11-11 17:56:53 +00002856/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2857/// the same for @c alignof and @c __alignof
2858/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00002859ExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00002860Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2861 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002862 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002863 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002864
Sebastian Redl05189992008-11-11 17:56:53 +00002865 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002866 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00002867 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
John McCalla93c9342009-12-07 02:54:59 +00002868 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002869 }
Sebastian Redl05189992008-11-11 17:56:53 +00002870
Douglas Gregorba498172009-03-13 21:01:28 +00002871 Expr *ArgEx = (Expr *)TyOrEx;
John McCall60d7b3a2010-08-24 06:29:42 +00002872 ExprResult Result
Douglas Gregorba498172009-03-13 21:01:28 +00002873 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2874
Douglas Gregorba498172009-03-13 21:01:28 +00002875 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002876}
2877
John McCall09431682010-11-18 19:01:18 +00002878static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2879 bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00002880 if (V->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00002881 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002882
John McCallf6a16482010-12-04 03:47:34 +00002883 // _Real and _Imag are only l-values for normal l-values.
2884 if (V->getObjectKind() != OK_Ordinary)
John McCall409fa9a2010-12-06 20:48:59 +00002885 S.DefaultLvalueConversion(V);
John McCallf6a16482010-12-04 03:47:34 +00002886
Chris Lattnercc26ed72007-08-26 05:39:26 +00002887 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00002888 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002889 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002890
Chris Lattnercc26ed72007-08-26 05:39:26 +00002891 // Otherwise they pass through real integer and floating point types here.
2892 if (V->getType()->isArithmeticType())
2893 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002894
John McCall2cd11fe2010-10-12 02:09:17 +00002895 // Test for placeholders.
John McCall09431682010-11-18 19:01:18 +00002896 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall2cd11fe2010-10-12 02:09:17 +00002897 if (PR.isInvalid()) return QualType();
2898 if (PR.take() != V) {
2899 V = PR.take();
John McCall09431682010-11-18 19:01:18 +00002900 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00002901 }
2902
Chris Lattnercc26ed72007-08-26 05:39:26 +00002903 // Reject anything else.
John McCall09431682010-11-18 19:01:18 +00002904 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002905 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002906 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002907}
2908
2909
Reid Spencer5f016e22007-07-11 17:01:13 +00002910
John McCall60d7b3a2010-08-24 06:29:42 +00002911ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00002912Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002913 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00002914 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00002915 switch (Kind) {
2916 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00002917 case tok::plusplus: Opc = UO_PostInc; break;
2918 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002919 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002920
John McCall9ae2f072010-08-23 23:25:46 +00002921 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002922}
2923
John McCall09431682010-11-18 19:01:18 +00002924/// Expressions of certain arbitrary types are forbidden by C from
2925/// having l-value type. These are:
2926/// - 'void', but not qualified void
2927/// - function types
2928///
2929/// The exact rule here is C99 6.3.2.1:
2930/// An lvalue is an expression with an object type or an incomplete
2931/// type other than void.
2932static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2933 return ((T->isVoidType() && !T.hasQualifiers()) ||
2934 T->isFunctionType());
2935}
2936
John McCall60d7b3a2010-08-24 06:29:42 +00002937ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002938Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2939 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00002940 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00002941 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00002942 if (Result.isInvalid()) return ExprError();
2943 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002944
John McCall9ae2f072010-08-23 23:25:46 +00002945 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00002946
Douglas Gregor337c6b92008-11-19 17:17:41 +00002947 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002948 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002949 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00002950 Context.DependentTy,
2951 VK_LValue, OK_Ordinary,
2952 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002953 }
2954
Mike Stump1eb44332009-09-09 15:08:12 +00002955 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002956 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00002957 LHSExp->getType()->isEnumeralType() ||
2958 RHSExp->getType()->isRecordType() ||
2959 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00002960 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00002961 }
2962
John McCall9ae2f072010-08-23 23:25:46 +00002963 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00002964}
2965
2966
John McCall60d7b3a2010-08-24 06:29:42 +00002967ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002968Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2969 Expr *Idx, SourceLocation RLoc) {
2970 Expr *LHSExp = Base;
2971 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00002972
Chris Lattner12d9ff62007-07-16 00:14:47 +00002973 // Perform default conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002974 if (!LHSExp->getType()->getAs<VectorType>())
2975 DefaultFunctionArrayLvalueConversion(LHSExp);
2976 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002977
Chris Lattner12d9ff62007-07-16 00:14:47 +00002978 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00002979 ExprValueKind VK = VK_LValue;
2980 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00002981
Reid Spencer5f016e22007-07-11 17:01:13 +00002982 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002983 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00002984 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00002985 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00002986 Expr *BaseExpr, *IndexExpr;
2987 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00002988 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2989 BaseExpr = LHSExp;
2990 IndexExpr = RHSExp;
2991 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002992 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00002993 BaseExpr = LHSExp;
2994 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002995 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002996 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00002997 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00002998 BaseExpr = RHSExp;
2999 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003000 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003001 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003002 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003003 BaseExpr = LHSExp;
3004 IndexExpr = RHSExp;
3005 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003006 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003007 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003008 // Handle the uncommon case of "123[Ptr]".
3009 BaseExpr = RHSExp;
3010 IndexExpr = LHSExp;
3011 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003012 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003013 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003014 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003015 VK = LHSExp->getValueKind();
3016 if (VK != VK_RValue)
3017 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003018
Chris Lattner12d9ff62007-07-16 00:14:47 +00003019 // FIXME: need to deal with const...
3020 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003021 } else if (LHSTy->isArrayType()) {
3022 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003023 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003024 // wasn't promoted because of the C90 rule that doesn't
3025 // allow promoting non-lvalue arrays. Warn, then
3026 // force the promotion here.
3027 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3028 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003029 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCall2de56d12010-08-25 11:45:40 +00003030 CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003031 LHSTy = LHSExp->getType();
3032
3033 BaseExpr = LHSExp;
3034 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003035 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003036 } else if (RHSTy->isArrayType()) {
3037 // Same as previous, except for 123[f().a] case
3038 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3039 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003040 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCall2de56d12010-08-25 11:45:40 +00003041 CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003042 RHSTy = RHSExp->getType();
3043
3044 BaseExpr = RHSExp;
3045 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003046 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003047 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003048 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3049 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003050 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003051 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003052 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003053 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3054 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003055
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003056 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003057 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3058 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003059 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3060
Douglas Gregore7450f52009-03-24 19:52:54 +00003061 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003062 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3063 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003064 // incomplete types are not object types.
3065 if (ResultType->isFunctionType()) {
3066 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3067 << ResultType << BaseExpr->getSourceRange();
3068 return ExprError();
3069 }
Mike Stump1eb44332009-09-09 15:08:12 +00003070
Abramo Bagnara46358452010-09-13 06:50:07 +00003071 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3072 // GNU extension: subscripting on pointer to void
3073 Diag(LLoc, diag::ext_gnu_void_ptr)
3074 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003075
3076 // C forbids expressions of unqualified void type from being l-values.
3077 // See IsCForbiddenLValueType.
3078 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003079 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003080 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003081 PDiag(diag::err_subscript_incomplete_type)
3082 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003083 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003084
Chris Lattner1efaa952009-04-24 00:30:45 +00003085 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003086 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003087 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3088 << ResultType << BaseExpr->getSourceRange();
3089 return ExprError();
3090 }
Mike Stump1eb44332009-09-09 15:08:12 +00003091
John McCall09431682010-11-18 19:01:18 +00003092 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3093 !IsCForbiddenLValueType(Context, ResultType));
3094
Mike Stumpeed9cac2009-02-19 03:04:26 +00003095 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003096 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003097}
3098
John McCall09431682010-11-18 19:01:18 +00003099/// Check an ext-vector component access expression.
3100///
3101/// VK should be set in advance to the value kind of the base
3102/// expression.
3103static QualType
3104CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3105 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003106 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00003107 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3108 // see FIXME there.
3109 //
3110 // FIXME: This logic can be greatly simplified by splitting it along
3111 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00003112 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00003113
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003114 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00003115 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003116
Mike Stumpeed9cac2009-02-19 03:04:26 +00003117 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00003118 // special names that indicate a subset of exactly half the elements are
3119 // to be selected.
3120 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003121
Nate Begeman353417a2009-01-18 01:47:54 +00003122 // This flag determines whether or not CompName has an 's' char prefix,
3123 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00003124 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00003125
John McCall09431682010-11-18 19:01:18 +00003126 bool HasRepeated = false;
3127 bool HasIndex[16] = {};
3128
3129 int Idx;
3130
Nate Begeman8a997642008-05-09 06:41:27 +00003131 // Check that we've found one of the special components, or that the component
3132 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003133 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00003134 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3135 HalvingSwizzle = true;
John McCall09431682010-11-18 19:01:18 +00003136 } else if (!HexSwizzle &&
3137 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3138 do {
3139 if (HasIndex[Idx]) HasRepeated = true;
3140 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003141 compStr++;
John McCall09431682010-11-18 19:01:18 +00003142 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3143 } else {
3144 if (HexSwizzle) compStr++;
3145 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3146 if (HasIndex[Idx]) HasRepeated = true;
3147 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003148 compStr++;
John McCall09431682010-11-18 19:01:18 +00003149 }
Chris Lattner88dca042007-08-02 22:33:49 +00003150 }
Nate Begeman353417a2009-01-18 01:47:54 +00003151
Mike Stumpeed9cac2009-02-19 03:04:26 +00003152 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003153 // We didn't get to the end of the string. This means the component names
3154 // didn't come from the same set *or* we encountered an illegal name.
John McCall09431682010-11-18 19:01:18 +00003155 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00003156 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003157 return QualType();
3158 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003159
Nate Begeman353417a2009-01-18 01:47:54 +00003160 // Ensure no component accessor exceeds the width of the vector type it
3161 // operates on.
3162 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00003163 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003164
3165 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003166 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00003167
3168 while (*compStr) {
3169 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall09431682010-11-18 19:01:18 +00003170 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begeman353417a2009-01-18 01:47:54 +00003171 << baseType << SourceRange(CompLoc);
3172 return QualType();
3173 }
3174 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003175 }
Nate Begeman8a997642008-05-09 06:41:27 +00003176
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003177 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003178 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003179 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00003180 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00003181 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00003182 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00003183 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00003184 if (HexSwizzle)
3185 CompSize--;
3186
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003187 if (CompSize == 1)
3188 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003189
John McCall09431682010-11-18 19:01:18 +00003190 if (HasRepeated) VK = VK_RValue;
3191
3192 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003193 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00003194 // diagostics look bad. We want extended vector types to appear built-in.
John McCall09431682010-11-18 19:01:18 +00003195 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3196 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3197 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00003198 }
3199 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003200}
3201
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003202static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003203 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003204 const Selector &Sel,
3205 ASTContext &Context) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003206 if (Member)
3207 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3208 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003209 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003210 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00003211
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003212 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3213 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003214 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3215 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003216 return D;
3217 }
3218 return 0;
3219}
3220
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003221static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3222 IdentifierInfo *Member,
3223 const Selector &Sel,
3224 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003225 // Check protocols on qualified interfaces.
3226 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003227 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003228 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003229 if (Member)
3230 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3231 GDecl = PD;
3232 break;
3233 }
3234 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003235 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003236 GDecl = OMD;
3237 break;
3238 }
3239 }
3240 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003241 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003242 E = QIdTy->qual_end(); I != E; ++I) {
3243 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003244 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3245 Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003246 if (GDecl)
3247 return GDecl;
3248 }
3249 }
3250 return GDecl;
3251}
Chris Lattner76a642f2009-02-15 22:43:40 +00003252
John McCall60d7b3a2010-08-24 06:29:42 +00003253ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003254Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCallaa81e162009-12-01 22:10:20 +00003255 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003256 const CXXScopeSpec &SS,
3257 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003258 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003259 const TemplateArgumentListInfo *TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00003260 // Even in dependent contexts, try to diagnose base expressions with
3261 // obviously wrong types, e.g.:
3262 //
3263 // T* t;
3264 // t.f;
3265 //
3266 // In Obj-C++, however, the above expression is valid, since it could be
3267 // accessing the 'f' property if T is an Obj-C interface. The extra check
3268 // allows this, while still reporting an error if T is a struct pointer.
3269 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00003270 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00003271 if (PT && (!getLangOptions().ObjC1 ||
3272 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00003273 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnara25777432010-08-11 22:01:17 +00003274 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00003275 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00003276 return ExprError();
3277 }
3278 }
3279
Abramo Bagnara25777432010-08-11 22:01:17 +00003280 assert(BaseType->isDependentType() ||
3281 NameInfo.getName().isDependentName() ||
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003282 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00003283
3284 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3285 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00003286 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003287 IsArrow, OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003288 SS.getScopeRep(),
John McCall129e2df2009-11-30 22:42:35 +00003289 SS.getRange(),
3290 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003291 NameInfo, TemplateArgs));
John McCall129e2df2009-11-30 22:42:35 +00003292}
3293
3294/// We know that the given qualified member reference points only to
3295/// declarations which do not belong to the static type of the base
3296/// expression. Diagnose the problem.
3297static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3298 Expr *BaseExpr,
3299 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003300 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00003301 NamedDecl *rep,
3302 const DeclarationNameInfo &nameInfo) {
John McCall2f841ba2009-12-02 03:53:29 +00003303 // If this is an implicit member access, use a different set of
3304 // diagnostics.
3305 if (!BaseExpr)
John McCall5808ce42011-02-03 08:15:49 +00003306 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003307
John McCall5808ce42011-02-03 08:15:49 +00003308 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3309 << SS.getRange() << rep << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00003310}
3311
3312// Check whether the declarations we found through a nested-name
3313// specifier in a member expression are actually members of the base
3314// type. The restriction here is:
3315//
3316// C++ [expr.ref]p2:
3317// ... In these cases, the id-expression shall name a
3318// member of the class or of one of its base classes.
3319//
3320// So it's perfectly legitimate for the nested-name specifier to name
3321// an unrelated class, and for us to find an overload set including
3322// decls from classes which are not superclasses, as long as the decl
3323// we actually pick through overload resolution is from a superclass.
3324bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3325 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003326 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003327 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00003328 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3329 if (!BaseRT) {
3330 // We can't check this yet because the base type is still
3331 // dependent.
3332 assert(BaseType->isDependentType());
3333 return false;
3334 }
3335 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00003336
3337 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00003338 // If this is an implicit member reference and we find a
3339 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00003340 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00003341 return false;
John McCall129e2df2009-11-30 22:42:35 +00003342
John McCallaa81e162009-12-01 22:10:20 +00003343 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman02463762010-07-27 20:51:02 +00003344 DeclContext *DC = (*I)->getDeclContext();
3345 while (DC->isTransparentContext())
3346 DC = DC->getParent();
John McCallaa81e162009-12-01 22:10:20 +00003347
Douglas Gregor9d4bb942010-07-28 22:27:52 +00003348 if (!DC->isRecord())
3349 continue;
3350
John McCallaa81e162009-12-01 22:10:20 +00003351 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman02463762010-07-27 20:51:02 +00003352 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCallaa81e162009-12-01 22:10:20 +00003353
3354 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3355 return false;
3356 }
3357
John McCall5808ce42011-02-03 08:15:49 +00003358 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3359 R.getRepresentativeDecl(),
3360 R.getLookupNameInfo());
John McCallaa81e162009-12-01 22:10:20 +00003361 return true;
3362}
3363
3364static bool
3365LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3366 SourceRange BaseRange, const RecordType *RTy,
John McCallad00b772010-06-16 08:42:20 +00003367 SourceLocation OpLoc, CXXScopeSpec &SS,
3368 bool HasTemplateArgs) {
John McCallaa81e162009-12-01 22:10:20 +00003369 RecordDecl *RDecl = RTy->getDecl();
3370 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003371 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00003372 << BaseRange))
3373 return true;
3374
John McCallad00b772010-06-16 08:42:20 +00003375 if (HasTemplateArgs) {
3376 // LookupTemplateName doesn't expect these both to exist simultaneously.
3377 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3378
3379 bool MOUS;
3380 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3381 return false;
3382 }
3383
John McCallaa81e162009-12-01 22:10:20 +00003384 DeclContext *DC = RDecl;
3385 if (SS.isSet()) {
3386 // If the member name was a qualified-id, look into the
3387 // nested-name-specifier.
3388 DC = SemaRef.computeDeclContext(SS, false);
3389
John McCall77bb1aa2010-05-01 00:40:08 +00003390 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCall2f841ba2009-12-02 03:53:29 +00003391 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3392 << SS.getRange() << DC;
3393 return true;
3394 }
3395
John McCallaa81e162009-12-01 22:10:20 +00003396 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003397
John McCallaa81e162009-12-01 22:10:20 +00003398 if (!isa<TypeDecl>(DC)) {
3399 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3400 << DC << SS.getRange();
3401 return true;
John McCall129e2df2009-11-30 22:42:35 +00003402 }
3403 }
3404
John McCallaa81e162009-12-01 22:10:20 +00003405 // The record definition is complete, now look up the member.
3406 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00003407
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003408 if (!R.empty())
3409 return false;
3410
3411 // We didn't find anything with the given name, so try to correct
3412 // for typos.
3413 DeclarationName Name = R.getLookupName();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003414 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00003415 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003416 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3417 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3418 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003419 << FixItHint::CreateReplacement(R.getNameLoc(),
3420 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003421 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3422 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3423 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003424 return false;
3425 } else {
3426 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003427 R.setLookupName(Name);
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003428 }
3429
John McCall129e2df2009-11-30 22:42:35 +00003430 return false;
3431}
3432
John McCall60d7b3a2010-08-24 06:29:42 +00003433ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003434Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003435 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003436 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003437 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003438 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003439 const TemplateArgumentListInfo *TemplateArgs) {
John McCall2f841ba2009-12-02 03:53:29 +00003440 if (BaseType->isDependentType() ||
3441 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall9ae2f072010-08-23 23:25:46 +00003442 return ActOnDependentMemberExpr(Base, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003443 IsArrow, OpLoc,
3444 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003445 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003446
Abramo Bagnara25777432010-08-11 22:01:17 +00003447 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00003448
John McCallaa81e162009-12-01 22:10:20 +00003449 // Implicit member accesses.
3450 if (!Base) {
3451 QualType RecordTy = BaseType;
3452 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3453 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3454 RecordTy->getAs<RecordType>(),
John McCallad00b772010-06-16 08:42:20 +00003455 OpLoc, SS, TemplateArgs != 0))
John McCallaa81e162009-12-01 22:10:20 +00003456 return ExprError();
3457
3458 // Explicit member accesses.
3459 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00003460 ExprResult Result =
John McCallaa81e162009-12-01 22:10:20 +00003461 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCalld226f652010-08-21 09:40:31 +00003462 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCallaa81e162009-12-01 22:10:20 +00003463
3464 if (Result.isInvalid()) {
3465 Owned(Base);
3466 return ExprError();
3467 }
3468
3469 if (Result.get())
3470 return move(Result);
Sebastian Redlf3e63372010-05-07 09:25:11 +00003471
3472 // LookupMemberExpr can modify Base, and thus change BaseType
3473 BaseType = Base->getType();
John McCall129e2df2009-11-30 22:42:35 +00003474 }
3475
John McCall9ae2f072010-08-23 23:25:46 +00003476 return BuildMemberReferenceExpr(Base, BaseType,
John McCallc2233c52010-01-15 08:34:02 +00003477 OpLoc, IsArrow, SS, FirstQualifierInScope,
3478 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003479}
3480
John McCall60d7b3a2010-08-24 06:29:42 +00003481ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003482Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCallaa81e162009-12-01 22:10:20 +00003483 SourceLocation OpLoc, bool IsArrow,
3484 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00003485 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00003486 LookupResult &R,
Douglas Gregor06a9f362010-05-01 20:49:11 +00003487 const TemplateArgumentListInfo *TemplateArgs,
3488 bool SuppressQualifierCheck) {
John McCallaa81e162009-12-01 22:10:20 +00003489 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00003490 if (IsArrow) {
3491 assert(BaseType->isPointerType());
3492 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3493 }
John McCall161755a2010-04-06 21:38:20 +00003494 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00003495
John McCall9ae2f072010-08-23 23:25:46 +00003496 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara25777432010-08-11 22:01:17 +00003497 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3498 DeclarationName MemberName = MemberNameInfo.getName();
3499 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall129e2df2009-11-30 22:42:35 +00003500
3501 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00003502 return ExprError();
3503
John McCall129e2df2009-11-30 22:42:35 +00003504 if (R.empty()) {
3505 // Rederive where we looked up.
3506 DeclContext *DC = (SS.isSet()
3507 ? computeDeclContext(SS, false)
3508 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00003509
John McCall129e2df2009-11-30 22:42:35 +00003510 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00003511 << MemberName << DC
3512 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00003513 return ExprError();
3514 }
3515
John McCallc2233c52010-01-15 08:34:02 +00003516 // Diagnose lookups that find only declarations from a non-base
3517 // type. This is possible for either qualified lookups (which may
3518 // have been qualified with an unrelated type) or implicit member
3519 // expressions (which were found with unqualified lookup and thus
3520 // may have come from an enclosing scope). Note that it's okay for
3521 // lookup to find declarations from a non-base type as long as those
3522 // aren't the ones picked by overload resolution.
3523 if ((SS.isSet() || !BaseExpr ||
3524 (isa<CXXThisExpr>(BaseExpr) &&
3525 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00003526 !SuppressQualifierCheck &&
John McCallc2233c52010-01-15 08:34:02 +00003527 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00003528 return ExprError();
3529
3530 // Construct an unresolved result if we in fact got an unresolved
3531 // result.
3532 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallc373d482010-01-27 01:50:18 +00003533 // Suppress any lookup-related diagnostics; we'll do these when we
3534 // pick a member.
3535 R.suppressDiagnostics();
3536
John McCall129e2df2009-11-30 22:42:35 +00003537 UnresolvedMemberExpr *MemExpr
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003538 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00003539 BaseExpr, BaseExprType,
3540 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003541 Qualifier, SS.getRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00003542 MemberNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00003543 TemplateArgs, R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00003544
3545 return Owned(MemExpr);
3546 }
3547
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003548 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00003549 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00003550 NamedDecl *MemberDecl = R.getFoundDecl();
3551
3552 // FIXME: diagnose the presence of template arguments now.
3553
3554 // If the decl being referenced had an error, return an error for this
3555 // sub-expr without emitting another error, in order to avoid cascading
3556 // error cases.
3557 if (MemberDecl->isInvalidDecl())
3558 return ExprError();
3559
John McCallaa81e162009-12-01 22:10:20 +00003560 // Handle the implicit-member-access case.
3561 if (!BaseExpr) {
3562 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00003563 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnara25777432010-08-11 22:01:17 +00003564 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCallaa81e162009-12-01 22:10:20 +00003565
Douglas Gregor828a1972010-01-07 23:12:05 +00003566 SourceLocation Loc = R.getNameLoc();
3567 if (SS.getRange().isValid())
3568 Loc = SS.getRange().getBegin();
3569 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003570 }
3571
John McCall129e2df2009-11-30 22:42:35 +00003572 bool ShouldCheckUse = true;
3573 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3574 // Don't diagnose the use of a virtual member function unless it's
3575 // explicitly qualified.
3576 if (MD->isVirtual() && !SS.isSet())
3577 ShouldCheckUse = false;
3578 }
3579
3580 // Check the use of this member.
3581 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3582 Owned(BaseExpr);
3583 return ExprError();
3584 }
3585
John McCallf6a16482010-12-04 03:47:34 +00003586 // Perform a property load on the base regardless of whether we
3587 // actually need it for the declaration.
3588 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3589 ConvertPropertyForRValue(BaseExpr);
3590
John McCalldfa1edb2010-11-23 20:48:44 +00003591 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3592 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3593 SS, FD, FoundDecl, MemberNameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003594
Francois Pichet87c2e122010-11-21 06:08:52 +00003595 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3596 // We may have found a field within an anonymous union or struct
3597 // (C++ [class.union]).
John McCall5808ce42011-02-03 08:15:49 +00003598 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCallf6a16482010-12-04 03:47:34 +00003599 BaseExpr, OpLoc);
Francois Pichet87c2e122010-11-21 06:08:52 +00003600
John McCall129e2df2009-11-30 22:42:35 +00003601 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3602 MarkDeclarationReferenced(MemberLoc, Var);
3603 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003604 Var, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003605 Var->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00003606 VK_LValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003607 }
3608
John McCallf89e55a2010-11-18 06:31:45 +00003609 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall129e2df2009-11-30 22:42:35 +00003610 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3611 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003612 MemberFn, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003613 MemberFn->getType(),
3614 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3615 OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003616 }
John McCallf89e55a2010-11-18 06:31:45 +00003617 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall129e2df2009-11-30 22:42:35 +00003618
3619 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3620 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3621 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003622 Enum, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003623 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003624 }
3625
3626 Owned(BaseExpr);
3627
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003628 // We found something that we didn't expect. Complain.
John McCall129e2df2009-11-30 22:42:35 +00003629 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnara25777432010-08-11 22:01:17 +00003630 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003631 << MemberName << BaseType << int(IsArrow);
3632 else
3633 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3634 << MemberName << BaseType << int(IsArrow);
John McCall129e2df2009-11-30 22:42:35 +00003635
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003636 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3637 << MemberName;
Douglas Gregor2b147f02010-04-25 21:15:30 +00003638 R.suppressDiagnostics();
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003639 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00003640}
3641
John McCall028d3972010-12-15 16:46:44 +00003642/// Given that normal member access failed on the given expression,
3643/// and given that the expression's type involves builtin-id or
3644/// builtin-Class, decide whether substituting in the redefinition
3645/// types would be profitable. The redefinition type is whatever
3646/// this translation unit tried to typedef to id/Class; we store
3647/// it to the side and then re-use it in places like this.
3648static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3649 const ObjCObjectPointerType *opty
3650 = base->getType()->getAs<ObjCObjectPointerType>();
3651 if (!opty) return false;
3652
3653 const ObjCObjectType *ty = opty->getObjectType();
3654
3655 QualType redef;
3656 if (ty->isObjCId()) {
3657 redef = S.Context.ObjCIdRedefinitionType;
3658 } else if (ty->isObjCClass()) {
3659 redef = S.Context.ObjCClassRedefinitionType;
3660 } else {
3661 return false;
3662 }
3663
3664 // Do the substitution as long as the redefinition type isn't just a
3665 // possibly-qualified pointer to builtin-id or builtin-Class again.
3666 opty = redef->getAs<ObjCObjectPointerType>();
3667 if (opty && !opty->getObjectType()->getInterface() != 0)
3668 return false;
3669
3670 S.ImpCastExprToType(base, redef, CK_BitCast);
3671 return true;
3672}
3673
John McCall129e2df2009-11-30 22:42:35 +00003674/// Look up the given member of the given non-type-dependent
3675/// expression. This can return in one of two ways:
3676/// * If it returns a sentinel null-but-valid result, the caller will
3677/// assume that lookup was performed and the results written into
3678/// the provided structure. It will take over from there.
3679/// * Otherwise, the returned expression will be produced in place of
3680/// an ordinary member expression.
3681///
3682/// The ObjCImpDecl bit is a gross hack that will need to be properly
3683/// fixed for ObjC++.
John McCall60d7b3a2010-08-24 06:29:42 +00003684ExprResult
John McCall129e2df2009-11-30 22:42:35 +00003685Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00003686 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003687 CXXScopeSpec &SS,
John McCalld226f652010-08-21 09:40:31 +00003688 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003689 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003690
Steve Naroff3cc4af82007-12-16 21:42:28 +00003691 // Perform default conversions.
3692 DefaultFunctionArrayConversion(BaseExpr);
John McCall5e3c67b2010-12-15 04:42:30 +00003693 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003694
Steve Naroffdfa6aae2007-07-26 03:11:44 +00003695 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00003696 assert(!BaseType->isDependentType());
3697
3698 DeclarationName MemberName = R.getLookupName();
3699 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003700
John McCall028d3972010-12-15 16:46:44 +00003701 // For later type-checking purposes, turn arrow accesses into dot
3702 // accesses. The only access type we support that doesn't follow
3703 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3704 // and those never use arrows, so this is unaffected.
3705 if (IsArrow) {
3706 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3707 BaseType = Ptr->getPointeeType();
3708 else if (const ObjCObjectPointerType *Ptr
3709 = BaseType->getAs<ObjCObjectPointerType>())
3710 BaseType = Ptr->getPointeeType();
3711 else if (BaseType->isRecordType()) {
3712 // Recover from arrow accesses to records, e.g.:
3713 // struct MyRecord foo;
3714 // foo->bar
3715 // This is actually well-formed in C++ if MyRecord has an
3716 // overloaded operator->, but that should have been dealt with
3717 // by now.
3718 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3719 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3720 << FixItHint::CreateReplacement(OpLoc, ".");
3721 IsArrow = false;
3722 } else {
3723 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3724 << BaseType << BaseExpr->getSourceRange();
3725 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003726 }
3727 }
3728
John McCall028d3972010-12-15 16:46:44 +00003729 // Handle field access to simple records.
3730 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3731 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3732 RTy, OpLoc, SS, HasTemplateArgs))
3733 return ExprError();
3734
3735 // Returning valid-but-null is how we indicate to the caller that
3736 // the lookup result was filled in.
3737 return Owned((Expr*) 0);
David Chisnall0f436562009-08-17 16:35:33 +00003738 }
John McCall129e2df2009-11-30 22:42:35 +00003739
John McCall028d3972010-12-15 16:46:44 +00003740 // Handle ivar access to Objective-C objects.
3741 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003742 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall028d3972010-12-15 16:46:44 +00003743
3744 // There are three cases for the base type:
3745 // - builtin id (qualified or unqualified)
3746 // - builtin Class (qualified or unqualified)
3747 // - an interface
3748 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3749 if (!IDecl) {
3750 // There's an implicit 'isa' ivar on all objects.
3751 // But we only actually find it this way on objects of type 'id',
3752 // apparently.
3753 if (OTy->isObjCId() && Member->isStr("isa"))
3754 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3755 Context.getObjCClassType()));
3756
3757 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3758 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3759 ObjCImpDecl, HasTemplateArgs);
3760 goto fail;
3761 }
3762
3763 ObjCInterfaceDecl *ClassDeclared;
3764 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3765
3766 if (!IV) {
3767 // Attempt to correct for typos in ivar names.
3768 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3769 LookupMemberName);
3770 if (CorrectTypo(Res, 0, 0, IDecl, false,
3771 IsArrow ? CTC_ObjCIvarLookup
3772 : CTC_ObjCPropertyLookup) &&
3773 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3774 Diag(R.getNameLoc(),
3775 diag::err_typecheck_member_reference_ivar_suggest)
3776 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3777 << FixItHint::CreateReplacement(R.getNameLoc(),
3778 IV->getNameAsString());
3779 Diag(IV->getLocation(), diag::note_previous_decl)
3780 << IV->getDeclName();
3781 } else {
3782 Res.clear();
3783 Res.setLookupName(Member);
3784
3785 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3786 << IDecl->getDeclName() << MemberName
3787 << BaseExpr->getSourceRange();
3788 return ExprError();
3789 }
3790 }
3791
3792 // If the decl being referenced had an error, return an error for this
3793 // sub-expr without emitting another error, in order to avoid cascading
3794 // error cases.
3795 if (IV->isInvalidDecl())
3796 return ExprError();
3797
3798 // Check whether we can reference this field.
3799 if (DiagnoseUseOfDecl(IV, MemberLoc))
3800 return ExprError();
3801 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3802 IV->getAccessControl() != ObjCIvarDecl::Package) {
3803 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3804 if (ObjCMethodDecl *MD = getCurMethodDecl())
3805 ClassOfMethodDecl = MD->getClassInterface();
3806 else if (ObjCImpDecl && getCurFunctionDecl()) {
3807 // Case of a c-function declared inside an objc implementation.
3808 // FIXME: For a c-style function nested inside an objc implementation
3809 // class, there is no implementation context available, so we pass
3810 // down the context as argument to this routine. Ideally, this context
3811 // need be passed down in the AST node and somehow calculated from the
3812 // AST for a function decl.
3813 if (ObjCImplementationDecl *IMPD =
3814 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3815 ClassOfMethodDecl = IMPD->getClassInterface();
3816 else if (ObjCCategoryImplDecl* CatImplClass =
3817 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3818 ClassOfMethodDecl = CatImplClass->getClassInterface();
3819 }
3820
3821 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3822 if (ClassDeclared != IDecl ||
3823 ClassOfMethodDecl != ClassDeclared)
3824 Diag(MemberLoc, diag::error_private_ivar_access)
3825 << IV->getDeclName();
3826 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3827 // @protected
3828 Diag(MemberLoc, diag::error_protected_ivar_access)
3829 << IV->getDeclName();
3830 }
3831
3832 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3833 MemberLoc, BaseExpr,
3834 IsArrow));
3835 }
3836
3837 // Objective-C property access.
3838 const ObjCObjectPointerType *OPT;
3839 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3840 // This actually uses the base as an r-value.
3841 DefaultLvalueConversion(BaseExpr);
3842 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3843
3844 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3845
3846 const ObjCObjectType *OT = OPT->getObjectType();
3847
3848 // id, with and without qualifiers.
3849 if (OT->isObjCId()) {
3850 // Check protocols on qualified interfaces.
3851 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3852 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3853 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3854 // Check the use of this declaration
3855 if (DiagnoseUseOfDecl(PD, MemberLoc))
3856 return ExprError();
3857
3858 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3859 VK_LValue,
3860 OK_ObjCProperty,
3861 MemberLoc,
3862 BaseExpr));
3863 }
3864
3865 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3866 // Check the use of this method.
3867 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3868 return ExprError();
3869 Selector SetterSel =
3870 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3871 PP.getSelectorTable(), Member);
3872 ObjCMethodDecl *SMD = 0;
3873 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3874 SetterSel, Context))
3875 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3876 QualType PType = OMD->getSendResultType();
3877
3878 ExprValueKind VK = VK_LValue;
3879 if (!getLangOptions().CPlusPlus &&
3880 IsCForbiddenLValueType(Context, PType))
3881 VK = VK_RValue;
3882 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3883
3884 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3885 VK, OK,
3886 MemberLoc, BaseExpr));
3887 }
3888 }
3889
3890 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3891 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3892 ObjCImpDecl, HasTemplateArgs);
3893
3894 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3895 << MemberName << BaseType);
3896 }
3897
3898 // 'Class', unqualified only.
3899 if (OT->isObjCClass()) {
3900 // Only works in a method declaration (??!).
3901 ObjCMethodDecl *MD = getCurMethodDecl();
3902 if (!MD) {
3903 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3904 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3905 ObjCImpDecl, HasTemplateArgs);
3906
3907 goto fail;
3908 }
3909
3910 // Also must look for a getter name which uses property syntax.
3911 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003912 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3913 ObjCMethodDecl *Getter;
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003914 if ((Getter = IFace->lookupClassMethod(Sel))) {
3915 // Check the use of this method.
3916 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3917 return ExprError();
John McCall028d3972010-12-15 16:46:44 +00003918 } else
Fariborz Jahanian74b27562010-12-03 23:37:08 +00003919 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003920 // If we found a getter then this may be a valid dot-reference, we
3921 // will look for the matching setter, in case it is needed.
3922 Selector SetterSel =
John McCall028d3972010-12-15 16:46:44 +00003923 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3924 PP.getSelectorTable(), Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003925 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3926 if (!Setter) {
3927 // If this reference is in an @implementation, also check for 'private'
3928 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00003929 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003930 }
3931 // Look through local category implementations associated with the class.
3932 if (!Setter)
3933 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003934
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003935 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3936 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003937
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003938 if (Getter || Setter) {
3939 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003940
John McCall09431682010-11-18 19:01:18 +00003941 ExprValueKind VK = VK_LValue;
3942 if (Getter) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003943 PType = Getter->getSendResultType();
John McCall09431682010-11-18 19:01:18 +00003944 if (!getLangOptions().CPlusPlus &&
3945 IsCForbiddenLValueType(Context, PType))
3946 VK = VK_RValue;
3947 } else {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003948 // Get the expression type from Setter's incoming parameter.
3949 PType = (*(Setter->param_end() -1))->getType();
John McCall09431682010-11-18 19:01:18 +00003950 }
3951 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3952
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003953 // FIXME: we must check that the setter has property type.
John McCall12f78a62010-12-02 01:19:52 +00003954 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3955 PType, VK, OK,
3956 MemberLoc, BaseExpr));
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003957 }
John McCall028d3972010-12-15 16:46:44 +00003958
3959 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3960 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3961 ObjCImpDecl, HasTemplateArgs);
3962
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003963 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall028d3972010-12-15 16:46:44 +00003964 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00003965 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003966
John McCall028d3972010-12-15 16:46:44 +00003967 // Normal property access.
3968 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3969 SourceLocation(), QualType(), false);
Steve Naroff14108da2009-07-10 23:34:53 +00003970 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003971
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003972 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00003973 if (BaseType->isExtVectorType()) {
John McCall5e3c67b2010-12-15 04:42:30 +00003974 // FIXME: this expr should store IsArrow.
Anders Carlsson8f28f992009-08-26 18:25:21 +00003975 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall5e3c67b2010-12-15 04:42:30 +00003976 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall09431682010-11-18 19:01:18 +00003977 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3978 Member, MemberLoc);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003979 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003980 return ExprError();
John McCall09431682010-11-18 19:01:18 +00003981
3982 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3983 *Member, MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003984 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003985
John McCall028d3972010-12-15 16:46:44 +00003986 // Adjust builtin-sel to the appropriate redefinition type if that's
3987 // not just a pointer to builtin-sel again.
3988 if (IsArrow &&
3989 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
3990 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
3991 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
3992 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3993 ObjCImpDecl, HasTemplateArgs);
3994 }
3995
3996 // Failure cases.
3997 fail:
3998
3999 // There's a possible road to recovery for function types.
4000 const FunctionType *Fun = 0;
Matt Beaumont-Gay26ae5dd2011-02-17 02:54:17 +00004001 SourceLocation ParenInsertionLoc =
4002 PP.getLocForEndOfToken(BaseExpr->getLocEnd());
John McCall028d3972010-12-15 16:46:44 +00004003
4004 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4005 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4006 // fall out, handled below.
4007
4008 // Recover from dot accesses to pointers, e.g.:
4009 // type *foo;
4010 // foo.bar
4011 // This is actually well-formed in two cases:
4012 // - 'type' is an Objective C type
4013 // - 'bar' is a pseudo-destructor name which happens to refer to
4014 // the appropriate pointer type
Argyrios Kyrtzidisdf8dc5d2011-01-25 23:16:36 +00004015 } else if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
John McCall028d3972010-12-15 16:46:44 +00004016 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
4017 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4018 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
4019 << FixItHint::CreateReplacement(OpLoc, "->");
4020
4021 // Recurse as an -> access.
4022 IsArrow = true;
4023 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4024 ObjCImpDecl, HasTemplateArgs);
4025 }
4026 } else {
4027 Fun = BaseType->getAs<FunctionType>();
4028 }
4029
4030 // If the user is trying to apply -> or . to a function pointer
4031 // type, it's probably because they forgot parentheses to call that
4032 // function. Suggest the addition of those parentheses, build the
4033 // call, and continue on.
4034 if (Fun || BaseType == Context.OverloadTy) {
4035 bool TryCall;
4036 if (BaseType == Context.OverloadTy) {
Matt Beaumont-Gay26ae5dd2011-02-17 02:54:17 +00004037 // Plunder the overload set for something that would make the member
4038 // expression valid.
4039 const OverloadExpr *Overloads = cast<OverloadExpr>(BaseExpr);
4040 UnresolvedSet<4> CandidateOverloads;
4041 bool HasZeroArgCandidateOverload = false;
4042 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
4043 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
4044 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*it);
4045 QualType ResultTy = OverloadDecl->getResultType();
4046 if ((!IsArrow && ResultTy->isRecordType()) ||
4047 (IsArrow && ResultTy->isPointerType() &&
4048 ResultTy->getPointeeType()->isRecordType())) {
4049 CandidateOverloads.addDecl(*it);
4050 if (OverloadDecl->getNumParams() == 0) {
4051 HasZeroArgCandidateOverload = true;
4052 }
4053 }
4054 }
4055 if (HasZeroArgCandidateOverload && CandidateOverloads.size() == 1) {
4056 // We have one reasonable overload, and there's only one way to call it,
4057 // so emit a fixit and try to recover
4058 Diag(ParenInsertionLoc, diag::err_member_reference_needs_call)
4059 << 1
4060 << BaseExpr->getSourceRange()
4061 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4062 TryCall = true;
4063 } else {
4064 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
4065 << 0
4066 << BaseExpr->getSourceRange();
4067 int CandidateOverloadCount = CandidateOverloads.size();
4068 int I;
4069 for (I = 0; I < CandidateOverloadCount; ++I) {
4070 // FIXME: Magic number for max shown overloads stolen from
4071 // OverloadCandidateSet::NoteCandidates.
4072 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4073 break;
4074 }
4075 Diag(CandidateOverloads[I].getDecl()->getSourceRange().getBegin(),
4076 diag::note_member_ref_possible_intended_overload);
4077 }
4078 if (I != CandidateOverloadCount) {
4079 Diag(BaseExpr->getExprLoc(), diag::note_ovl_too_many_candidates)
4080 << int(CandidateOverloadCount - I);
4081 }
4082 return ExprError();
4083 }
John McCall028d3972010-12-15 16:46:44 +00004084 } else {
4085 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4086 TryCall = (FPT->getNumArgs() == 0);
4087 } else {
4088 TryCall = true;
4089 }
4090
4091 if (TryCall) {
4092 QualType ResultTy = Fun->getResultType();
4093 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4094 (IsArrow && ResultTy->isPointerType() &&
4095 ResultTy->getAs<PointerType>()->getPointeeType()->isRecordType());
4096 }
4097 }
4098
4099
4100 if (TryCall) {
Matt Beaumont-Gay26ae5dd2011-02-17 02:54:17 +00004101 if (Fun) {
4102 Diag(BaseExpr->getExprLoc(),
4103 diag::err_member_reference_needs_call_zero_arg)
4104 << QualType(Fun, 0)
4105 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4106 }
John McCall028d3972010-12-15 16:46:44 +00004107
4108 ExprResult NewBase
Matt Beaumont-Gay26ae5dd2011-02-17 02:54:17 +00004109 = ActOnCallExpr(0, BaseExpr, ParenInsertionLoc,
4110 MultiExprArg(*this, 0, 0), ParenInsertionLoc);
John McCall028d3972010-12-15 16:46:44 +00004111 if (NewBase.isInvalid())
4112 return ExprError();
4113 BaseExpr = NewBase.takeAs<Expr>();
4114
4115
4116 DefaultFunctionArrayConversion(BaseExpr);
4117 BaseType = BaseExpr->getType();
4118
4119 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4120 ObjCImpDecl, HasTemplateArgs);
4121 }
4122 }
4123
Douglas Gregor214f31a2009-03-27 06:00:30 +00004124 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
4125 << BaseType << BaseExpr->getSourceRange();
4126
Douglas Gregor214f31a2009-03-27 06:00:30 +00004127 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00004128}
4129
John McCall129e2df2009-11-30 22:42:35 +00004130/// The main callback when the parser finds something like
4131/// expression . [nested-name-specifier] identifier
4132/// expression -> [nested-name-specifier] identifier
4133/// where 'identifier' encompasses a fairly broad spectrum of
4134/// possibilities, including destructor and operator references.
4135///
4136/// \param OpKind either tok::arrow or tok::period
4137/// \param HasTrailingLParen whether the next token is '(', which
4138/// is used to diagnose mis-uses of special members that can
4139/// only be called
4140/// \param ObjCImpDecl the current ObjC @implementation decl;
4141/// this is an ugly hack around the fact that ObjC @implementations
4142/// aren't properly put in the context chain
John McCall60d7b3a2010-08-24 06:29:42 +00004143ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall5e3c67b2010-12-15 04:42:30 +00004144 SourceLocation OpLoc,
4145 tok::TokenKind OpKind,
4146 CXXScopeSpec &SS,
4147 UnqualifiedId &Id,
4148 Decl *ObjCImpDecl,
4149 bool HasTrailingLParen) {
John McCall129e2df2009-11-30 22:42:35 +00004150 if (SS.isSet() && SS.isInvalid())
4151 return ExprError();
4152
Francois Pichetdbee3412011-01-18 05:04:39 +00004153 // Warn about the explicit constructor calls Microsoft extension.
4154 if (getLangOptions().Microsoft &&
4155 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4156 Diag(Id.getSourceRange().getBegin(),
4157 diag::ext_ms_explicit_constructor_call);
4158
John McCall129e2df2009-11-30 22:42:35 +00004159 TemplateArgumentListInfo TemplateArgsBuffer;
4160
4161 // Decompose the name into its component parts.
Abramo Bagnara25777432010-08-11 22:01:17 +00004162 DeclarationNameInfo NameInfo;
John McCall129e2df2009-11-30 22:42:35 +00004163 const TemplateArgumentListInfo *TemplateArgs;
4164 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00004165 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004166
Abramo Bagnara25777432010-08-11 22:01:17 +00004167 DeclarationName Name = NameInfo.getName();
John McCall129e2df2009-11-30 22:42:35 +00004168 bool IsArrow = (OpKind == tok::arrow);
4169
4170 NamedDecl *FirstQualifierInScope
4171 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4172 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4173
4174 // This is a postfix expression, so get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004175 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004176 if (Result.isInvalid()) return ExprError();
4177 Base = Result.take();
John McCall129e2df2009-11-30 22:42:35 +00004178
Douglas Gregor01e56ae2010-04-12 20:54:26 +00004179 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4180 isDependentScopeSpecifier(SS)) {
John McCall9ae2f072010-08-23 23:25:46 +00004181 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00004182 IsArrow, OpLoc,
4183 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00004184 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004185 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00004186 LookupResult R(*this, NameInfo, LookupMemberName);
John McCallad00b772010-06-16 08:42:20 +00004187 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
4188 SS, ObjCImpDecl, TemplateArgs != 0);
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004189
John McCallad00b772010-06-16 08:42:20 +00004190 if (Result.isInvalid()) {
4191 Owned(Base);
4192 return ExprError();
4193 }
John McCall129e2df2009-11-30 22:42:35 +00004194
John McCallad00b772010-06-16 08:42:20 +00004195 if (Result.get()) {
4196 // The only way a reference to a destructor can be used is to
4197 // immediately call it, which falls into this case. If the
4198 // next token is not a '(', produce a diagnostic and build the
4199 // call now.
4200 if (!HasTrailingLParen &&
4201 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCall9ae2f072010-08-23 23:25:46 +00004202 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall129e2df2009-11-30 22:42:35 +00004203
John McCallad00b772010-06-16 08:42:20 +00004204 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00004205 }
4206
John McCall9ae2f072010-08-23 23:25:46 +00004207 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00004208 OpLoc, IsArrow, SS, FirstQualifierInScope,
4209 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004210 }
4211
4212 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00004213}
4214
John McCall60d7b3a2010-08-24 06:29:42 +00004215ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00004216 FunctionDecl *FD,
4217 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00004218 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004219 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00004220 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00004221 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004222 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00004223 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004224 return ExprError();
4225 }
4226
4227 if (Param->hasUninstantiatedDefaultArg()) {
4228 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00004229
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004230 // Instantiate the expression.
4231 MultiLevelTemplateArgumentList ArgList
4232 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00004233
Nico Weber08e41a62010-11-29 18:19:25 +00004234 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004235 = ArgList.getInnermost();
4236 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4237 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004238
Nico Weber08e41a62010-11-29 18:19:25 +00004239 ExprResult Result;
4240 {
4241 // C++ [dcl.fct.default]p5:
4242 // The names in the [default argument] expression are bound, and
4243 // the semantic constraints are checked, at the point where the
4244 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00004245 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00004246 Result = SubstExpr(UninstExpr, ArgList);
4247 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004248 if (Result.isInvalid())
4249 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004250
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004251 // Check the expression as an initializer for the parameter.
4252 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004253 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004254 InitializationKind Kind
4255 = InitializationKind::CreateCopy(Param->getLocation(),
4256 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4257 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00004258
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004259 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4260 Result = InitSeq.Perform(*this, Entity, Kind,
4261 MultiExprArg(*this, &ResultE, 1));
4262 if (Result.isInvalid())
4263 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004264
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004265 // Build the default argument expression.
4266 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4267 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004268 }
4269
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004270 // If the default expression creates temporaries, we need to
4271 // push them to the current stack of expression temporaries so they'll
4272 // be properly destroyed.
4273 // FIXME: We should really be rebuilding the default argument with new
4274 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00004275 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4276 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4277 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4278 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4279 ExprTemporaries.push_back(Temporary);
4280 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004281
4282 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00004283 // Just mark all of the declarations in this potentially-evaluated expression
4284 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004285 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00004286 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004287}
4288
Douglas Gregor88a35142008-12-22 05:46:06 +00004289/// ConvertArgumentsForCall - Converts the arguments specified in
4290/// Args/NumArgs to the parameter types of the function FDecl with
4291/// function prototype Proto. Call is the call expression itself, and
4292/// Fn is the function expression. For a C++ member function, this
4293/// routine does not attempt to convert the object argument. Returns
4294/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004295bool
4296Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00004297 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00004298 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00004299 Expr **Args, unsigned NumArgs,
4300 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004301 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00004302 // assignment, to the types of the corresponding parameter, ...
4303 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004304 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004305
Douglas Gregor88a35142008-12-22 05:46:06 +00004306 // If too few arguments are available (and we don't have default
4307 // arguments for the remaining parameters), don't make the call.
4308 if (NumArgs < NumArgsInProto) {
4309 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4310 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004311 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00004312 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004313 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00004314 }
4315
4316 // If too many are passed and not variadic, error on the extras and drop
4317 // them.
4318 if (NumArgs > NumArgsInProto) {
4319 if (!Proto->isVariadic()) {
4320 Diag(Args[NumArgsInProto]->getLocStart(),
4321 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004322 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00004323 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00004324 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4325 Args[NumArgs-1]->getLocEnd());
4326 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004327 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004328 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004329 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004330 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004331 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004332 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004333 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4334 if (Fn->getType()->isBlockPointerType())
4335 CallType = VariadicBlock; // Block
4336 else if (isa<MemberExpr>(Fn))
4337 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004338 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004339 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004340 if (Invalid)
4341 return true;
4342 unsigned TotalNumArgs = AllArgs.size();
4343 for (unsigned i = 0; i < TotalNumArgs; ++i)
4344 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004345
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004346 return false;
4347}
Mike Stumpeed9cac2009-02-19 03:04:26 +00004348
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004349bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4350 FunctionDecl *FDecl,
4351 const FunctionProtoType *Proto,
4352 unsigned FirstProtoArg,
4353 Expr **Args, unsigned NumArgs,
4354 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004355 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004356 unsigned NumArgsInProto = Proto->getNumArgs();
4357 unsigned NumArgsToCheck = NumArgs;
4358 bool Invalid = false;
4359 if (NumArgs != NumArgsInProto)
4360 // Use default arguments for missing arguments
4361 NumArgsToCheck = NumArgsInProto;
4362 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00004363 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004364 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004365 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004366
Douglas Gregor88a35142008-12-22 05:46:06 +00004367 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004368 if (ArgIx < NumArgs) {
4369 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004370
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004371 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4372 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004373 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004374 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004375 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004376
Douglas Gregora188ff22009-12-22 16:09:06 +00004377 // Pass the argument
4378 ParmVarDecl *Param = 0;
4379 if (FDecl && i < FDecl->getNumParams())
4380 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00004381
Douglas Gregora188ff22009-12-22 16:09:06 +00004382 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004383 Param? InitializedEntity::InitializeParameter(Context, Param)
4384 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCall60d7b3a2010-08-24 06:29:42 +00004385 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00004386 SourceLocation(),
4387 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00004388 if (ArgE.isInvalid())
4389 return true;
4390
4391 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004392 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00004393 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004394
John McCall60d7b3a2010-08-24 06:29:42 +00004395 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004396 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004397 if (ArgExpr.isInvalid())
4398 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004399
Anders Carlsson56c5e332009-08-25 03:49:14 +00004400 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004401 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004402 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004403 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004404
Douglas Gregor88a35142008-12-22 05:46:06 +00004405 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004406 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004407 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner40378332010-05-16 04:01:30 +00004408 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004409 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00004410 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004411 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004412 }
4413 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004414 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00004415}
4416
Steve Narofff69936d2007-09-16 03:34:24 +00004417/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00004418/// This provides the location of the left/right parens and a list of comma
4419/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00004420ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004421Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004422 MultiExprArg args, SourceLocation RParenLoc,
4423 Expr *ExecConfig) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00004424 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00004425
4426 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004427 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00004428 if (Result.isInvalid()) return ExprError();
4429 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00004430
John McCall9ae2f072010-08-23 23:25:46 +00004431 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004432
Douglas Gregor88a35142008-12-22 05:46:06 +00004433 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00004434 // If this is a pseudo-destructor expression, build the call immediately.
4435 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4436 if (NumArgs > 0) {
4437 // Pseudo-destructor calls should not have any arguments.
4438 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00004439 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00004440 SourceRange(Args[0]->getLocStart(),
4441 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00004442
Douglas Gregora71d8192009-09-04 17:36:40 +00004443 NumArgs = 0;
4444 }
Mike Stump1eb44332009-09-09 15:08:12 +00004445
Douglas Gregora71d8192009-09-04 17:36:40 +00004446 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00004447 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00004448 }
Mike Stump1eb44332009-09-09 15:08:12 +00004449
Douglas Gregor17330012009-02-04 15:01:18 +00004450 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004451 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00004452 // FIXME: Will need to cache the results of name lookup (including ADL) in
4453 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00004454 bool Dependent = false;
4455 if (Fn->isTypeDependent())
4456 Dependent = true;
4457 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4458 Dependent = true;
4459
Peter Collingbournee08ce652011-02-09 21:07:24 +00004460 if (Dependent) {
4461 if (ExecConfig) {
4462 return Owned(new (Context) CUDAKernelCallExpr(
4463 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4464 Context.DependentTy, VK_RValue, RParenLoc));
4465 } else {
4466 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4467 Context.DependentTy, VK_RValue,
4468 RParenLoc));
4469 }
4470 }
Douglas Gregor17330012009-02-04 15:01:18 +00004471
4472 // Determine whether this is a call to an object (C++ [over.call.object]).
4473 if (Fn->getType()->isRecordType())
4474 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004475 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00004476
John McCall129e2df2009-11-30 22:42:35 +00004477 Expr *NakedFn = Fn->IgnoreParens();
4478
4479 // Determine whether this is a call to an unresolved member function.
4480 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4481 // If lookup was unresolved but not dependent (i.e. didn't find
4482 // an unresolved using declaration), it has to be an overloaded
4483 // function set, which means it must contain either multiple
4484 // declarations (all methods or method templates) or a single
4485 // method template.
4486 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor2b147f02010-04-25 21:15:30 +00004487 isa<FunctionTemplateDecl>(
4488 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00004489 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00004490
John McCallaa81e162009-12-01 22:10:20 +00004491 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004492 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00004493 }
4494
Douglas Gregorfa047642009-02-04 00:32:51 +00004495 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00004496 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00004497 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00004498 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00004499 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004500 RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00004501 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004502
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004503 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00004504 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCall2de56d12010-08-25 11:45:40 +00004505 if (BO->getOpcode() == BO_PtrMemD ||
4506 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00004507 if (const FunctionProtoType *FPT
4508 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004509 QualType ResultTy = FPT->getCallResultType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00004510 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004511
Douglas Gregorfdc13a02011-02-04 12:57:49 +00004512 // Check that the object type isn't more qualified than the
4513 // member function we're calling.
4514 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4515 Qualifiers ObjectQuals
4516 = BO->getOpcode() == BO_PtrMemD
4517 ? BO->getLHS()->getType().getQualifiers()
4518 : BO->getLHS()->getType()->getAs<PointerType>()
4519 ->getPointeeType().getQualifiers();
4520
4521 Qualifiers Difference = ObjectQuals - FuncQuals;
4522 Difference.removeObjCGCAttr();
4523 Difference.removeAddressSpace();
4524 if (Difference) {
4525 std::string QualsString = Difference.getAsString();
4526 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4527 << BO->getType().getUnqualifiedType()
4528 << QualsString
4529 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4530 }
4531
John McCall9ae2f072010-08-23 23:25:46 +00004532 CXXMemberCallExpr *TheCall
Abramo Bagnara6c572f12010-12-03 21:39:42 +00004533 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCallf89e55a2010-11-18 06:31:45 +00004534 NumArgs, ResultTy, VK,
John McCall9ae2f072010-08-23 23:25:46 +00004535 RParenLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004536
4537 if (CheckCallReturnType(FPT->getResultType(),
4538 BO->getRHS()->getSourceRange().getBegin(),
John McCall9ae2f072010-08-23 23:25:46 +00004539 TheCall, 0))
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004540 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00004541
John McCall9ae2f072010-08-23 23:25:46 +00004542 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004543 RParenLoc))
4544 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004545
John McCall9ae2f072010-08-23 23:25:46 +00004546 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004547 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004548 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004549 diag::err_typecheck_call_not_function)
4550 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004551 }
4552 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004553 }
4554
Douglas Gregorfa047642009-02-04 00:32:51 +00004555 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004556 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004557 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004558
Eli Friedmanefa42f72009-12-26 03:35:45 +00004559 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00004560 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4561 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4562 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004563 RParenLoc, ExecConfig);
Douglas Gregoref9b1492010-11-09 20:03:54 +00004564 }
4565
John McCall3b4294e2009-12-16 12:17:52 +00004566 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00004567 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4568 if (UnOp->getOpcode() == UO_AddrOf)
4569 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4570
John McCall3b4294e2009-12-16 12:17:52 +00004571 if (isa<DeclRefExpr>(NakedFn))
4572 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4573
Peter Collingbournee08ce652011-02-09 21:07:24 +00004574 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4575 ExecConfig);
4576}
4577
4578ExprResult
4579Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4580 MultiExprArg execConfig, SourceLocation GGGLoc) {
4581 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4582 if (!ConfigDecl)
4583 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4584 << "cudaConfigureCall");
4585 QualType ConfigQTy = ConfigDecl->getType();
4586
4587 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4588 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4589
4590 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00004591}
4592
John McCall3b4294e2009-12-16 12:17:52 +00004593/// BuildResolvedCallExpr - Build a call to a resolved expression,
4594/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00004595/// unary-convert to an expression of function-pointer or
4596/// block-pointer type.
4597///
4598/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00004599ExprResult
John McCallaa81e162009-12-01 22:10:20 +00004600Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4601 SourceLocation LParenLoc,
4602 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004603 SourceLocation RParenLoc,
4604 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00004605 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4606
Chris Lattner04421082008-04-08 04:40:51 +00004607 // Promote the function operand.
4608 UsualUnaryConversions(Fn);
4609
Chris Lattner925e60d2007-12-28 05:29:59 +00004610 // Make the call expr early, before semantic checks. This guarantees cleanup
4611 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004612 CallExpr *TheCall;
4613 if (Config) {
4614 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4615 cast<CallExpr>(Config),
4616 Args, NumArgs,
4617 Context.BoolTy,
4618 VK_RValue,
4619 RParenLoc);
4620 } else {
4621 TheCall = new (Context) CallExpr(Context, Fn,
4622 Args, NumArgs,
4623 Context.BoolTy,
4624 VK_RValue,
4625 RParenLoc);
4626 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004627
Steve Naroffdd972f22008-09-05 22:11:13 +00004628 const FunctionType *FuncT;
4629 if (!Fn->getType()->isBlockPointerType()) {
4630 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4631 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00004632 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00004633 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00004634 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4635 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00004636 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00004637 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00004638 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00004639 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00004640 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004641 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00004642 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4643 << Fn->getType() << Fn->getSourceRange());
4644
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004645 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004646 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00004647 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004648 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004649 return ExprError();
4650
Chris Lattner925e60d2007-12-28 05:29:59 +00004651 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004652 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004653 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004654
Douglas Gregor72564e72009-02-26 23:50:07 +00004655 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00004656 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00004657 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004658 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004659 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004660 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004661
Douglas Gregor74734d52009-04-02 15:37:10 +00004662 if (FDecl) {
4663 // Check if we have too few/too many template arguments, based
4664 // on our knowledge of the function definition.
4665 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004666 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004667 const FunctionProtoType *Proto
4668 = Def->getType()->getAs<FunctionProtoType>();
4669 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004670 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4671 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004672 }
Douglas Gregor46542412010-10-25 20:39:23 +00004673
4674 // If the function we're calling isn't a function prototype, but we have
4675 // a function prototype from a prior declaratiom, use that prototype.
4676 if (!FDecl->hasPrototype())
4677 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004678 }
4679
Steve Naroffb291ab62007-08-28 23:30:39 +00004680 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004681 for (unsigned i = 0; i != NumArgs; i++) {
4682 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004683
4684 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004685 InitializedEntity Entity
4686 = InitializedEntity::InitializeParameter(Context,
4687 Proto->getArgType(i));
4688 ExprResult ArgE = PerformCopyInitialization(Entity,
4689 SourceLocation(),
4690 Owned(Arg));
4691 if (ArgE.isInvalid())
4692 return true;
4693
4694 Arg = ArgE.takeAs<Expr>();
4695
4696 } else {
4697 DefaultArgumentPromotion(Arg);
Douglas Gregor46542412010-10-25 20:39:23 +00004698 }
4699
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004700 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4701 Arg->getType(),
4702 PDiag(diag::err_call_incomplete_argument)
4703 << Arg->getSourceRange()))
4704 return ExprError();
4705
Chris Lattner925e60d2007-12-28 05:29:59 +00004706 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004707 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004708 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004709
Douglas Gregor88a35142008-12-22 05:46:06 +00004710 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4711 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004712 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4713 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004714
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004715 // Check for sentinels
4716 if (NDecl)
4717 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004718
Chris Lattner59907c42007-08-10 20:18:51 +00004719 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004720 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00004721 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00004722 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004723
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004724 if (unsigned BuiltinID = FDecl->getBuiltinID())
4725 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004726 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00004727 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00004728 return ExprError();
4729 }
Chris Lattner59907c42007-08-10 20:18:51 +00004730
John McCall9ae2f072010-08-23 23:25:46 +00004731 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004732}
4733
John McCall60d7b3a2010-08-24 06:29:42 +00004734ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004735Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004736 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004737 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004738 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004739 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004740
4741 TypeSourceInfo *TInfo;
4742 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4743 if (!TInfo)
4744 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4745
John McCall9ae2f072010-08-23 23:25:46 +00004746 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004747}
4748
John McCall60d7b3a2010-08-24 06:29:42 +00004749ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004750Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00004751 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004752 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004753
Eli Friedman6223c222008-05-20 05:22:08 +00004754 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004755 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4756 PDiag(diag::err_illegal_decl_array_incomplete_type)
4757 << SourceRange(LParenLoc,
4758 literalExpr->getSourceRange().getEnd())))
4759 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004760 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004761 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4762 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004763 } else if (!literalType->isDependentType() &&
4764 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004765 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00004766 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00004767 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004768 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004769
Douglas Gregor99a2e602009-12-16 01:38:02 +00004770 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004771 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004772 InitializationKind Kind
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004773 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004774 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00004775 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00004776 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00004777 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00004778 &literalType);
4779 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004780 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004781 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004782
Chris Lattner371f2582008-12-04 23:50:19 +00004783 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004784 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00004785 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004786 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004787 }
Eli Friedman08544622009-12-22 02:35:53 +00004788
John McCallf89e55a2010-11-18 06:31:45 +00004789 // In C, compound literals are l-values for some reason.
4790 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4791
John McCall1d7d8d62010-01-19 22:33:45 +00004792 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCallf89e55a2010-11-18 06:31:45 +00004793 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004794}
4795
John McCall60d7b3a2010-08-24 06:29:42 +00004796ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004797Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004798 SourceLocation RBraceLoc) {
4799 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00004800 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00004801
Steve Naroff08d92e42007-09-15 18:49:24 +00004802 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004803 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004804
Ted Kremenek709210f2010-04-13 23:39:13 +00004805 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4806 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004807 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004808 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004809}
4810
John McCallf3ea8cf2010-11-14 08:17:51 +00004811/// Prepares for a scalar cast, performing all the necessary stages
4812/// except the final cast and returning the kind required.
4813static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4814 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4815 // Also, callers should have filtered out the invalid cases with
4816 // pointers. Everything else should be possible.
4817
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004818 QualType SrcTy = Src->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00004819 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004820 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004821
John McCalldaa8e4e2010-11-15 09:13:47 +00004822 switch (SrcTy->getScalarTypeKind()) {
4823 case Type::STK_MemberPointer:
4824 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004825
John McCalldaa8e4e2010-11-15 09:13:47 +00004826 case Type::STK_Pointer:
4827 switch (DestTy->getScalarTypeKind()) {
4828 case Type::STK_Pointer:
4829 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00004830 CK_AnyPointerToObjCPointerCast :
4831 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004832 case Type::STK_Bool:
4833 return CK_PointerToBoolean;
4834 case Type::STK_Integral:
4835 return CK_PointerToIntegral;
4836 case Type::STK_Floating:
4837 case Type::STK_FloatingComplex:
4838 case Type::STK_IntegralComplex:
4839 case Type::STK_MemberPointer:
4840 llvm_unreachable("illegal cast from pointer");
4841 }
4842 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004843
John McCalldaa8e4e2010-11-15 09:13:47 +00004844 case Type::STK_Bool: // casting from bool is like casting from an integer
4845 case Type::STK_Integral:
4846 switch (DestTy->getScalarTypeKind()) {
4847 case Type::STK_Pointer:
John McCallf3ea8cf2010-11-14 08:17:51 +00004848 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004849 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004850 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004851 case Type::STK_Bool:
4852 return CK_IntegralToBoolean;
4853 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004854 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004855 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004856 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004857 case Type::STK_IntegralComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004858 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCall8786da72010-12-14 17:51:41 +00004859 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004860 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004861 case Type::STK_FloatingComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004862 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004863 CK_IntegralToFloating);
4864 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004865 case Type::STK_MemberPointer:
4866 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004867 }
4868 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004869
John McCalldaa8e4e2010-11-15 09:13:47 +00004870 case Type::STK_Floating:
4871 switch (DestTy->getScalarTypeKind()) {
4872 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004873 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004874 case Type::STK_Bool:
4875 return CK_FloatingToBoolean;
4876 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004877 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004878 case Type::STK_FloatingComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004879 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCall8786da72010-12-14 17:51:41 +00004880 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004881 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004882 case Type::STK_IntegralComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004883 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004884 CK_FloatingToIntegral);
4885 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004886 case Type::STK_Pointer:
4887 llvm_unreachable("valid float->pointer cast?");
4888 case Type::STK_MemberPointer:
4889 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004890 }
4891 break;
4892
John McCalldaa8e4e2010-11-15 09:13:47 +00004893 case Type::STK_FloatingComplex:
4894 switch (DestTy->getScalarTypeKind()) {
4895 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004896 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004897 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004898 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004899 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004900 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00004901 if (S.Context.hasSameType(ET, DestTy))
4902 return CK_FloatingComplexToReal;
4903 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4904 return CK_FloatingCast;
4905 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004906 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004907 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004908 case Type::STK_Integral:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004909 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004910 CK_FloatingComplexToReal);
4911 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004912 case Type::STK_Pointer:
4913 llvm_unreachable("valid complex float->pointer cast?");
4914 case Type::STK_MemberPointer:
4915 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004916 }
4917 break;
4918
John McCalldaa8e4e2010-11-15 09:13:47 +00004919 case Type::STK_IntegralComplex:
4920 switch (DestTy->getScalarTypeKind()) {
4921 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004922 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004923 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004924 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004925 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004926 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00004927 if (S.Context.hasSameType(ET, DestTy))
4928 return CK_IntegralComplexToReal;
4929 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4930 return CK_IntegralCast;
4931 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004932 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004933 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004934 case Type::STK_Floating:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004935 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004936 CK_IntegralComplexToReal);
4937 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004938 case Type::STK_Pointer:
4939 llvm_unreachable("valid complex int->pointer cast?");
4940 case Type::STK_MemberPointer:
4941 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004942 }
4943 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00004944 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004945
John McCallf3ea8cf2010-11-14 08:17:51 +00004946 llvm_unreachable("Unhandled scalar cast");
4947 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00004948}
4949
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004950/// CheckCastTypes - Check type constraints for casting between types.
John McCallf89e55a2010-11-18 06:31:45 +00004951bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4952 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4953 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004954 if (getLangOptions().CPlusPlus)
Douglas Gregor40749ee2010-11-03 00:35:38 +00004955 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4956 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00004957 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004958 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004959
John McCallf89e55a2010-11-18 06:31:45 +00004960 // We only support r-value casts in C.
4961 VK = VK_RValue;
4962
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004963 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4964 // type needs to be scalar.
4965 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00004966 // We don't necessarily do lvalue-to-rvalue conversions on this.
4967 IgnoredValueConversions(castExpr);
4968
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004969 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00004970 Kind = CK_ToVoid;
Anders Carlssonebeaf202009-10-16 02:35:04 +00004971 return false;
4972 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004973
John McCallf6a16482010-12-04 03:47:34 +00004974 DefaultFunctionArrayLvalueConversion(castExpr);
4975
Eli Friedman8d438082010-07-17 20:43:49 +00004976 if (RequireCompleteType(TyR.getBegin(), castType,
4977 diag::err_typecheck_cast_to_incomplete))
4978 return true;
4979
Anders Carlssonebeaf202009-10-16 02:35:04 +00004980 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00004981 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004982 (castType->isStructureType() || castType->isUnionType())) {
4983 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004984 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004985 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4986 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004987 Kind = CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00004988 return false;
4989 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004990
Anders Carlssonc3516322009-10-16 02:48:28 +00004991 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004992 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00004993 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004994 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004995 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004996 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004997 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00004998 castExpr->getType()) &&
4999 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005000 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5001 << castExpr->getSourceRange();
5002 break;
5003 }
5004 }
5005 if (Field == FieldEnd)
5006 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
5007 << castExpr->getType() << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005008 Kind = CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00005009 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005010 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005011
Anders Carlssonc3516322009-10-16 02:48:28 +00005012 // Reject any other conversions to non-scalar types.
5013 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
5014 << castType << castExpr->getSourceRange();
5015 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005016
John McCallf3ea8cf2010-11-14 08:17:51 +00005017 // The type we're casting to is known to be a scalar or vector.
5018
5019 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005020 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00005021 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005022 return Diag(castExpr->getLocStart(),
5023 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00005024 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00005025 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005026
5027 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00005028 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005029
Anders Carlssonc3516322009-10-16 02:48:28 +00005030 if (castType->isVectorType())
5031 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
5032 if (castExpr->getType()->isVectorType())
5033 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
5034
John McCallf3ea8cf2010-11-14 08:17:51 +00005035 // The source and target types are both scalars, i.e.
5036 // - arithmetic types (fundamental, enum, and complex)
5037 // - all kinds of pointers
5038 // Note that member pointers were filtered out with C++, above.
5039
Anders Carlsson16a89042009-10-16 05:23:41 +00005040 if (isa<ObjCSelectorExpr>(castExpr))
5041 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005042
John McCallf3ea8cf2010-11-14 08:17:51 +00005043 // If either type is a pointer, the other type has to be either an
5044 // integer or a pointer.
Anders Carlssonc3516322009-10-16 02:48:28 +00005045 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00005046 QualType castExprType = castExpr->getType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005047 if (!castExprType->isIntegralType(Context) &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005048 castExprType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00005049 return Diag(castExpr->getLocStart(),
5050 diag::err_cast_pointer_from_non_pointer_int)
5051 << castExprType << castExpr->getSourceRange();
5052 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005053 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00005054 return Diag(castExpr->getLocStart(),
5055 diag::err_cast_pointer_to_non_pointer_int)
5056 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005057 }
Anders Carlsson82debc72009-10-18 18:12:03 +00005058
John McCallf3ea8cf2010-11-14 08:17:51 +00005059 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCallb7f4ffe2010-08-12 21:44:57 +00005060
John McCallf3ea8cf2010-11-14 08:17:51 +00005061 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00005062 CheckCastAlign(castExpr, castType, TyR);
5063
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005064 return false;
5065}
5066
Anders Carlssonc3516322009-10-16 02:48:28 +00005067bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00005068 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00005069 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005070
Anders Carlssona64db8f2007-11-27 05:51:55 +00005071 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00005072 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00005073 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00005074 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00005075 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005076 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00005077 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005078 } else
5079 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005080 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00005081 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005082
John McCall2de56d12010-08-25 11:45:40 +00005083 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005084 return false;
5085}
5086
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005087bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCall2de56d12010-08-25 11:45:40 +00005088 CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00005089 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005090
Anders Carlsson16a89042009-10-16 05:23:41 +00005091 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005092
Nate Begeman9b10da62009-06-27 22:05:55 +00005093 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5094 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00005095 if (SrcTy->isVectorType()) {
5096 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
5097 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5098 << DestTy << SrcTy << R;
John McCall2de56d12010-08-25 11:45:40 +00005099 Kind = CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00005100 return false;
5101 }
5102
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005103 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00005104 // conversion will take place first from scalar to elt type, and then
5105 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005106 if (SrcTy->isPointerType())
5107 return Diag(R.getBegin(),
5108 diag::err_invalid_conversion_between_vector_and_scalar)
5109 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00005110
5111 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5112 ImpCastExprToType(CastExpr, DestElemTy,
John McCallf3ea8cf2010-11-14 08:17:51 +00005113 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005114
John McCall2de56d12010-08-25 11:45:40 +00005115 Kind = CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00005116 return false;
5117}
5118
John McCall60d7b3a2010-08-24 06:29:42 +00005119ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005120Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005121 SourceLocation RParenLoc, Expr *castExpr) {
5122 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005123 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00005124
John McCall9d125032010-01-15 18:39:57 +00005125 TypeSourceInfo *castTInfo;
5126 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5127 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00005128 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00005129
Nate Begeman2ef13e52009-08-10 23:49:36 +00005130 // If the Expr being casted is a ParenListExpr, handle it specially.
5131 if (isa<ParenListExpr>(castExpr))
John McCall9ae2f072010-08-23 23:25:46 +00005132 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCall42f56b52010-01-18 19:35:47 +00005133 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00005134
John McCall9ae2f072010-08-23 23:25:46 +00005135 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00005136}
5137
John McCall60d7b3a2010-08-24 06:29:42 +00005138ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00005139Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005140 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005141 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00005142 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00005143 CXXCastPath BasePath;
John McCallb042fdf2010-01-15 18:56:44 +00005144 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCallf89e55a2010-11-18 06:31:45 +00005145 Kind, VK, BasePath))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005146 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00005147
John McCallf871d0c2010-08-07 06:22:56 +00005148 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +00005149 Ty->getType().getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +00005150 VK, Kind, castExpr, &BasePath, Ty,
John McCallf871d0c2010-08-07 06:22:56 +00005151 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005152}
5153
Nate Begeman2ef13e52009-08-10 23:49:36 +00005154/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5155/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005156ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005157Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005158 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5159 if (!E)
5160 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00005161
John McCall60d7b3a2010-08-24 06:29:42 +00005162 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00005163
Nate Begeman2ef13e52009-08-10 23:49:36 +00005164 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00005165 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5166 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00005167
John McCall9ae2f072010-08-23 23:25:46 +00005168 if (Result.isInvalid()) return ExprError();
5169
5170 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005171}
5172
John McCall60d7b3a2010-08-24 06:29:42 +00005173ExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00005174Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00005175 SourceLocation RParenLoc, Expr *Op,
John McCall42f56b52010-01-18 19:35:47 +00005176 TypeSourceInfo *TInfo) {
John McCall9ae2f072010-08-23 23:25:46 +00005177 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCall42f56b52010-01-18 19:35:47 +00005178 QualType Ty = TInfo->getType();
John Thompson8bb59a82010-06-30 22:55:51 +00005179 bool isAltiVecLiteral = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005180
John Thompson8bb59a82010-06-30 22:55:51 +00005181 // Check for an altivec literal,
5182 // i.e. all the elements are integer constants.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005183 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5184 if (PE->getNumExprs() == 0) {
5185 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5186 return ExprError();
5187 }
John Thompson8bb59a82010-06-30 22:55:51 +00005188 if (PE->getNumExprs() == 1) {
5189 if (!PE->getExpr(0)->getType()->isVectorType())
5190 isAltiVecLiteral = true;
5191 }
5192 else
5193 isAltiVecLiteral = true;
5194 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00005195
John Thompson8bb59a82010-06-30 22:55:51 +00005196 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
5197 // then handle it as such.
5198 if (isAltiVecLiteral) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005199 llvm::SmallVector<Expr *, 8> initExprs;
5200 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5201 initExprs.push_back(PE->getExpr(i));
5202
5203 // FIXME: This means that pretty-printing the final AST will produce curly
5204 // braces instead of the original commas.
Ted Kremenek709210f2010-04-13 23:39:13 +00005205 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5206 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00005207 initExprs.size(), RParenLoc);
5208 E->setType(Ty);
John McCall9ae2f072010-08-23 23:25:46 +00005209 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005210 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005211 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00005212 // sequence of BinOp comma operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005213 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCall9ae2f072010-08-23 23:25:46 +00005214 if (Result.isInvalid()) return ExprError();
5215 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005216 }
5217}
5218
John McCall60d7b3a2010-08-24 06:29:42 +00005219ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00005220 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005221 MultiExprArg Val,
John McCallb3d87482010-08-24 05:47:05 +00005222 ParsedType TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005223 unsigned nexprs = Val.size();
5224 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005225 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5226 Expr *expr;
5227 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5228 expr = new (Context) ParenExpr(L, R, exprs[0]);
5229 else
5230 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005231 return Owned(expr);
5232}
5233
Chandler Carruth82214a82011-02-18 23:54:50 +00005234/// \brief Emit a specialized diagnostic when one expression is a null pointer
5235/// constant and the other is not a pointer.
5236bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5237 SourceLocation QuestionLoc) {
5238 Expr *NullExpr = LHS;
5239 Expr *NonPointerExpr = RHS;
5240 Expr::NullPointerConstantKind NullKind =
5241 NullExpr->isNullPointerConstant(Context,
5242 Expr::NPC_ValueDependentIsNotNull);
5243
5244 if (NullKind == Expr::NPCK_NotNull) {
5245 NullExpr = RHS;
5246 NonPointerExpr = LHS;
5247 NullKind =
5248 NullExpr->isNullPointerConstant(Context,
5249 Expr::NPC_ValueDependentIsNotNull);
5250 }
5251
5252 if (NullKind == Expr::NPCK_NotNull)
5253 return false;
5254
5255 if (NullKind == Expr::NPCK_ZeroInteger) {
5256 // In this case, check to make sure that we got here from a "NULL"
5257 // string in the source code.
5258 NullExpr = NullExpr->IgnoreParenImpCasts();
5259 SourceManager& SM = Context.getSourceManager();
5260 SourceLocation Loc = SM.getInstantiationLoc(NullExpr->getExprLoc());
5261 unsigned Len =
5262 Lexer::MeasureTokenLength(Loc, SM, Context.getLangOptions());
5263 if (Len != 4 || memcmp(SM.getCharacterData(Loc), "NULL", 4))
5264 return false;
5265 }
5266
5267 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5268 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5269 << NonPointerExpr->getType() << DiagType
5270 << NonPointerExpr->getSourceRange();
5271 return true;
5272}
5273
Sebastian Redl28507842009-02-26 14:39:58 +00005274/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5275/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00005276/// C99 6.5.15
5277QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005278 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00005279 SourceLocation QuestionLoc) {
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005280 // If both LHS and RHS are overloaded functions, try to resolve them.
5281 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
5282 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
5283 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
5284 if (LHSResult.isInvalid())
5285 return QualType();
5286
5287 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
5288 if (RHSResult.isInvalid())
5289 return QualType();
5290
5291 LHS = LHSResult.take();
5292 RHS = RHSResult.take();
5293 }
5294
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005295 // C++ is sufficiently different to merit its own checker.
5296 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00005297 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00005298
5299 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005300 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005301
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005302 UsualUnaryConversions(Cond);
John McCall56ca35d2011-02-17 10:25:35 +00005303 UsualUnaryConversions(LHS);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005304 UsualUnaryConversions(RHS);
5305 QualType CondTy = Cond->getType();
5306 QualType LHSTy = LHS->getType();
5307 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005308
Reid Spencer5f016e22007-07-11 17:01:13 +00005309 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005310 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begeman6155d732010-09-20 22:41:17 +00005311 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5312 // Throw an error if its not either.
5313 if (getLangOptions().OpenCL) {
5314 if (!CondTy->isVectorType()) {
5315 Diag(Cond->getLocStart(),
5316 diag::err_typecheck_cond_expect_scalar_or_vector)
5317 << CondTy;
5318 return QualType();
5319 }
5320 }
5321 else {
5322 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5323 << CondTy;
5324 return QualType();
5325 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005326 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005327
Chris Lattner70d67a92008-01-06 22:42:25 +00005328 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005329 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5330 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00005331
Nate Begeman6155d732010-09-20 22:41:17 +00005332 // OpenCL: If the condition is a vector, and both operands are scalar,
5333 // attempt to implicity convert them to the vector type to act like the
5334 // built in select.
5335 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5336 // Both operands should be of scalar type.
5337 if (!LHSTy->isScalarType()) {
5338 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5339 << CondTy;
5340 return QualType();
5341 }
5342 if (!RHSTy->isScalarType()) {
5343 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5344 << CondTy;
5345 return QualType();
5346 }
5347 // Implicity convert these scalars to the type of the condition.
5348 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5349 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5350 }
5351
Chris Lattner70d67a92008-01-06 22:42:25 +00005352 // If both operands have arithmetic type, do the usual arithmetic conversions
5353 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005354 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5355 UsualArithmeticConversions(LHS, RHS);
5356 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005357 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005358
Chris Lattner70d67a92008-01-06 22:42:25 +00005359 // If both operands are the same structure or union type, the result is that
5360 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005361 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5362 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005363 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005364 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005365 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005366 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005367 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005368 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005369
Chris Lattner70d67a92008-01-06 22:42:25 +00005370 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005371 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005372 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5373 if (!LHSTy->isVoidType())
5374 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5375 << RHS->getSourceRange();
5376 if (!RHSTy->isVoidType())
5377 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5378 << LHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005379 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5380 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00005381 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00005382 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00005383 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5384 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005385 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005386 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005387 // promote the null to a pointer.
John McCalldaa8e4e2010-11-15 09:13:47 +00005388 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005389 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005390 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005391 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005392 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005393 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005394 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005395 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005396
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005397 // All objective-c pointer type analysis is done here.
5398 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5399 QuestionLoc);
5400 if (!compositeType.isNull())
5401 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005402
5403
Steve Naroff7154a772009-07-01 14:36:47 +00005404 // Handle block pointer types.
5405 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5406 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5407 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5408 QualType destType = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005409 ImpCastExprToType(LHS, destType, CK_BitCast);
5410 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005411 return destType;
5412 }
5413 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005414 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00005415 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005416 }
Steve Naroff7154a772009-07-01 14:36:47 +00005417 // We have 2 block pointer types.
5418 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5419 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005420 return LHSTy;
5421 }
Steve Naroff7154a772009-07-01 14:36:47 +00005422 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00005423 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5424 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005425
Steve Naroff7154a772009-07-01 14:36:47 +00005426 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5427 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00005428 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005429 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005430 // In this situation, we assume void* type. No especially good
5431 // reason, but this is what gcc does, and we do have to pick
5432 // to get a consistent AST.
5433 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005434 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5435 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00005436 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005437 }
Steve Naroff7154a772009-07-01 14:36:47 +00005438 // The block pointer types are compatible.
John McCall2de56d12010-08-25 11:45:40 +00005439 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5440 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00005441 return LHSTy;
5442 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005443
Steve Naroff7154a772009-07-01 14:36:47 +00005444 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5445 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5446 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00005447 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5448 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00005449
5450 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5451 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5452 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00005453 QualType destPointee
5454 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005455 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005456 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005457 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005458 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005459 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005460 return destType;
5461 }
5462 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00005463 QualType destPointee
5464 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005465 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005466 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005467 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005468 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005469 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005470 return destType;
5471 }
5472
5473 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5474 // Two identical pointer types are always compatible.
5475 return LHSTy;
5476 }
5477 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5478 rhptee.getUnqualifiedType())) {
5479 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5480 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5481 // In this situation, we assume void* type. No especially good
5482 // reason, but this is what gcc does, and we do have to pick
5483 // to get a consistent AST.
5484 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005485 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5486 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005487 return incompatTy;
5488 }
5489 // The pointer types are compatible.
5490 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5491 // differently qualified versions of compatible types, the result type is
5492 // a pointer to an appropriately qualified version of the *composite*
5493 // type.
5494 // FIXME: Need to calculate the composite type.
5495 // FIXME: Need to add qualifiers
John McCall2de56d12010-08-25 11:45:40 +00005496 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5497 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005498 return LHSTy;
5499 }
Mike Stump1eb44332009-09-09 15:08:12 +00005500
John McCall404cd162010-11-13 01:35:44 +00005501 // GCC compatibility: soften pointer/integer mismatch. Note that
5502 // null pointers have been filtered out by this point.
Steve Naroff7154a772009-07-01 14:36:47 +00005503 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5504 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5505 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005506 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005507 return RHSTy;
5508 }
5509 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5510 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5511 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005512 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005513 return LHSTy;
5514 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005515
Chandler Carruth82214a82011-02-18 23:54:50 +00005516 // Emit a better diagnostic if one of the expressions is a null pointer
5517 // constant and the other is not a pointer type. In this case, the user most
5518 // likely forgot to take the address of the other expression.
5519 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
5520 return QualType();
5521
Chris Lattner70d67a92008-01-06 22:42:25 +00005522 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005523 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5524 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005525 return QualType();
5526}
5527
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005528/// FindCompositeObjCPointerType - Helper method to find composite type of
5529/// two objective-c pointer types of the two input expressions.
5530QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5531 SourceLocation QuestionLoc) {
5532 QualType LHSTy = LHS->getType();
5533 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005534
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005535 // Handle things like Class and struct objc_class*. Here we case the result
5536 // to the pseudo-builtin, because that will be implicitly cast back to the
5537 // redefinition type if an attempt is made to access its fields.
5538 if (LHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005539 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005540 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005541 return LHSTy;
5542 }
5543 if (RHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005544 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005545 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005546 return RHSTy;
5547 }
5548 // And the same for struct objc_object* / id
5549 if (LHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005550 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005551 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005552 return LHSTy;
5553 }
5554 if (RHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005555 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005556 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005557 return RHSTy;
5558 }
5559 // And the same for struct objc_selector* / SEL
5560 if (Context.isObjCSelType(LHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00005561 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005562 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005563 return LHSTy;
5564 }
5565 if (Context.isObjCSelType(RHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00005566 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005567 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005568 return RHSTy;
5569 }
5570 // Check constraints for Objective-C object pointers types.
5571 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005572
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005573 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5574 // Two identical object pointer types are always compatible.
5575 return LHSTy;
5576 }
5577 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5578 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5579 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005580
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005581 // If both operands are interfaces and either operand can be
5582 // assigned to the other, use that type as the composite
5583 // type. This allows
5584 // xxx ? (A*) a : (B*) b
5585 // where B is a subclass of A.
5586 //
5587 // Additionally, as for assignment, if either type is 'id'
5588 // allow silent coercion. Finally, if the types are
5589 // incompatible then make sure to use 'id' as the composite
5590 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005591
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005592 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5593 // It could return the composite type.
5594 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5595 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5596 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5597 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5598 } else if ((LHSTy->isObjCQualifiedIdType() ||
5599 RHSTy->isObjCQualifiedIdType()) &&
5600 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5601 // Need to handle "id<xx>" explicitly.
5602 // GCC allows qualified id and any Objective-C type to devolve to
5603 // id. Currently localizing to here until clear this should be
5604 // part of ObjCQualifiedIdTypesAreCompatible.
5605 compositeType = Context.getObjCIdType();
5606 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5607 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005608 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005609 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5610 ;
5611 else {
5612 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5613 << LHSTy << RHSTy
5614 << LHS->getSourceRange() << RHS->getSourceRange();
5615 QualType incompatTy = Context.getObjCIdType();
John McCall2de56d12010-08-25 11:45:40 +00005616 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5617 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005618 return incompatTy;
5619 }
5620 // The object pointer types are compatible.
John McCall2de56d12010-08-25 11:45:40 +00005621 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5622 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005623 return compositeType;
5624 }
5625 // Check Objective-C object pointer types and 'void *'
5626 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5627 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5628 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5629 QualType destPointee
5630 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5631 QualType destType = Context.getPointerType(destPointee);
5632 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005633 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005634 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005635 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005636 return destType;
5637 }
5638 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5639 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5640 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5641 QualType destPointee
5642 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5643 QualType destType = Context.getPointerType(destPointee);
5644 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005645 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005646 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005647 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005648 return destType;
5649 }
5650 return QualType();
5651}
5652
Steve Narofff69936d2007-09-16 03:34:24 +00005653/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005654/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005655ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005656 SourceLocation ColonLoc,
5657 Expr *CondExpr, Expr *LHSExpr,
5658 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005659 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5660 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005661 OpaqueValueExpr *opaqueValue = 0;
5662 Expr *commonExpr = 0;
5663 if (LHSExpr == 0) {
5664 commonExpr = CondExpr;
5665
5666 // We usually want to apply unary conversions *before* saving, except
5667 // in the special case of a C++ l-value conditional.
5668 if (!(getLangOptions().CPlusPlus
5669 && !commonExpr->isTypeDependent()
5670 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5671 && commonExpr->isGLValue()
5672 && commonExpr->isOrdinaryOrBitFieldObject()
5673 && RHSExpr->isOrdinaryOrBitFieldObject()
5674 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5675 UsualUnaryConversions(commonExpr);
5676 }
5677
5678 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5679 commonExpr->getType(),
5680 commonExpr->getValueKind(),
5681 commonExpr->getObjectKind());
5682 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005683 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005684
John McCallf89e55a2010-11-18 06:31:45 +00005685 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005686 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian1fb019b2010-09-18 19:38:38 +00005687 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCall56ca35d2011-02-17 10:25:35 +00005688 VK, OK, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00005689 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005690 return ExprError();
5691
John McCall56ca35d2011-02-17 10:25:35 +00005692 if (!commonExpr)
5693 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
5694 LHSExpr, ColonLoc,
5695 RHSExpr, result, VK, OK));
5696
5697 return Owned(new (Context)
5698 BinaryConditionalOperator(commonExpr, opaqueValue, CondExpr, LHSExpr,
5699 RHSExpr, QuestionLoc, ColonLoc, result, VK, OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005700}
5701
John McCalle4be87e2011-01-31 23:13:11 +00005702// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005703// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005704// routine is it effectively iqnores the qualifiers on the top level pointee.
5705// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5706// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005707static Sema::AssignConvertType
5708checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5709 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5710 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005711
Reid Spencer5f016e22007-07-11 17:01:13 +00005712 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005713 const Type *lhptee, *rhptee;
5714 Qualifiers lhq, rhq;
5715 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5716 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005717
John McCalle4be87e2011-01-31 23:13:11 +00005718 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005719
5720 // C99 6.5.16.1p1: This following citation is common to constraints
5721 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5722 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005723 Qualifiers lq;
5724
5725 if (!lhq.compatiblyIncludes(rhq)) {
5726 // Treat address-space mismatches as fatal. TODO: address subspaces
5727 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5728 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5729
5730 // For GCC compatibility, other qualifier mismatches are treated
5731 // as still compatible in C.
5732 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5733 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005734
Mike Stumpeed9cac2009-02-19 03:04:26 +00005735 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5736 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005737 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005738 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005739 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005740 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005741
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005742 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005743 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005744 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005745 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005746
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005747 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005748 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005749 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005750
5751 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005752 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005753 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005754 }
John McCall86c05f32011-02-01 00:10:29 +00005755
Mike Stumpeed9cac2009-02-19 03:04:26 +00005756 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005757 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005758 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5759 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005760 // Check if the pointee types are compatible ignoring the sign.
5761 // We explicitly check for char so that we catch "char" vs
5762 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005763 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005764 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005765 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005766 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005767
Chris Lattner6a2b9262009-10-17 20:33:28 +00005768 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005769 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005770 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005771 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005772
John McCall86c05f32011-02-01 00:10:29 +00005773 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005774 // Types are compatible ignoring the sign. Qualifier incompatibility
5775 // takes priority over sign incompatibility because the sign
5776 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005777 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005778 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005779
John McCalle4be87e2011-01-31 23:13:11 +00005780 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005781 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005782
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005783 // If we are a multi-level pointer, it's possible that our issue is simply
5784 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5785 // the eventual target type is the same and the pointers have the same
5786 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005787 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005788 do {
John McCall86c05f32011-02-01 00:10:29 +00005789 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5790 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005791 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005792
John McCall86c05f32011-02-01 00:10:29 +00005793 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005794 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005795 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005796
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005797 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005798 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005799 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005800 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005801}
5802
John McCalle4be87e2011-01-31 23:13:11 +00005803/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005804/// block pointer types are compatible or whether a block and normal pointer
5805/// are compatible. It is more restrict than comparing two function pointer
5806// types.
John McCalle4be87e2011-01-31 23:13:11 +00005807static Sema::AssignConvertType
5808checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5809 QualType rhsType) {
5810 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5811 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5812
Steve Naroff1c7d0672008-09-04 15:10:53 +00005813 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005814
Steve Naroff1c7d0672008-09-04 15:10:53 +00005815 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00005816 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5817 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005818
John McCalle4be87e2011-01-31 23:13:11 +00005819 // In C++, the types have to match exactly.
5820 if (S.getLangOptions().CPlusPlus)
5821 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005822
John McCalle4be87e2011-01-31 23:13:11 +00005823 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005824
Steve Naroff1c7d0672008-09-04 15:10:53 +00005825 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005826 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5827 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005828
John McCalle4be87e2011-01-31 23:13:11 +00005829 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5830 return Sema::IncompatibleBlockPointer;
5831
Steve Naroff1c7d0672008-09-04 15:10:53 +00005832 return ConvTy;
5833}
5834
John McCalle4be87e2011-01-31 23:13:11 +00005835/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005836/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005837static Sema::AssignConvertType
5838checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5839 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5840 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5841
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005842 if (lhsType->isObjCBuiltinType()) {
5843 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005844 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5845 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005846 return Sema::IncompatiblePointer;
5847 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005848 }
5849 if (rhsType->isObjCBuiltinType()) {
5850 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005851 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5852 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005853 return Sema::IncompatiblePointer;
5854 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005855 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005856 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005857 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005858 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005859 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005860
John McCalle4be87e2011-01-31 23:13:11 +00005861 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5862 return Sema::CompatiblePointerDiscardsQualifiers;
5863
5864 if (S.Context.typesAreCompatible(lhsType, rhsType))
5865 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005866 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005867 return Sema::IncompatibleObjCQualifiedId;
5868 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005869}
5870
John McCall1c23e912010-11-16 02:32:08 +00005871Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005872Sema::CheckAssignmentConstraints(SourceLocation Loc,
5873 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00005874 // Fake up an opaque expression. We don't actually care about what
5875 // cast operations are required, so if CheckAssignmentConstraints
5876 // adds casts to this they'll be wasted, but fortunately that doesn't
5877 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00005878 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John McCall1c23e912010-11-16 02:32:08 +00005879 Expr *rhsPtr = &rhs;
5880 CastKind K = CK_Invalid;
5881
5882 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5883}
5884
Mike Stumpeed9cac2009-02-19 03:04:26 +00005885/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5886/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005887/// pointers. Here are some objectionable examples that GCC considers warnings:
5888///
5889/// int a, *pint;
5890/// short *pshort;
5891/// struct foo *pfoo;
5892///
5893/// pint = pshort; // warning: assignment from incompatible pointer type
5894/// a = pint; // warning: assignment makes integer from pointer without a cast
5895/// pint = a; // warning: assignment makes pointer from integer without a cast
5896/// pint = pfoo; // warning: assignment from incompatible pointer type
5897///
5898/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005899/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005900///
John McCalldaa8e4e2010-11-15 09:13:47 +00005901/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005902Sema::AssignConvertType
John McCall1c23e912010-11-16 02:32:08 +00005903Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00005904 CastKind &Kind) {
John McCall1c23e912010-11-16 02:32:08 +00005905 QualType rhsType = rhs->getType();
5906
Chris Lattnerfc144e22008-01-04 23:18:45 +00005907 // Get canonical types. We're not formatting these types, just comparing
5908 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005909 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5910 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005911
John McCallb6cfa242011-01-31 22:28:28 +00005912 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00005913 if (lhsType == rhsType) {
5914 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005915 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005916 }
5917
Douglas Gregor9d293df2008-10-28 00:22:11 +00005918 // If the left-hand side is a reference type, then we are in a
5919 // (rare!) case where we've allowed the use of references in C,
5920 // e.g., as a parameter type in a built-in function. In this case,
5921 // just make sure that the type referenced is compatible with the
5922 // right-hand side type. The caller is responsible for adjusting
5923 // lhsType so that the resulting expression does not have reference
5924 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005925 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005926 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5927 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005928 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005929 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005930 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005931 }
John McCallb6cfa242011-01-31 22:28:28 +00005932
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005933 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5934 // to the same ExtVector type.
5935 if (lhsType->isExtVectorType()) {
5936 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005937 return Incompatible;
5938 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005939 // CK_VectorSplat does T -> vector T, so first cast to the
5940 // element type.
5941 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5942 if (elType != rhsType) {
5943 Kind = PrepareScalarCast(*this, rhs, elType);
5944 ImpCastExprToType(rhs, elType, Kind);
5945 }
5946 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005947 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005948 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005949 }
Mike Stump1eb44332009-09-09 15:08:12 +00005950
John McCallb6cfa242011-01-31 22:28:28 +00005951 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005952 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00005953 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005954 // Allow assignments of an AltiVec vector type to an equivalent GCC
5955 // vector type and vice versa
5956 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5957 Kind = CK_BitCast;
5958 return Compatible;
5959 }
5960
Douglas Gregor255210e2010-08-06 10:14:59 +00005961 // If we are allowing lax vector conversions, and LHS and RHS are both
5962 // vectors, the total size only needs to be the same. This is a bitcast;
5963 // no bits are changed but the result type is different.
5964 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005965 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005966 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005967 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005968 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005969 }
5970 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005971 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005972
John McCallb6cfa242011-01-31 22:28:28 +00005973 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00005974 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005975 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00005976 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005977 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005978 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005979
John McCallb6cfa242011-01-31 22:28:28 +00005980 // Conversions to normal pointers.
5981 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5982 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00005983 if (isa<PointerType>(rhsType)) {
5984 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00005985 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005986 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005987
John McCallb6cfa242011-01-31 22:28:28 +00005988 // int -> T*
5989 if (rhsType->isIntegerType()) {
5990 Kind = CK_IntegralToPointer; // FIXME: null?
5991 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005992 }
John McCallb6cfa242011-01-31 22:28:28 +00005993
5994 // C pointers are not compatible with ObjC object pointers,
5995 // with two exceptions:
5996 if (isa<ObjCObjectPointerType>(rhsType)) {
5997 // - conversions to void*
5998 if (lhsPointer->getPointeeType()->isVoidType()) {
5999 Kind = CK_AnyPointerToObjCPointerCast;
6000 return Compatible;
6001 }
6002
6003 // - conversions from 'Class' to the redefinition type
6004 if (rhsType->isObjCClassType() &&
6005 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006006 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006007 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006008 }
Steve Naroffb4406862008-09-29 18:10:17 +00006009
John McCallb6cfa242011-01-31 22:28:28 +00006010 Kind = CK_BitCast;
6011 return IncompatiblePointer;
6012 }
6013
6014 // U^ -> void*
6015 if (rhsType->getAs<BlockPointerType>()) {
6016 if (lhsPointer->getPointeeType()->isVoidType()) {
6017 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006018 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006019 }
Steve Naroffb4406862008-09-29 18:10:17 +00006020 }
John McCallb6cfa242011-01-31 22:28:28 +00006021
Steve Naroff1c7d0672008-09-04 15:10:53 +00006022 return Incompatible;
6023 }
6024
John McCallb6cfa242011-01-31 22:28:28 +00006025 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00006026 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006027 // U^ -> T^
6028 if (rhsType->isBlockPointerType()) {
6029 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00006030 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006031 }
6032
6033 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006034 if (rhsType->isIntegerType()) {
6035 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00006036 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006037 }
6038
John McCallb6cfa242011-01-31 22:28:28 +00006039 // id -> T^
6040 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6041 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006042 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006043 }
Steve Naroffb4406862008-09-29 18:10:17 +00006044
John McCallb6cfa242011-01-31 22:28:28 +00006045 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006046 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00006047 if (RHSPT->getPointeeType()->isVoidType()) {
6048 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006049 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006050 }
John McCalldaa8e4e2010-11-15 09:13:47 +00006051
Chris Lattnerfc144e22008-01-04 23:18:45 +00006052 return Incompatible;
6053 }
6054
John McCallb6cfa242011-01-31 22:28:28 +00006055 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00006056 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006057 // A* -> B*
6058 if (rhsType->isObjCObjectPointerType()) {
6059 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006060 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006061 }
6062
6063 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00006064 if (rhsType->isIntegerType()) {
6065 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00006066 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006067 }
6068
John McCallb6cfa242011-01-31 22:28:28 +00006069 // In general, C pointers are not compatible with ObjC object pointers,
6070 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00006071 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006072 // - conversions from 'void*'
6073 if (rhsType->isVoidPointerType()) {
6074 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006075 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006076 }
6077
6078 // - conversions to 'Class' from its redefinition type
6079 if (lhsType->isObjCClassType() &&
6080 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6081 Kind = CK_BitCast;
6082 return Compatible;
6083 }
6084
6085 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006086 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006087 }
John McCallb6cfa242011-01-31 22:28:28 +00006088
6089 // T^ -> A*
6090 if (rhsType->isBlockPointerType()) {
6091 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00006092 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006093 }
6094
Steve Naroff14108da2009-07-10 23:34:53 +00006095 return Incompatible;
6096 }
John McCallb6cfa242011-01-31 22:28:28 +00006097
6098 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00006099 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006100 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006101 if (lhsType == Context.BoolTy) {
6102 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006103 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006104 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006105
John McCallb6cfa242011-01-31 22:28:28 +00006106 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006107 if (lhsType->isIntegerType()) {
6108 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006109 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006110 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006111
Chris Lattnerfc144e22008-01-04 23:18:45 +00006112 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00006113 }
John McCallb6cfa242011-01-31 22:28:28 +00006114
6115 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00006116 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006117 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006118 if (lhsType == Context.BoolTy) {
6119 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00006120 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006121 }
Steve Naroff14108da2009-07-10 23:34:53 +00006122
John McCallb6cfa242011-01-31 22:28:28 +00006123 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006124 if (lhsType->isIntegerType()) {
6125 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00006126 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006127 }
6128
Steve Naroff14108da2009-07-10 23:34:53 +00006129 return Incompatible;
6130 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006131
John McCallb6cfa242011-01-31 22:28:28 +00006132 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00006133 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006134 if (Context.typesAreCompatible(lhsType, rhsType)) {
6135 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00006136 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006137 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006138 }
John McCallb6cfa242011-01-31 22:28:28 +00006139
Reid Spencer5f016e22007-07-11 17:01:13 +00006140 return Incompatible;
6141}
6142
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006143/// \brief Constructs a transparent union from an expression that is
6144/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00006145static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006146 QualType UnionType, FieldDecl *Field) {
6147 // Build an initializer list that designates the appropriate member
6148 // of the transparent union.
Ted Kremenek709210f2010-04-13 23:39:13 +00006149 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00006150 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006151 SourceLocation());
6152 Initializer->setType(UnionType);
6153 Initializer->setInitializedFieldInUnion(Field);
6154
6155 // Build a compound literal constructing a value of the transparent
6156 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00006157 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall1d7d8d62010-01-19 22:33:45 +00006158 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCallf89e55a2010-11-18 06:31:45 +00006159 VK_RValue, Initializer, false);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006160}
6161
6162Sema::AssignConvertType
6163Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
6164 QualType FromType = rExpr->getType();
6165
Mike Stump1eb44332009-09-09 15:08:12 +00006166 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006167 // transparent_union GCC extension.
6168 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006169 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006170 return Incompatible;
6171
6172 // The field to initialize within the transparent union.
6173 RecordDecl *UD = UT->getDecl();
6174 FieldDecl *InitField = 0;
6175 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006176 for (RecordDecl::field_iterator it = UD->field_begin(),
6177 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006178 it != itend; ++it) {
6179 if (it->getType()->isPointerType()) {
6180 // If the transparent union contains a pointer type, we allow:
6181 // 1) void pointer
6182 // 2) null pointer constant
6183 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00006184 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCall2de56d12010-08-25 11:45:40 +00006185 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006186 InitField = *it;
6187 break;
6188 }
Mike Stump1eb44332009-09-09 15:08:12 +00006189
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006190 if (rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006191 Expr::NPC_ValueDependentIsNull)) {
John McCall404cd162010-11-13 01:35:44 +00006192 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006193 InitField = *it;
6194 break;
6195 }
6196 }
6197
John McCall1c23e912010-11-16 02:32:08 +00006198 Expr *rhs = rExpr;
John McCalldaa8e4e2010-11-15 09:13:47 +00006199 CastKind Kind = CK_Invalid;
John McCall1c23e912010-11-16 02:32:08 +00006200 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006201 == Compatible) {
John McCall1c23e912010-11-16 02:32:08 +00006202 ImpCastExprToType(rhs, it->getType(), Kind);
6203 rExpr = rhs;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006204 InitField = *it;
6205 break;
6206 }
6207 }
6208
6209 if (!InitField)
6210 return Incompatible;
6211
6212 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
6213 return Compatible;
6214}
6215
Chris Lattner5cf216b2008-01-04 18:04:52 +00006216Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00006217Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00006218 if (getLangOptions().CPlusPlus) {
6219 if (!lhsType->isRecordType()) {
6220 // C++ 5.17p3: If the left operand is not of class type, the
6221 // expression is implicitly converted (C++ 4) to the
6222 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00006223 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00006224 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00006225 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00006226 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00006227 }
6228
6229 // FIXME: Currently, we fall through and treat C++ classes like C
6230 // structures.
John McCallf6a16482010-12-04 03:47:34 +00006231 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00006232
Steve Naroff529a4ad2007-11-27 17:58:44 +00006233 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6234 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00006235 if ((lhsType->isPointerType() ||
6236 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00006237 lhsType->isBlockPointerType())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006238 && rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006239 Expr::NPC_ValueDependentIsNull)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006240 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00006241 return Compatible;
6242 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006243
Chris Lattner943140e2007-10-16 02:55:40 +00006244 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00006245 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00006246 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00006247 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00006248 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00006249 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00006250 if (!lhsType->isReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00006251 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00006252
John McCalldaa8e4e2010-11-15 09:13:47 +00006253 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006254 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00006255 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006256
Steve Narofff1120de2007-08-24 22:33:52 +00006257 // C99 6.5.16.1p2: The value of the right operand is converted to the
6258 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006259 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6260 // so that we can use references in built-in functions even in C.
6261 // The getNonReferenceType() call makes sure that the resulting expression
6262 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006263 if (result != Incompatible && rExpr->getType() != lhsType)
John McCalldaa8e4e2010-11-15 09:13:47 +00006264 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006265 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006266}
6267
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006268QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006269 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00006270 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006271 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00006272 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006273}
6274
Chris Lattner7ef655a2010-01-12 21:23:57 +00006275QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00006276 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006277 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00006278 QualType lhsType =
6279 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
6280 QualType rhsType =
6281 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006282
Nate Begemanbe2341d2008-07-14 18:02:46 +00006283 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006284 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00006285 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006286
Nate Begemanbe2341d2008-07-14 18:02:46 +00006287 // Handle the case of a vector & extvector type of the same size and element
6288 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006289 if (getLangOptions().LaxVectorConversions) {
John McCall183700f2009-09-21 23:43:11 +00006290 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth629f9e42010-08-30 07:36:24 +00006291 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006292 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006293 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregor26bcf672010-05-19 03:21:00 +00006294 if (lhsType->isExtVectorType()) {
John McCall2de56d12010-08-25 11:45:40 +00006295 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006296 return lhsType;
6297 }
6298
John McCall2de56d12010-08-25 11:45:40 +00006299 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006300 return rhsType;
Eric Christophere84f9eb2010-08-26 00:42:16 +00006301 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6302 // If we are allowing lax vector conversions, and LHS and RHS are both
6303 // vectors, the total size only needs to be the same. This is a
6304 // bitcast; no bits are changed but the result type is different.
6305 ImpCastExprToType(rex, lhsType, CK_BitCast);
6306 return lhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006307 }
Eric Christophere84f9eb2010-08-26 00:42:16 +00006308 }
Chandler Carruth629f9e42010-08-30 07:36:24 +00006309 }
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006310 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006311
Douglas Gregor255210e2010-08-06 10:14:59 +00006312 // Handle the case of equivalent AltiVec and GCC vector types
6313 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6314 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCall2de56d12010-08-25 11:45:40 +00006315 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00006316 return rhsType;
6317 }
6318
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006319 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6320 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6321 bool swapped = false;
6322 if (rhsType->isExtVectorType()) {
6323 swapped = true;
6324 std::swap(rex, lex);
6325 std::swap(rhsType, lhsType);
6326 }
Mike Stump1eb44332009-09-09 15:08:12 +00006327
Nate Begemandde25982009-06-28 19:12:57 +00006328 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00006329 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006330 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00006331 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006332 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6333 if (order > 0)
6334 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
6335 if (order >= 0) {
6336 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006337 if (swapped) std::swap(rex, lex);
6338 return lhsType;
6339 }
6340 }
6341 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6342 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006343 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6344 if (order > 0)
6345 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
6346 if (order >= 0) {
6347 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006348 if (swapped) std::swap(rex, lex);
6349 return lhsType;
6350 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006351 }
6352 }
Mike Stump1eb44332009-09-09 15:08:12 +00006353
Nate Begemandde25982009-06-28 19:12:57 +00006354 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006355 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00006356 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006357 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006358 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006359}
6360
Chris Lattner7ef655a2010-01-12 21:23:57 +00006361QualType Sema::CheckMultiplyDivideOperands(
6362 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00006363 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006364 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006365
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006366 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006367
Chris Lattner7ef655a2010-01-12 21:23:57 +00006368 if (!lex->getType()->isArithmeticType() ||
6369 !rex->getType()->isArithmeticType())
6370 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006371
Chris Lattner7ef655a2010-01-12 21:23:57 +00006372 // Check for division by zero.
6373 if (isDiv &&
6374 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006375 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattnercb329c52010-01-12 21:30:55 +00006376 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006377
Chris Lattner7ef655a2010-01-12 21:23:57 +00006378 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006379}
6380
Chris Lattner7ef655a2010-01-12 21:23:57 +00006381QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00006382 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00006383 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006384 if (lex->getType()->hasIntegerRepresentation() &&
6385 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar523aa602009-01-05 22:55:36 +00006386 return CheckVectorOperands(Loc, lex, rex);
6387 return InvalidOperands(Loc, lex, rex);
6388 }
Steve Naroff90045e82007-07-13 23:32:42 +00006389
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006390 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006391
Chris Lattner7ef655a2010-01-12 21:23:57 +00006392 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6393 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006394
Chris Lattner7ef655a2010-01-12 21:23:57 +00006395 // Check for remainder by zero.
6396 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattnercb329c52010-01-12 21:30:55 +00006397 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
6398 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006399
Chris Lattner7ef655a2010-01-12 21:23:57 +00006400 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006401}
6402
Chris Lattner7ef655a2010-01-12 21:23:57 +00006403QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00006404 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006405 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6406 QualType compType = CheckVectorOperands(Loc, lex, rex);
6407 if (CompLHSTy) *CompLHSTy = compType;
6408 return compType;
6409 }
Steve Naroff49b45262007-07-13 16:58:59 +00006410
Eli Friedmanab3a8522009-03-28 01:22:36 +00006411 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006412
Reid Spencer5f016e22007-07-11 17:01:13 +00006413 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00006414 if (lex->getType()->isArithmeticType() &&
6415 rex->getType()->isArithmeticType()) {
6416 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006417 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006418 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006419
Eli Friedmand72d16e2008-05-18 18:08:51 +00006420 // Put any potential pointer into PExp
6421 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006422 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006423 std::swap(PExp, IExp);
6424
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006425 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006426
Eli Friedmand72d16e2008-05-18 18:08:51 +00006427 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00006428 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00006429
Chris Lattnerb5f15622009-04-24 23:50:08 +00006430 // Check for arithmetic on pointers to incomplete types.
6431 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006432 if (getLangOptions().CPlusPlus) {
6433 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006434 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006435 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006436 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006437
6438 // GNU extension: arithmetic on pointer to void
6439 Diag(Loc, diag::ext_gnu_void_ptr)
6440 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00006441 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006442 if (getLangOptions().CPlusPlus) {
6443 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6444 << lex->getType() << lex->getSourceRange();
6445 return QualType();
6446 }
6447
6448 // GNU extension: arithmetic on pointer to function
6449 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6450 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00006451 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00006452 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00006453 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00006454 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00006455 PExp->getType()->isObjCObjectPointerType()) &&
6456 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00006457 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6458 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006459 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00006460 return QualType();
6461 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00006462 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006463 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006464 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6465 << PointeeTy << PExp->getSourceRange();
6466 return QualType();
6467 }
Mike Stump1eb44332009-09-09 15:08:12 +00006468
Eli Friedmanab3a8522009-03-28 01:22:36 +00006469 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00006470 QualType LHSTy = Context.isPromotableBitField(lex);
6471 if (LHSTy.isNull()) {
6472 LHSTy = lex->getType();
6473 if (LHSTy->isPromotableIntegerType())
6474 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00006475 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00006476 *CompLHSTy = LHSTy;
6477 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00006478 return PExp->getType();
6479 }
6480 }
6481
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006482 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006483}
6484
Chris Lattnereca7be62008-04-07 05:30:13 +00006485// C99 6.5.6
6486QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006487 SourceLocation Loc, QualType* CompLHSTy) {
6488 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6489 QualType compType = CheckVectorOperands(Loc, lex, rex);
6490 if (CompLHSTy) *CompLHSTy = compType;
6491 return compType;
6492 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006493
Eli Friedmanab3a8522009-03-28 01:22:36 +00006494 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006495
Chris Lattner6e4ab612007-12-09 21:53:25 +00006496 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006497
Chris Lattner6e4ab612007-12-09 21:53:25 +00006498 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00006499 if (lex->getType()->isArithmeticType()
6500 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006501 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006502 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006503 }
Mike Stump1eb44332009-09-09 15:08:12 +00006504
Chris Lattner6e4ab612007-12-09 21:53:25 +00006505 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006506 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00006507 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006508
Douglas Gregore7450f52009-03-24 19:52:54 +00006509 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00006510
Douglas Gregore7450f52009-03-24 19:52:54 +00006511 bool ComplainAboutVoid = false;
6512 Expr *ComplainAboutFunc = 0;
6513 if (lpointee->isVoidType()) {
6514 if (getLangOptions().CPlusPlus) {
6515 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6516 << lex->getSourceRange() << rex->getSourceRange();
6517 return QualType();
6518 }
6519
6520 // GNU C extension: arithmetic on pointer to void
6521 ComplainAboutVoid = true;
6522 } else if (lpointee->isFunctionType()) {
6523 if (getLangOptions().CPlusPlus) {
6524 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00006525 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006526 return QualType();
6527 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006528
6529 // GNU C extension: arithmetic on pointer to function
6530 ComplainAboutFunc = lex;
6531 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006532 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00006533 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00006534 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006535 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00006536 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006537
Chris Lattnerb5f15622009-04-24 23:50:08 +00006538 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006539 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006540 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6541 << lpointee << lex->getSourceRange();
6542 return QualType();
6543 }
Mike Stump1eb44332009-09-09 15:08:12 +00006544
Chris Lattner6e4ab612007-12-09 21:53:25 +00006545 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00006546 if (rex->getType()->isIntegerType()) {
6547 if (ComplainAboutVoid)
6548 Diag(Loc, diag::ext_gnu_void_ptr)
6549 << lex->getSourceRange() << rex->getSourceRange();
6550 if (ComplainAboutFunc)
6551 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00006552 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00006553 << ComplainAboutFunc->getSourceRange();
6554
Eli Friedmanab3a8522009-03-28 01:22:36 +00006555 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006556 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006557 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006558
Chris Lattner6e4ab612007-12-09 21:53:25 +00006559 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006560 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006561 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006562
Douglas Gregore7450f52009-03-24 19:52:54 +00006563 // RHS must be a completely-type object type.
6564 // Handle the GNU void* extension.
6565 if (rpointee->isVoidType()) {
6566 if (getLangOptions().CPlusPlus) {
6567 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6568 << lex->getSourceRange() << rex->getSourceRange();
6569 return QualType();
6570 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006571
Douglas Gregore7450f52009-03-24 19:52:54 +00006572 ComplainAboutVoid = true;
6573 } else if (rpointee->isFunctionType()) {
6574 if (getLangOptions().CPlusPlus) {
6575 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00006576 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006577 return QualType();
6578 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006579
6580 // GNU extension: arithmetic on pointer to function
6581 if (!ComplainAboutFunc)
6582 ComplainAboutFunc = rex;
6583 } else if (!rpointee->isDependentType() &&
6584 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00006585 PDiag(diag::err_typecheck_sub_ptr_object)
6586 << rex->getSourceRange()
6587 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00006588 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006589
Eli Friedman88d936b2009-05-16 13:54:38 +00006590 if (getLangOptions().CPlusPlus) {
6591 // Pointee types must be the same: C++ [expr.add]
6592 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6593 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6594 << lex->getType() << rex->getType()
6595 << lex->getSourceRange() << rex->getSourceRange();
6596 return QualType();
6597 }
6598 } else {
6599 // Pointee types must be compatible C99 6.5.6p3
6600 if (!Context.typesAreCompatible(
6601 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6602 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6603 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6604 << lex->getType() << rex->getType()
6605 << lex->getSourceRange() << rex->getSourceRange();
6606 return QualType();
6607 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006608 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006609
Douglas Gregore7450f52009-03-24 19:52:54 +00006610 if (ComplainAboutVoid)
6611 Diag(Loc, diag::ext_gnu_void_ptr)
6612 << lex->getSourceRange() << rex->getSourceRange();
6613 if (ComplainAboutFunc)
6614 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00006615 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00006616 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006617
6618 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006619 return Context.getPointerDiffType();
6620 }
6621 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006622
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006623 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006624}
6625
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006626static bool isScopedEnumerationType(QualType T) {
6627 if (const EnumType *ET = dyn_cast<EnumType>(T))
6628 return ET->getDecl()->isScoped();
6629 return false;
6630}
6631
Chris Lattnereca7be62008-04-07 05:30:13 +00006632// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006633QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00006634 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00006635 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregorf6094622010-07-23 15:58:24 +00006636 if (!lex->getType()->hasIntegerRepresentation() ||
6637 !rex->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006638 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006639
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006640 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6641 // hasIntegerRepresentation() above instead of this.
6642 if (isScopedEnumerationType(lex->getType()) ||
6643 isScopedEnumerationType(rex->getType())) {
6644 return InvalidOperands(Loc, lex, rex);
6645 }
6646
Nate Begeman2207d792009-10-25 02:26:48 +00006647 // Vector shifts promote their scalar inputs to vector type.
6648 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6649 return CheckVectorOperands(Loc, lex, rex);
6650
Chris Lattnerca5eede2007-12-12 05:47:28 +00006651 // Shifts don't perform usual arithmetic conversions, they just do integer
6652 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006653
John McCall1bc80af2010-12-16 19:28:59 +00006654 // For the LHS, do usual unary conversions, but then reset them away
6655 // if this is a compound assignment.
6656 Expr *old_lex = lex;
6657 UsualUnaryConversions(lex);
6658 QualType LHSTy = lex->getType();
6659 if (isCompAssign) lex = old_lex;
6660
6661 // The RHS is simpler.
Chris Lattnerca5eede2007-12-12 05:47:28 +00006662 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006663
Ryan Flynnd0439682009-08-07 16:20:20 +00006664 // Sanity-check shift operands
6665 llvm::APSInt Right;
6666 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00006667 if (!rex->isValueDependent() &&
6668 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00006669 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00006670 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6671 else {
6672 llvm::APInt LeftBits(Right.getBitWidth(),
6673 Context.getTypeSize(lex->getType()));
6674 if (Right.uge(LeftBits))
6675 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6676 }
6677 }
6678
Chris Lattnerca5eede2007-12-12 05:47:28 +00006679 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00006680 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006681}
6682
Chandler Carruth99919472010-07-10 12:30:03 +00006683static bool IsWithinTemplateSpecialization(Decl *D) {
6684 if (DeclContext *DC = D->getDeclContext()) {
6685 if (isa<ClassTemplateSpecializationDecl>(DC))
6686 return true;
6687 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6688 return FD->isFunctionTemplateSpecialization();
6689 }
6690 return false;
6691}
6692
Douglas Gregor0c6db942009-05-04 06:07:12 +00006693// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006694QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00006695 unsigned OpaqueOpc, bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00006696 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006697
Chris Lattner02dd4b12009-12-05 05:40:13 +00006698 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00006699 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006700 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006701
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006702 QualType lType = lex->getType();
6703 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006704
Chandler Carruth543cb652011-02-17 08:37:06 +00006705 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6706 Expr *RHSStripped = rex->IgnoreParenImpCasts();
6707 QualType LHSStrippedType = LHSStripped->getType();
6708 QualType RHSStrippedType = RHSStripped->getType();
6709
6710 // Two different enums will raise a warning when compared.
6711 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6712 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6713 if (LHSEnumType->getDecl()->getIdentifier() &&
6714 RHSEnumType->getDecl()->getIdentifier() &&
6715 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6716 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6717 << LHSStrippedType << RHSStrippedType
6718 << lex->getSourceRange() << rex->getSourceRange();
6719 }
6720 }
6721 }
6722
Douglas Gregor8eee1192010-06-22 22:12:46 +00006723 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006724 !(lType->isBlockPointerType() && isRelational) &&
6725 !lex->getLocStart().isMacroID() &&
6726 !rex->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006727 // For non-floating point types, check for self-comparisons of the form
6728 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6729 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006730 //
6731 // NOTE: Don't warn about comparison expressions resulting from macro
6732 // expansion. Also don't warn about comparisons which are only self
6733 // comparisons within a template specialization. The warnings should catch
6734 // obvious cases in the definition of the template anyways. The idea is to
6735 // warn when the typed comparison operator will always evaluate to the same
6736 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006737 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006738 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006739 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006740 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006741 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6742 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006743 << (Opc == BO_EQ
6744 || Opc == BO_LE
6745 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00006746 } else if (lType->isArrayType() && rType->isArrayType() &&
6747 !DRL->getDecl()->getType()->isReferenceType() &&
6748 !DRR->getDecl()->getType()->isReferenceType()) {
6749 // what is it always going to eval to?
6750 char always_evals_to;
6751 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006752 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006753 always_evals_to = 0; // false
6754 break;
John McCall2de56d12010-08-25 11:45:40 +00006755 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006756 always_evals_to = 1; // true
6757 break;
6758 default:
6759 // best we can say is 'a constant'
6760 always_evals_to = 2; // e.g. array1 <= array2
6761 break;
6762 }
6763 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6764 << 1 // array
6765 << always_evals_to);
6766 }
6767 }
Chandler Carruth99919472010-07-10 12:30:03 +00006768 }
Mike Stump1eb44332009-09-09 15:08:12 +00006769
Chris Lattner55660a72009-03-08 19:39:53 +00006770 if (isa<CastExpr>(LHSStripped))
6771 LHSStripped = LHSStripped->IgnoreParenCasts();
6772 if (isa<CastExpr>(RHSStripped))
6773 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006774
Chris Lattner55660a72009-03-08 19:39:53 +00006775 // Warn about comparisons against a string constant (unless the other
6776 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006777 Expr *literalString = 0;
6778 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006779 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006780 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006781 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00006782 literalString = lex;
6783 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006784 } else if ((isa<StringLiteral>(RHSStripped) ||
6785 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006786 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006787 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00006788 literalString = rex;
6789 literalStringStripped = RHSStripped;
6790 }
6791
6792 if (literalString) {
6793 std::string resultComparison;
6794 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006795 case BO_LT: resultComparison = ") < 0"; break;
6796 case BO_GT: resultComparison = ") > 0"; break;
6797 case BO_LE: resultComparison = ") <= 0"; break;
6798 case BO_GE: resultComparison = ") >= 0"; break;
6799 case BO_EQ: resultComparison = ") == 0"; break;
6800 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00006801 default: assert(false && "Invalid comparison operator");
6802 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006803
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006804 DiagRuntimeBehavior(Loc,
6805 PDiag(diag::warn_stringcompare)
6806 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006807 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006808 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006809 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006810
Douglas Gregord64fdd02010-06-08 19:50:34 +00006811 // C99 6.5.8p3 / C99 6.5.9p4
6812 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6813 UsualArithmeticConversions(lex, rex);
6814 else {
6815 UsualUnaryConversions(lex);
6816 UsualUnaryConversions(rex);
6817 }
6818
6819 lType = lex->getType();
6820 rType = rex->getType();
6821
Douglas Gregor447b69e2008-11-19 03:25:36 +00006822 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006823 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006824
Chris Lattnera5937dd2007-08-26 01:18:55 +00006825 if (isRelational) {
6826 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006827 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006828 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006829 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006830 if (lType->hasFloatingRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006831 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006832
Chris Lattnera5937dd2007-08-26 01:18:55 +00006833 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006834 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006835 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006836
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006837 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006838 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006839 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006840 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006841
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006842 // All of the following pointer-related warnings are GCC extensions, except
6843 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00006844 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006845 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006846 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00006847 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006848 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006849
Douglas Gregor0c6db942009-05-04 06:07:12 +00006850 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006851 if (LCanPointeeTy == RCanPointeeTy)
6852 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006853 if (!isRelational &&
6854 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6855 // Valid unless comparison between non-null pointer and function pointer
6856 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006857 // In a SFINAE context, we treat this as a hard error to maintain
6858 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006859 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6860 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006861 Diag(Loc,
6862 isSFINAEContext()?
6863 diag::err_typecheck_comparison_of_fptr_to_void
6864 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006865 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006866
6867 if (isSFINAEContext())
6868 return QualType();
6869
John McCall2de56d12010-08-25 11:45:40 +00006870 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006871 return ResultTy;
6872 }
6873 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006874
Douglas Gregor0c6db942009-05-04 06:07:12 +00006875 // C++ [expr.rel]p2:
6876 // [...] Pointer conversions (4.10) and qualification
6877 // conversions (4.4) are performed on pointer operands (or on
6878 // a pointer operand and a null pointer constant) to bring
6879 // them to their composite pointer type. [...]
6880 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00006881 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00006882 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006883 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006884 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006885 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006886 if (T.isNull()) {
6887 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6888 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6889 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006890 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006891 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006892 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006893 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006894 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00006895 }
6896
John McCall2de56d12010-08-25 11:45:40 +00006897 ImpCastExprToType(lex, T, CK_BitCast);
6898 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006899 return ResultTy;
6900 }
Eli Friedman3075e762009-08-23 00:27:47 +00006901 // C99 6.5.9p2 and C99 6.5.8p2
6902 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6903 RCanPointeeTy.getUnqualifiedType())) {
6904 // Valid unless a relational comparison of function pointers
6905 if (isRelational && LCanPointeeTy->isFunctionType()) {
6906 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6907 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6908 }
6909 } else if (!isRelational &&
6910 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6911 // Valid unless comparison between non-null pointer and function pointer
6912 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6913 && !LHSIsNull && !RHSIsNull) {
6914 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6915 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6916 }
6917 } else {
6918 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006919 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00006920 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006921 }
Eli Friedman3075e762009-08-23 00:27:47 +00006922 if (LCanPointeeTy != RCanPointeeTy)
John McCall2de56d12010-08-25 11:45:40 +00006923 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006924 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00006925 }
Mike Stump1eb44332009-09-09 15:08:12 +00006926
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006927 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006928 // Comparison of nullptr_t with itself.
6929 if (lType->isNullPtrType() && rType->isNullPtrType())
6930 return ResultTy;
6931
Mike Stump1eb44332009-09-09 15:08:12 +00006932 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00006933 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00006934 if (RHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006935 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00006936 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregor443c2122010-08-07 13:36:37 +00006937 ImpCastExprToType(rex, lType,
6938 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006939 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006940 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006941 return ResultTy;
6942 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006943 if (LHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006944 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00006945 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregor443c2122010-08-07 13:36:37 +00006946 ImpCastExprToType(lex, rType,
6947 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006948 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006949 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006950 return ResultTy;
6951 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006952
6953 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00006954 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00006955 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6956 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006957 // In addition, pointers to members can be compared, or a pointer to
6958 // member and a null pointer constant. Pointer to member conversions
6959 // (4.11) and qualification conversions (4.4) are performed to bring
6960 // them to a common type. If one operand is a null pointer constant,
6961 // the common type is the type of the other operand. Otherwise, the
6962 // common type is a pointer to member type similar (4.4) to the type
6963 // of one of the operands, with a cv-qualification signature (4.4)
6964 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00006965 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006966 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006967 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006968 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00006969 if (T.isNull()) {
6970 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006971 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00006972 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006973 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006974 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006975 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006976 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006977 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00006978 }
Mike Stump1eb44332009-09-09 15:08:12 +00006979
John McCall2de56d12010-08-25 11:45:40 +00006980 ImpCastExprToType(lex, T, CK_BitCast);
6981 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00006982 return ResultTy;
6983 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006984 }
Mike Stump1eb44332009-09-09 15:08:12 +00006985
Steve Naroff1c7d0672008-09-04 15:10:53 +00006986 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00006987 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006988 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6989 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006990
Steve Naroff1c7d0672008-09-04 15:10:53 +00006991 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00006992 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006993 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00006994 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00006995 }
John McCall2de56d12010-08-25 11:45:40 +00006996 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006997 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006998 }
Steve Naroff59f53942008-09-28 01:11:11 +00006999 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007000 if (!isRelational
7001 && ((lType->isBlockPointerType() && rType->isPointerType())
7002 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007003 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00007004 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007005 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00007006 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007007 ->getPointeeType()->isVoidType())))
7008 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7009 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007010 }
John McCall2de56d12010-08-25 11:45:40 +00007011 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007012 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007013 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007014
Steve Naroff14108da2009-07-10 23:34:53 +00007015 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00007016 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00007017 const PointerType *LPT = lType->getAs<PointerType>();
7018 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007019 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00007020 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007021 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00007022 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007023
Steve Naroffa8069f12008-11-17 19:49:16 +00007024 if (!LPtrToVoid && !RPtrToVoid &&
7025 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007026 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00007027 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00007028 }
John McCall2de56d12010-08-25 11:45:40 +00007029 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007030 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007031 }
Steve Naroff14108da2009-07-10 23:34:53 +00007032 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007033 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00007034 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
7035 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00007036 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007037 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007038 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007039 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007040 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7041 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007042 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007043 bool isError = false;
7044 if ((LHSIsNull && lType->isIntegerType()) ||
7045 (RHSIsNull && rType->isIntegerType())) {
7046 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007047 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007048 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007049 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007050 else if (getLangOptions().CPlusPlus) {
7051 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7052 isError = true;
7053 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007054 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007055
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007056 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007057 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00007058 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007059 if (isError)
7060 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007061 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007062
7063 if (lType->isIntegerType())
John McCall404cd162010-11-13 01:35:44 +00007064 ImpCastExprToType(lex, rType,
7065 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007066 else
John McCall404cd162010-11-13 01:35:44 +00007067 ImpCastExprToType(rex, lType,
7068 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007069 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007070 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007071
Steve Naroff39218df2008-09-04 16:56:14 +00007072 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00007073 if (!isRelational && RHSIsNull
7074 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCall404cd162010-11-13 01:35:44 +00007075 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007076 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007077 }
Mike Stumpaf199f32009-05-07 18:43:07 +00007078 if (!isRelational && LHSIsNull
7079 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCall404cd162010-11-13 01:35:44 +00007080 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007081 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007082 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007083 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007084}
7085
Nate Begemanbe2341d2008-07-14 18:02:46 +00007086/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007087/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007088/// like a scalar comparison, a vector comparison produces a vector of integer
7089/// types.
7090QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007091 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007092 bool isRelational) {
7093 // Check to make sure we're operating on vectors of the same type and width,
7094 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007095 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007096 if (vType.isNull())
7097 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007098
Anton Yartsevaa4fe052010-11-18 03:19:30 +00007099 // If AltiVec, the comparison results in a numeric type, i.e.
7100 // bool for C++, int for C
7101 if (getLangOptions().AltiVec)
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007102 return Context.getLogicalOperationType();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00007103
Nate Begemanbe2341d2008-07-14 18:02:46 +00007104 QualType lType = lex->getType();
7105 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007106
Nate Begemanbe2341d2008-07-14 18:02:46 +00007107 // For non-floating point types, check for self-comparisons of the form
7108 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7109 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007110 if (!lType->hasFloatingRepresentation()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007111 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
7112 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
7113 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregord64fdd02010-06-08 19:50:34 +00007114 DiagRuntimeBehavior(Loc,
7115 PDiag(diag::warn_comparison_always)
7116 << 0 // self-
7117 << 2 // "a constant"
7118 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007119 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007120
Nate Begemanbe2341d2008-07-14 18:02:46 +00007121 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007122 if (!isRelational && lType->hasFloatingRepresentation()) {
7123 assert (rType->hasFloatingRepresentation());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007124 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007125 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007126
Nate Begemanbe2341d2008-07-14 18:02:46 +00007127 // Return the type for the comparison, which is the same as vector type for
7128 // integer vectors, or an integer type of identical size and number of
7129 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00007130 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00007131 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007132
John McCall183700f2009-09-21 23:43:11 +00007133 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00007134 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00007135 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007136 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00007137 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00007138 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7139
Mike Stumpeed9cac2009-02-19 03:04:26 +00007140 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00007141 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00007142 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7143}
7144
Reid Spencer5f016e22007-07-11 17:01:13 +00007145inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00007146 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregorf6094622010-07-23 15:58:24 +00007147 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
7148 if (lex->getType()->hasIntegerRepresentation() &&
7149 rex->getType()->hasIntegerRepresentation())
7150 return CheckVectorOperands(Loc, lex, rex);
7151
7152 return InvalidOperands(Loc, lex, rex);
7153 }
Steve Naroff90045e82007-07-13 23:32:42 +00007154
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007155 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007156
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007157 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
7158 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007159 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007160 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007161}
7162
7163inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner90a8f272010-07-13 19:41:32 +00007164 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
7165
7166 // Diagnose cases where the user write a logical and/or but probably meant a
7167 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7168 // is a constant.
7169 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman787b0942010-07-27 19:14:53 +00007170 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattner23ef3e42010-07-15 00:26:43 +00007171 // Don't warn in macros.
Chris Lattnerb7690b42010-07-24 01:10:11 +00007172 !Loc.isMacroID()) {
7173 // If the RHS can be constant folded, and if it constant folds to something
7174 // that isn't 0 or 1 (which indicate a potential logical operation that
7175 // happened to fold to true/false) then warn.
7176 Expr::EvalResult Result;
7177 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
7178 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7179 Diag(Loc, diag::warn_logical_instead_of_bitwise)
7180 << rex->getSourceRange()
John McCall2de56d12010-08-25 11:45:40 +00007181 << (Opc == BO_LAnd ? "&&" : "||")
7182 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattnerb7690b42010-07-24 01:10:11 +00007183 }
7184 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007185
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007186 if (!Context.getLangOptions().CPlusPlus) {
7187 UsualUnaryConversions(lex);
7188 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007189
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007190 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
7191 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007192
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007193 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007194 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007195
John McCall75f7c0f2010-06-04 00:29:51 +00007196 // The following is safe because we only use this method for
7197 // non-overloadable operands.
7198
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007199 // C++ [expr.log.and]p1
7200 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007201 // The operands are both contextually converted to type bool.
7202 if (PerformContextuallyConvertToBool(lex) ||
7203 PerformContextuallyConvertToBool(rex))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007204 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007205
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007206 // C++ [expr.log.and]p2
7207 // C++ [expr.log.or]p2
7208 // The result is a bool.
7209 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007210}
7211
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007212/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7213/// is a read-only property; return true if so. A readonly property expression
7214/// depends on various declarations and thus must be treated specially.
7215///
Mike Stump1eb44332009-09-09 15:08:12 +00007216static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007217 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7218 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00007219 if (PropExpr->isImplicitProperty()) return false;
7220
7221 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7222 QualType BaseType = PropExpr->isSuperReceiver() ?
7223 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007224 PropExpr->getBase()->getType();
7225
John McCall12f78a62010-12-02 01:19:52 +00007226 if (const ObjCObjectPointerType *OPT =
7227 BaseType->getAsObjCInterfacePointerType())
7228 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7229 if (S.isPropertyReadonly(PDecl, IFace))
7230 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007231 }
7232 return false;
7233}
7234
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007235/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7236/// emit an error and return true. If so, return false.
7237static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007238 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007239 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007240 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007241 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7242 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007243 if (IsLV == Expr::MLV_Valid)
7244 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007245
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007246 unsigned Diag = 0;
7247 bool NeedType = false;
7248 switch (IsLV) { // C99 6.5.16p2
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007249 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007250 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007251 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7252 NeedType = true;
7253 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007254 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007255 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7256 NeedType = true;
7257 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007258 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007259 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7260 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007261 case Expr::MLV_Valid:
7262 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007263 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007264 case Expr::MLV_MemberFunction:
7265 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007266 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7267 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007268 case Expr::MLV_IncompleteType:
7269 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007270 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007271 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00007272 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00007273 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007274 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7275 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00007276 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007277 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7278 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007279 case Expr::MLV_ReadonlyProperty:
7280 Diag = diag::error_readonly_property_assignment;
7281 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007282 case Expr::MLV_NoSetterProperty:
7283 Diag = diag::error_nosetter_property_assignment;
7284 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007285 case Expr::MLV_SubObjCPropertySetting:
7286 Diag = diag::error_no_subobject_property_setting;
7287 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007288 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007289
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007290 SourceRange Assign;
7291 if (Loc != OrigLoc)
7292 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007293 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007294 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007295 else
Mike Stump1eb44332009-09-09 15:08:12 +00007296 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007297 return true;
7298}
7299
7300
7301
7302// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007303QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
7304 SourceLocation Loc,
7305 QualType CompoundType) {
7306 // Verify that LHS is a modifiable lvalue, and emit error if not.
7307 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007308 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007309
7310 QualType LHSType = LHS->getType();
7311 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007312 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007313 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007314 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007315 // Simple assignment "x = y".
John McCallf6a16482010-12-04 03:47:34 +00007316 if (LHS->getObjectKind() == OK_ObjCProperty)
7317 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007318 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007319 // Special case of NSObject attributes on c-style pointer types.
7320 if (ConvTy == IncompatiblePointer &&
7321 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007322 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007323 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007324 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007325 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007326
John McCallf89e55a2010-11-18 06:31:45 +00007327 if (ConvTy == Compatible &&
7328 getLangOptions().ObjCNonFragileABI &&
7329 LHSType->isObjCObjectType())
7330 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7331 << LHSType;
7332
Chris Lattner2c156472008-08-21 18:04:13 +00007333 // If the RHS is a unary plus or minus, check to see if they = and + are
7334 // right next to each other. If so, the user may have typo'd "x =+ 4"
7335 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007336 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00007337 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7338 RHSCheck = ICE->getSubExpr();
7339 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007340 if ((UO->getOpcode() == UO_Plus ||
7341 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007342 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007343 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00007344 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7345 // And there is a space or other character before the subexpr of the
7346 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00007347 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7348 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007349 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007350 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007351 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007352 }
Chris Lattner2c156472008-08-21 18:04:13 +00007353 }
7354 } else {
7355 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007356 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007357 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007358
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007359 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00007360 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007361 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007362
Chris Lattner8b5dec32010-07-07 06:14:23 +00007363
7364 // Check to see if the destination operand is a dereferenced null pointer. If
7365 // so, and if not volatile-qualified, this is undefined behavior that the
7366 // optimizer will delete, so warn about it. People sometimes try to use this
7367 // to get a deterministic trap and are surprised by clang's behavior. This
7368 // only handles the pattern "*null = whatever", which is a very syntactic
7369 // check.
7370 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCall2de56d12010-08-25 11:45:40 +00007371 if (UO->getOpcode() == UO_Deref &&
Chris Lattner8b5dec32010-07-07 06:14:23 +00007372 UO->getSubExpr()->IgnoreParenCasts()->
7373 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7374 !UO->getType().isVolatileQualified()) {
7375 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
7376 << UO->getSubExpr()->getSourceRange();
7377 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
7378 }
7379
Ted Kremeneka0125d82011-02-16 01:57:07 +00007380 // Check for trivial buffer overflows.
7381 if (const ArraySubscriptExpr *ae
7382 = dyn_cast<ArraySubscriptExpr>(LHS->IgnoreParenCasts()))
7383 CheckArrayAccess(ae);
7384
Reid Spencer5f016e22007-07-11 17:01:13 +00007385 // C99 6.5.16p3: The type of an assignment expression is the type of the
7386 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007387 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007388 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7389 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007390 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007391 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00007392 return (getLangOptions().CPlusPlus
7393 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007394}
7395
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007396// C99 6.5.17
John McCallf6a16482010-12-04 03:47:34 +00007397static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall09431682010-11-18 19:01:18 +00007398 SourceLocation Loc) {
7399 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00007400
John McCall09431682010-11-18 19:01:18 +00007401 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007402 if (LHSResult.isInvalid())
7403 return QualType();
7404
John McCall09431682010-11-18 19:01:18 +00007405 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007406 if (RHSResult.isInvalid())
7407 return QualType();
7408 RHS = RHSResult.take();
7409
John McCallcf2e5062010-10-12 07:14:40 +00007410 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7411 // operands, but not unary promotions.
7412 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007413
John McCallf6a16482010-12-04 03:47:34 +00007414 // So we treat the LHS as a ignored value, and in C++ we allow the
7415 // containing site to determine what should be done with the RHS.
7416 S.IgnoredValueConversions(LHS);
7417
7418 if (!S.getLangOptions().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007419 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCallcf2e5062010-10-12 07:14:40 +00007420 if (!RHS->getType()->isVoidType())
John McCall09431682010-11-18 19:01:18 +00007421 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007422 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007423
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007424 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007425}
7426
Steve Naroff49b45262007-07-13 16:58:59 +00007427/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7428/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007429static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7430 ExprValueKind &VK,
7431 SourceLocation OpLoc,
7432 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007433 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007434 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007435
Chris Lattner3528d352008-11-21 07:05:48 +00007436 QualType ResType = Op->getType();
7437 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007438
John McCall09431682010-11-18 19:01:18 +00007439 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007440 // Decrement of bool is not allowed.
7441 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00007442 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007443 return QualType();
7444 }
7445 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007446 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007447 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007448 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007449 } else if (ResType->isAnyPointerType()) {
7450 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00007451
Chris Lattner3528d352008-11-21 07:05:48 +00007452 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00007453 if (PointeeTy->isVoidType()) {
John McCall09431682010-11-18 19:01:18 +00007454 if (S.getLangOptions().CPlusPlus) {
7455 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00007456 << Op->getSourceRange();
7457 return QualType();
7458 }
7459
7460 // Pointer to void is a GNU extension in C.
John McCall09431682010-11-18 19:01:18 +00007461 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00007462 } else if (PointeeTy->isFunctionType()) {
John McCall09431682010-11-18 19:01:18 +00007463 if (S.getLangOptions().CPlusPlus) {
7464 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00007465 << Op->getType() << Op->getSourceRange();
7466 return QualType();
7467 }
7468
John McCall09431682010-11-18 19:01:18 +00007469 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00007470 << ResType << Op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007471 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7472 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00007473 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00007474 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007475 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007476 // Diagnose bad cases where we step over interface counts.
John McCall09431682010-11-18 19:01:18 +00007477 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7478 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007479 << PointeeTy << Op->getSourceRange();
7480 return QualType();
7481 }
Eli Friedman5b088a12010-01-03 00:20:48 +00007482 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007483 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007484 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007485 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007486 } else if (ResType->isPlaceholderType()) {
John McCall09431682010-11-18 19:01:18 +00007487 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007488 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007489 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7490 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00007491 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7492 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007493 } else {
John McCall09431682010-11-18 19:01:18 +00007494 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00007495 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007496 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007497 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007498 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007499 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007500 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007501 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007502 // In C++, a prefix increment is the same type as the operand. Otherwise
7503 // (in C or with postfix), the increment is the unqualified type of the
7504 // operand.
John McCall09431682010-11-18 19:01:18 +00007505 if (isPrefix && S.getLangOptions().CPlusPlus) {
7506 VK = VK_LValue;
7507 return ResType;
7508 } else {
7509 VK = VK_RValue;
7510 return ResType.getUnqualifiedType();
7511 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007512}
7513
John McCallf6a16482010-12-04 03:47:34 +00007514void Sema::ConvertPropertyForRValue(Expr *&E) {
7515 assert(E->getValueKind() == VK_LValue &&
7516 E->getObjectKind() == OK_ObjCProperty);
7517 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7518
7519 ExprValueKind VK = VK_RValue;
7520 if (PRE->isImplicitProperty()) {
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007521 if (const ObjCMethodDecl *GetterMethod =
7522 PRE->getImplicitPropertyGetter()) {
7523 QualType Result = GetterMethod->getResultType();
7524 VK = Expr::getValueKindForType(Result);
7525 }
7526 else {
7527 Diag(PRE->getLocation(), diag::err_getter_not_found)
7528 << PRE->getBase()->getType();
7529 }
John McCallf6a16482010-12-04 03:47:34 +00007530 }
7531
7532 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7533 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00007534
7535 ExprResult Result = MaybeBindToTemporary(E);
7536 if (!Result.isInvalid())
7537 E = Result.take();
John McCallf6a16482010-12-04 03:47:34 +00007538}
7539
7540void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7541 assert(LHS->getValueKind() == VK_LValue &&
7542 LHS->getObjectKind() == OK_ObjCProperty);
7543 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7544
7545 if (PRE->isImplicitProperty()) {
7546 // If using property-dot syntax notation for assignment, and there is a
7547 // setter, RHS expression is being passed to the setter argument. So,
7548 // type conversion (and comparison) is RHS to setter's argument type.
7549 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7550 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7551 LHSTy = (*P)->getType();
7552
7553 // Otherwise, if the getter returns an l-value, just call that.
7554 } else {
7555 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7556 ExprValueKind VK = Expr::getValueKindForType(Result);
7557 if (VK == VK_LValue) {
7558 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7559 CK_GetObjCProperty, LHS, 0, VK);
7560 return;
John McCall12f78a62010-12-02 01:19:52 +00007561 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007562 }
John McCallf6a16482010-12-04 03:47:34 +00007563 }
7564
7565 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007566 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007567 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007568 Expr *Arg = RHS;
7569 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7570 Owned(Arg));
7571 if (!ArgE.isInvalid())
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007572 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007573 }
7574}
7575
7576
Anders Carlsson369dee42008-02-01 07:15:58 +00007577/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007578/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007579/// where the declaration is needed for type checking. We only need to
7580/// handle cases when the expression references a function designator
7581/// or is an lvalue. Here are some examples:
7582/// - &(x) => x
7583/// - &*****f => f for f a function designator.
7584/// - &s.xx => s
7585/// - &s.zz[1].yy -> s, if zz is an array
7586/// - *(x + 1) -> x, if x is an array
7587/// - &"123"[2] -> 0
7588/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007589static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007590 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007591 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007592 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007593 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007594 // If this is an arrow operator, the address is an offset from
7595 // the base's value, so the object the base refers to is
7596 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007597 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007598 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007599 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007600 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007601 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007602 // FIXME: This code shouldn't be necessary! We should catch the implicit
7603 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007604 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7605 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7606 if (ICE->getSubExpr()->getType()->isArrayType())
7607 return getPrimaryDecl(ICE->getSubExpr());
7608 }
7609 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007610 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007611 case Stmt::UnaryOperatorClass: {
7612 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007613
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007614 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007615 case UO_Real:
7616 case UO_Imag:
7617 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007618 return getPrimaryDecl(UO->getSubExpr());
7619 default:
7620 return 0;
7621 }
7622 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007623 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007624 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007625 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007626 // If the result of an implicit cast is an l-value, we care about
7627 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007628 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007629 default:
7630 return 0;
7631 }
7632}
7633
7634/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007635/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007636/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007637/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007638/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007639/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007640/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00007641static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7642 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00007643 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007644 return S.Context.DependentTy;
7645 if (OrigOp->getType() == S.Context.OverloadTy)
7646 return S.Context.OverloadTy;
John McCall9c72c602010-08-27 09:08:28 +00007647
John McCall09431682010-11-18 19:01:18 +00007648 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007649 if (PR.isInvalid()) return QualType();
7650 OrigOp = PR.take();
7651
John McCall9c72c602010-08-27 09:08:28 +00007652 // Make sure to ignore parentheses in subsequent checks
7653 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007654
John McCall09431682010-11-18 19:01:18 +00007655 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007656 // Implement C99-only parts of addressof rules.
7657 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007658 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007659 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7660 // (assuming the deref expression is valid).
7661 return uOp->getSubExpr()->getType();
7662 }
7663 // Technically, there should be a check for array subscript
7664 // expressions here, but the result of one is always an lvalue anyway.
7665 }
John McCall5808ce42011-02-03 08:15:49 +00007666 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007667 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007668
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007669 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007670 bool sfinae = S.isSFINAEContext();
7671 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7672 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007673 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007674 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007675 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007676 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007677 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007678 } else if (lval == Expr::LV_MemberFunction) {
7679 // If it's an instance method, make a member pointer.
7680 // The expression must have exactly the form &A::foo.
7681
7682 // If the underlying expression isn't a decl ref, give up.
7683 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007684 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007685 << OrigOp->getSourceRange();
7686 return QualType();
7687 }
7688 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7689 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7690
7691 // The id-expression was parenthesized.
7692 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00007693 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007694 << OrigOp->getSourceRange();
7695
7696 // The method was named without a qualifier.
7697 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007698 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007699 << op->getSourceRange();
7700 }
7701
John McCall09431682010-11-18 19:01:18 +00007702 return S.Context.getMemberPointerType(op->getType(),
7703 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007704 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007705 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007706 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007707 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00007708 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00007709 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00007710 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007711 return QualType();
7712 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007713 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007714 // The operand cannot be a bit-field
John McCall09431682010-11-18 19:01:18 +00007715 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman23d58ce2009-04-20 08:23:18 +00007716 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00007717 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007718 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007719 // The operand cannot be an element of a vector
John McCall09431682010-11-18 19:01:18 +00007720 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00007721 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007722 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007723 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007724 // cannot take address of a property expression.
John McCall09431682010-11-18 19:01:18 +00007725 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007726 << "property expression" << op->getSourceRange();
7727 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007728 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007729 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007730 // with the register storage-class specifier.
7731 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007732 // in C++ it is not error to take address of a register
7733 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007734 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007735 !S.getLangOptions().CPlusPlus) {
7736 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007737 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007738 return QualType();
7739 }
John McCallba135432009-11-21 08:51:07 +00007740 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007741 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007742 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007743 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007744 // Could be a pointer to member, though, if there is an explicit
7745 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007746 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007747 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007748 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007749 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007750 S.Diag(OpLoc,
7751 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007752 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007753 return QualType();
7754 }
Mike Stump1eb44332009-09-09 15:08:12 +00007755
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007756 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7757 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007758 return S.Context.getMemberPointerType(op->getType(),
7759 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007760 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007761 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00007762 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00007763 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007764 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007765
Eli Friedman441cf102009-05-16 23:27:50 +00007766 if (lval == Expr::LV_IncompleteVoidType) {
7767 // Taking the address of a void variable is technically illegal, but we
7768 // allow it in cases which are otherwise valid.
7769 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007770 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007771 }
7772
Reid Spencer5f016e22007-07-11 17:01:13 +00007773 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007774 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007775 return S.Context.getObjCObjectPointerType(op->getType());
7776 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007777}
7778
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007779/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007780static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7781 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007782 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007783 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007784
John McCall09431682010-11-18 19:01:18 +00007785 S.UsualUnaryConversions(Op);
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007786 QualType OpTy = Op->getType();
7787 QualType Result;
7788
7789 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7790 // is an incomplete type or void. It would be possible to warn about
7791 // dereferencing a void pointer, but it's completely well-defined, and such a
7792 // warning is unlikely to catch any mistakes.
7793 if (const PointerType *PT = OpTy->getAs<PointerType>())
7794 Result = PT->getPointeeType();
7795 else if (const ObjCObjectPointerType *OPT =
7796 OpTy->getAs<ObjCObjectPointerType>())
7797 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007798 else {
John McCall09431682010-11-18 19:01:18 +00007799 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007800 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007801 if (PR.take() != Op)
7802 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007803 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007804
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007805 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007806 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007807 << OpTy << Op->getSourceRange();
7808 return QualType();
7809 }
John McCall09431682010-11-18 19:01:18 +00007810
7811 // Dereferences are usually l-values...
7812 VK = VK_LValue;
7813
7814 // ...except that certain expressions are never l-values in C.
7815 if (!S.getLangOptions().CPlusPlus &&
7816 IsCForbiddenLValueType(S.Context, Result))
7817 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007818
7819 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007820}
7821
John McCall2de56d12010-08-25 11:45:40 +00007822static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007823 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007824 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007825 switch (Kind) {
7826 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007827 case tok::periodstar: Opc = BO_PtrMemD; break;
7828 case tok::arrowstar: Opc = BO_PtrMemI; break;
7829 case tok::star: Opc = BO_Mul; break;
7830 case tok::slash: Opc = BO_Div; break;
7831 case tok::percent: Opc = BO_Rem; break;
7832 case tok::plus: Opc = BO_Add; break;
7833 case tok::minus: Opc = BO_Sub; break;
7834 case tok::lessless: Opc = BO_Shl; break;
7835 case tok::greatergreater: Opc = BO_Shr; break;
7836 case tok::lessequal: Opc = BO_LE; break;
7837 case tok::less: Opc = BO_LT; break;
7838 case tok::greaterequal: Opc = BO_GE; break;
7839 case tok::greater: Opc = BO_GT; break;
7840 case tok::exclaimequal: Opc = BO_NE; break;
7841 case tok::equalequal: Opc = BO_EQ; break;
7842 case tok::amp: Opc = BO_And; break;
7843 case tok::caret: Opc = BO_Xor; break;
7844 case tok::pipe: Opc = BO_Or; break;
7845 case tok::ampamp: Opc = BO_LAnd; break;
7846 case tok::pipepipe: Opc = BO_LOr; break;
7847 case tok::equal: Opc = BO_Assign; break;
7848 case tok::starequal: Opc = BO_MulAssign; break;
7849 case tok::slashequal: Opc = BO_DivAssign; break;
7850 case tok::percentequal: Opc = BO_RemAssign; break;
7851 case tok::plusequal: Opc = BO_AddAssign; break;
7852 case tok::minusequal: Opc = BO_SubAssign; break;
7853 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7854 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7855 case tok::ampequal: Opc = BO_AndAssign; break;
7856 case tok::caretequal: Opc = BO_XorAssign; break;
7857 case tok::pipeequal: Opc = BO_OrAssign; break;
7858 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007859 }
7860 return Opc;
7861}
7862
John McCall2de56d12010-08-25 11:45:40 +00007863static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007864 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007865 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007866 switch (Kind) {
7867 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007868 case tok::plusplus: Opc = UO_PreInc; break;
7869 case tok::minusminus: Opc = UO_PreDec; break;
7870 case tok::amp: Opc = UO_AddrOf; break;
7871 case tok::star: Opc = UO_Deref; break;
7872 case tok::plus: Opc = UO_Plus; break;
7873 case tok::minus: Opc = UO_Minus; break;
7874 case tok::tilde: Opc = UO_Not; break;
7875 case tok::exclaim: Opc = UO_LNot; break;
7876 case tok::kw___real: Opc = UO_Real; break;
7877 case tok::kw___imag: Opc = UO_Imag; break;
7878 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007879 }
7880 return Opc;
7881}
7882
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007883/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7884/// This warning is only emitted for builtin assignment operations. It is also
7885/// suppressed in the event of macro expansions.
7886static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7887 SourceLocation OpLoc) {
7888 if (!S.ActiveTemplateInstantiations.empty())
7889 return;
7890 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7891 return;
7892 lhs = lhs->IgnoreParenImpCasts();
7893 rhs = rhs->IgnoreParenImpCasts();
7894 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7895 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7896 if (!LeftDeclRef || !RightDeclRef ||
7897 LeftDeclRef->getLocation().isMacroID() ||
7898 RightDeclRef->getLocation().isMacroID())
7899 return;
7900 const ValueDecl *LeftDecl =
7901 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7902 const ValueDecl *RightDecl =
7903 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7904 if (LeftDecl != RightDecl)
7905 return;
7906 if (LeftDecl->getType().isVolatileQualified())
7907 return;
7908 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7909 if (RefTy->getPointeeType().isVolatileQualified())
7910 return;
7911
7912 S.Diag(OpLoc, diag::warn_self_assignment)
7913 << LeftDeclRef->getType()
7914 << lhs->getSourceRange() << rhs->getSourceRange();
7915}
7916
Douglas Gregoreaebc752008-11-06 23:29:22 +00007917/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7918/// operator @p Opc at location @c TokLoc. This routine only supports
7919/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00007920ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007921 BinaryOperatorKind Opc,
John McCall2de56d12010-08-25 11:45:40 +00007922 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00007923 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00007924 // The following two variables are used for compound assignment operators
7925 QualType CompLHSTy; // Type of LHS after promotions for computation
7926 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00007927 ExprValueKind VK = VK_RValue;
7928 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00007929
7930 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007931 case BO_Assign:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007932 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00007933 if (getLangOptions().CPlusPlus &&
7934 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall09431682010-11-18 19:01:18 +00007935 VK = lhs->getValueKind();
7936 OK = lhs->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007937 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007938 if (!ResultTy.isNull())
7939 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007940 break;
John McCall2de56d12010-08-25 11:45:40 +00007941 case BO_PtrMemD:
7942 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00007943 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007944 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00007945 break;
John McCall2de56d12010-08-25 11:45:40 +00007946 case BO_Mul:
7947 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007948 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00007949 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007950 break;
John McCall2de56d12010-08-25 11:45:40 +00007951 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007952 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7953 break;
John McCall2de56d12010-08-25 11:45:40 +00007954 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007955 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7956 break;
John McCall2de56d12010-08-25 11:45:40 +00007957 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007958 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7959 break;
John McCall2de56d12010-08-25 11:45:40 +00007960 case BO_Shl:
7961 case BO_Shr:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007962 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
7963 break;
John McCall2de56d12010-08-25 11:45:40 +00007964 case BO_LE:
7965 case BO_LT:
7966 case BO_GE:
7967 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00007968 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007969 break;
John McCall2de56d12010-08-25 11:45:40 +00007970 case BO_EQ:
7971 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00007972 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007973 break;
John McCall2de56d12010-08-25 11:45:40 +00007974 case BO_And:
7975 case BO_Xor:
7976 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007977 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7978 break;
John McCall2de56d12010-08-25 11:45:40 +00007979 case BO_LAnd:
7980 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00007981 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007982 break;
John McCall2de56d12010-08-25 11:45:40 +00007983 case BO_MulAssign:
7984 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007985 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00007986 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007987 CompLHSTy = CompResultTy;
7988 if (!CompResultTy.isNull())
7989 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007990 break;
John McCall2de56d12010-08-25 11:45:40 +00007991 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007992 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7993 CompLHSTy = CompResultTy;
7994 if (!CompResultTy.isNull())
7995 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007996 break;
John McCall2de56d12010-08-25 11:45:40 +00007997 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007998 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7999 if (!CompResultTy.isNull())
8000 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008001 break;
John McCall2de56d12010-08-25 11:45:40 +00008002 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008003 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8004 if (!CompResultTy.isNull())
8005 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008006 break;
John McCall2de56d12010-08-25 11:45:40 +00008007 case BO_ShlAssign:
8008 case BO_ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008009 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
8010 CompLHSTy = CompResultTy;
8011 if (!CompResultTy.isNull())
8012 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008013 break;
John McCall2de56d12010-08-25 11:45:40 +00008014 case BO_AndAssign:
8015 case BO_XorAssign:
8016 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008017 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8018 CompLHSTy = CompResultTy;
8019 if (!CompResultTy.isNull())
8020 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008021 break;
John McCall2de56d12010-08-25 11:45:40 +00008022 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00008023 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCallf89e55a2010-11-18 06:31:45 +00008024 if (getLangOptions().CPlusPlus) {
8025 VK = rhs->getValueKind();
8026 OK = rhs->getObjectKind();
8027 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008028 break;
8029 }
8030 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008031 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00008032 if (CompResultTy.isNull())
John McCallf89e55a2010-11-18 06:31:45 +00008033 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
8034 VK, OK, OpLoc));
8035
John McCallf6a16482010-12-04 03:47:34 +00008036 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008037 VK = VK_LValue;
8038 OK = lhs->getObjectKind();
8039 }
8040 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
8041 VK, OK, CompLHSTy,
8042 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008043}
8044
Sebastian Redlaee3c932009-10-27 12:10:02 +00008045/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8046/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008047static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8048 const PartialDiagnostic &PD,
Douglas Gregor55b38842010-04-14 16:09:52 +00008049 const PartialDiagnostic &FirstNote,
8050 SourceRange FirstParenRange,
8051 const PartialDiagnostic &SecondNote,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008052 SourceRange SecondParenRange) {
Douglas Gregor55b38842010-04-14 16:09:52 +00008053 Self.Diag(Loc, PD);
8054
8055 if (!FirstNote.getDiagID())
8056 return;
8057
8058 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8059 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8060 // We can't display the parentheses, so just return.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008061 return;
8062 }
8063
Douglas Gregor55b38842010-04-14 16:09:52 +00008064 Self.Diag(Loc, FirstNote)
8065 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregor849b2432010-03-31 17:46:05 +00008066 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008067
Douglas Gregor55b38842010-04-14 16:09:52 +00008068 if (!SecondNote.getDiagID())
Douglas Gregor827feec2010-01-08 00:20:23 +00008069 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008070
Douglas Gregor827feec2010-01-08 00:20:23 +00008071 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8072 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8073 // We can't display the parentheses, so just dig the
8074 // warning/error and return.
Douglas Gregor55b38842010-04-14 16:09:52 +00008075 Self.Diag(Loc, SecondNote);
Douglas Gregor827feec2010-01-08 00:20:23 +00008076 return;
8077 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008078
Douglas Gregor55b38842010-04-14 16:09:52 +00008079 Self.Diag(Loc, SecondNote)
Douglas Gregor849b2432010-03-31 17:46:05 +00008080 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8081 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008082}
8083
Sebastian Redlaee3c932009-10-27 12:10:02 +00008084/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8085/// operators are mixed in a way that suggests that the programmer forgot that
8086/// comparison operators have higher precedence. The most typical example of
8087/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008088static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008089 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00008090 typedef BinaryOperator BinOp;
8091 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8092 rhsopc = static_cast<BinOp::Opcode>(-1);
8093 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008094 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00008095 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008096 rhsopc = BO->getOpcode();
8097
8098 // Subs are not binary operators.
8099 if (lhsopc == -1 && rhsopc == -1)
8100 return;
8101
8102 // Bitwise operations are sometimes used as eager logical ops.
8103 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00008104 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8105 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008106 return;
8107
Sebastian Redlaee3c932009-10-27 12:10:02 +00008108 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008109 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008110 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00008111 << SourceRange(lhs->getLocStart(), OpLoc)
8112 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008113 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00008114 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00008115 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
8116 Self.PDiag(diag::note_precedence_bitwise_silence)
8117 << BinOp::getOpcodeStr(lhsopc),
8118 lhs->getSourceRange());
Sebastian Redlaee3c932009-10-27 12:10:02 +00008119 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008120 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008121 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00008122 << SourceRange(OpLoc, rhs->getLocEnd())
8123 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008124 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00008125 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00008126 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
8127 Self.PDiag(diag::note_precedence_bitwise_silence)
8128 << BinOp::getOpcodeStr(rhsopc),
8129 rhs->getSourceRange());
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008130}
8131
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008132/// \brief It accepts a '&&' expr that is inside a '||' one.
8133/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8134/// in parentheses.
8135static void
8136EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8137 Expr *E) {
8138 assert(isa<BinaryOperator>(E) &&
8139 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
8140 SuggestParentheses(Self, OpLoc,
8141 Self.PDiag(diag::warn_logical_and_in_logical_or)
8142 << E->getSourceRange(),
8143 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8144 E->getSourceRange(),
8145 Self.PDiag(0), SourceRange());
8146}
8147
8148/// \brief Returns true if the given expression can be evaluated as a constant
8149/// 'true'.
8150static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8151 bool Res;
8152 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8153}
8154
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008155/// \brief Returns true if the given expression can be evaluated as a constant
8156/// 'false'.
8157static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8158 bool Res;
8159 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8160}
8161
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008162/// \brief Look for '&&' in the left hand of a '||' expr.
8163static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008164 Expr *OrLHS, Expr *OrRHS) {
8165 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008166 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008167 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8168 if (EvaluatesAsFalse(S, OrRHS))
8169 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008170 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8171 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8172 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8173 } else if (Bop->getOpcode() == BO_LOr) {
8174 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8175 // If it's "a || b && 1 || c" we didn't warn earlier for
8176 // "a || b && 1", but warn now.
8177 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8178 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8179 }
8180 }
8181 }
8182}
8183
8184/// \brief Look for '&&' in the right hand of a '||' expr.
8185static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008186 Expr *OrLHS, Expr *OrRHS) {
8187 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008188 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008189 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8190 if (EvaluatesAsFalse(S, OrLHS))
8191 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008192 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8193 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8194 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008195 }
8196 }
8197}
8198
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008199/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008200/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008201static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008202 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008203 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008204 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008205 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8206
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008207 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8208 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008209 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008210 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8211 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008212 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008213}
8214
Reid Spencer5f016e22007-07-11 17:01:13 +00008215// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008216ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008217 tok::TokenKind Kind,
8218 Expr *lhs, Expr *rhs) {
8219 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00008220 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8221 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008222
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008223 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8224 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8225
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008226 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8227}
8228
John McCall60d7b3a2010-08-24 06:29:42 +00008229ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008230 BinaryOperatorKind Opc,
8231 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00008232 if (getLangOptions().CPlusPlus) {
8233 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008234
John McCall01b2e4e2010-12-06 05:26:58 +00008235 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8236 UseBuiltinOperator = false;
8237 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8238 UseBuiltinOperator = true;
8239 } else {
8240 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8241 !rhs->getType()->isOverloadableType();
8242 }
8243
8244 if (!UseBuiltinOperator) {
8245 // Find all of the overloaded operators visible from this
8246 // point. We perform both an operator-name lookup from the local
8247 // scope and an argument-dependent lookup based on the types of
8248 // the arguments.
8249 UnresolvedSet<16> Functions;
8250 OverloadedOperatorKind OverOp
8251 = BinaryOperator::getOverloadedOperator(Opc);
8252 if (S && OverOp != OO_None)
8253 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8254 Functions);
8255
8256 // Build the (potentially-overloaded, potentially-dependent)
8257 // binary operation.
8258 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8259 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008260 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008261
Douglas Gregoreaebc752008-11-06 23:29:22 +00008262 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008263 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00008264}
8265
John McCall60d7b3a2010-08-24 06:29:42 +00008266ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008267 UnaryOperatorKind Opc,
John McCall2cd11fe2010-10-12 02:09:17 +00008268 Expr *Input) {
John McCallf89e55a2010-11-18 06:31:45 +00008269 ExprValueKind VK = VK_RValue;
8270 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008271 QualType resultType;
8272 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008273 case UO_PreInc:
8274 case UO_PreDec:
8275 case UO_PostInc:
8276 case UO_PostDec:
John McCall09431682010-11-18 19:01:18 +00008277 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008278 Opc == UO_PreInc ||
8279 Opc == UO_PostInc,
8280 Opc == UO_PreInc ||
8281 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008282 break;
John McCall2de56d12010-08-25 11:45:40 +00008283 case UO_AddrOf:
John McCall09431682010-11-18 19:01:18 +00008284 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008285 break;
John McCall2de56d12010-08-25 11:45:40 +00008286 case UO_Deref:
Douglas Gregora873dfc2010-02-03 00:27:59 +00008287 DefaultFunctionArrayLvalueConversion(Input);
John McCall09431682010-11-18 19:01:18 +00008288 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008289 break;
John McCall2de56d12010-08-25 11:45:40 +00008290 case UO_Plus:
8291 case UO_Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00008292 UsualUnaryConversions(Input);
8293 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008294 if (resultType->isDependentType())
8295 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008296 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8297 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008298 break;
8299 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8300 resultType->isEnumeralType())
8301 break;
8302 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008303 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008304 resultType->isPointerType())
8305 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008306 else if (resultType->isPlaceholderType()) {
8307 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8308 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008309 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008310 }
Douglas Gregor74253732008-11-19 15:42:04 +00008311
Sebastian Redl0eb23302009-01-19 00:08:26 +00008312 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8313 << resultType << Input->getSourceRange());
John McCall2de56d12010-08-25 11:45:40 +00008314 case UO_Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00008315 UsualUnaryConversions(Input);
8316 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008317 if (resultType->isDependentType())
8318 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008319 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8320 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8321 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008322 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00008323 << resultType << Input->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008324 else if (resultType->hasIntegerRepresentation())
8325 break;
8326 else if (resultType->isPlaceholderType()) {
8327 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8328 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008329 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008330 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008331 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8332 << resultType << Input->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008333 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008334 break;
John McCall2de56d12010-08-25 11:45:40 +00008335 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008336 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregora873dfc2010-02-03 00:27:59 +00008337 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00008338 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008339 if (resultType->isDependentType())
8340 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008341 if (resultType->isScalarType()) { // C99 6.5.3.3p1
8342 // ok, fallthrough
8343 } else if (resultType->isPlaceholderType()) {
8344 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8345 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008346 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008347 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008348 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8349 << resultType << Input->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008350 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008351
Reid Spencer5f016e22007-07-11 17:01:13 +00008352 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008353 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008354 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008355 break;
John McCall2de56d12010-08-25 11:45:40 +00008356 case UO_Real:
8357 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008358 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008359 // _Real and _Imag map ordinary l-values into ordinary l-values.
8360 if (Input->getValueKind() != VK_RValue &&
8361 Input->getObjectKind() == OK_Ordinary)
8362 VK = Input->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00008363 break;
John McCall2de56d12010-08-25 11:45:40 +00008364 case UO_Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00008365 resultType = Input->getType();
John McCallf89e55a2010-11-18 06:31:45 +00008366 VK = Input->getValueKind();
8367 OK = Input->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008368 break;
8369 }
8370 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008371 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008372
John McCallf89e55a2010-11-18 06:31:45 +00008373 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
8374 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008375}
8376
John McCall60d7b3a2010-08-24 06:29:42 +00008377ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008378 UnaryOperatorKind Opc,
8379 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00008380 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00008381 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008382 // Find all of the overloaded operators visible from this
8383 // point. We perform both an operator-name lookup from the local
8384 // scope and an argument-dependent lookup based on the types of
8385 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008386 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008387 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008388 if (S && OverOp != OO_None)
8389 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8390 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008391
John McCall9ae2f072010-08-23 23:25:46 +00008392 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008393 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008394
John McCall9ae2f072010-08-23 23:25:46 +00008395 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008396}
8397
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008398// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008399ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008400 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008401 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008402}
8403
Steve Naroff1b273c42007-09-16 14:56:35 +00008404/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008405ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008406 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008407 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008408 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008409 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008410 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008411}
8412
John McCall60d7b3a2010-08-24 06:29:42 +00008413ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008414Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008415 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008416 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8417 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8418
Douglas Gregordd8f5692010-03-10 04:54:39 +00008419 bool isFileScope
8420 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008421 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008422 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008423
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008424 // FIXME: there are a variety of strange constraints to enforce here, for
8425 // example, it is not possible to goto into a stmt expression apparently.
8426 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008427
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008428 // If there are sub stmts in the compound stmt, take the type of the last one
8429 // as the type of the stmtexpr.
8430 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008431 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008432 if (!Compound->body_empty()) {
8433 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008434 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008435 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008436 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8437 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008438 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008439 }
8440 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008441 // Do function/array conversion on the last expression, but not
8442 // lvalue-to-rvalue. However, initialize an unqualified type.
8443 DefaultFunctionArrayConversion(LastExpr);
8444 Ty = LastExpr->getType().getUnqualifiedType();
8445
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008446 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8447 ExprResult Res = PerformCopyInitialization(
8448 InitializedEntity::InitializeResult(LPLoc,
8449 Ty,
8450 false),
8451 SourceLocation(),
8452 Owned(LastExpr));
8453 if (Res.isInvalid())
8454 return ExprError();
8455 if ((LastExpr = Res.takeAs<Expr>())) {
8456 if (!LastLabelStmt)
8457 Compound->setLastStmt(LastExpr);
8458 else
8459 LastLabelStmt->setSubStmt(LastExpr);
8460 StmtExprMayBindToTemp = true;
8461 }
8462 }
8463 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008464 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008465
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008466 // FIXME: Check that expression type is complete/non-abstract; statement
8467 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008468 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8469 if (StmtExprMayBindToTemp)
8470 return MaybeBindToTemporary(ResStmtExpr);
8471 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008472}
Steve Naroffd34e9152007-08-01 22:05:33 +00008473
John McCall60d7b3a2010-08-24 06:29:42 +00008474ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008475 TypeSourceInfo *TInfo,
8476 OffsetOfComponent *CompPtr,
8477 unsigned NumComponents,
8478 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008479 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008480 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008481 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008482
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008483 // We must have at least one component that refers to the type, and the first
8484 // one is known to be a field designator. Verify that the ArgTy represents
8485 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008486 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008487 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8488 << ArgTy << TypeRange);
8489
8490 // Type must be complete per C99 7.17p3 because a declaring a variable
8491 // with an incomplete type would be ill-formed.
8492 if (!Dependent
8493 && RequireCompleteType(BuiltinLoc, ArgTy,
8494 PDiag(diag::err_offsetof_incomplete_type)
8495 << TypeRange))
8496 return ExprError();
8497
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008498 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8499 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008500 // FIXME: This diagnostic isn't actually visible because the location is in
8501 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008502 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008503 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8504 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008505
8506 bool DidWarnAboutNonPOD = false;
8507 QualType CurrentType = ArgTy;
8508 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8509 llvm::SmallVector<OffsetOfNode, 4> Comps;
8510 llvm::SmallVector<Expr*, 4> Exprs;
8511 for (unsigned i = 0; i != NumComponents; ++i) {
8512 const OffsetOfComponent &OC = CompPtr[i];
8513 if (OC.isBrackets) {
8514 // Offset of an array sub-field. TODO: Should we allow vector elements?
8515 if (!CurrentType->isDependentType()) {
8516 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8517 if(!AT)
8518 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8519 << CurrentType);
8520 CurrentType = AT->getElementType();
8521 } else
8522 CurrentType = Context.DependentTy;
8523
8524 // The expression must be an integral expression.
8525 // FIXME: An integral constant expression?
8526 Expr *Idx = static_cast<Expr*>(OC.U.E);
8527 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8528 !Idx->getType()->isIntegerType())
8529 return ExprError(Diag(Idx->getLocStart(),
8530 diag::err_typecheck_subscript_not_integer)
8531 << Idx->getSourceRange());
8532
8533 // Record this array index.
8534 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8535 Exprs.push_back(Idx);
8536 continue;
8537 }
8538
8539 // Offset of a field.
8540 if (CurrentType->isDependentType()) {
8541 // We have the offset of a field, but we can't look into the dependent
8542 // type. Just record the identifier of the field.
8543 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8544 CurrentType = Context.DependentTy;
8545 continue;
8546 }
8547
8548 // We need to have a complete type to look into.
8549 if (RequireCompleteType(OC.LocStart, CurrentType,
8550 diag::err_offsetof_incomplete_type))
8551 return ExprError();
8552
8553 // Look for the designated field.
8554 const RecordType *RC = CurrentType->getAs<RecordType>();
8555 if (!RC)
8556 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8557 << CurrentType);
8558 RecordDecl *RD = RC->getDecl();
8559
8560 // C++ [lib.support.types]p5:
8561 // The macro offsetof accepts a restricted set of type arguments in this
8562 // International Standard. type shall be a POD structure or a POD union
8563 // (clause 9).
8564 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8565 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8566 DiagRuntimeBehavior(BuiltinLoc,
8567 PDiag(diag::warn_offsetof_non_pod_type)
8568 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8569 << CurrentType))
8570 DidWarnAboutNonPOD = true;
8571 }
8572
8573 // Look for the field.
8574 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8575 LookupQualifiedName(R, RD);
8576 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008577 IndirectFieldDecl *IndirectMemberDecl = 0;
8578 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008579 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008580 MemberDecl = IndirectMemberDecl->getAnonField();
8581 }
8582
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008583 if (!MemberDecl)
8584 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8585 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8586 OC.LocEnd));
8587
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008588 // C99 7.17p3:
8589 // (If the specified member is a bit-field, the behavior is undefined.)
8590 //
8591 // We diagnose this as an error.
8592 if (MemberDecl->getBitWidth()) {
8593 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8594 << MemberDecl->getDeclName()
8595 << SourceRange(BuiltinLoc, RParenLoc);
8596 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8597 return ExprError();
8598 }
Eli Friedman19410a72010-08-05 10:11:36 +00008599
8600 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008601 if (IndirectMemberDecl)
8602 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008603
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008604 // If the member was found in a base class, introduce OffsetOfNodes for
8605 // the base class indirections.
8606 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8607 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008608 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008609 CXXBasePath &Path = Paths.front();
8610 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8611 B != BEnd; ++B)
8612 Comps.push_back(OffsetOfNode(B->Base));
8613 }
Eli Friedman19410a72010-08-05 10:11:36 +00008614
Francois Pichet87c2e122010-11-21 06:08:52 +00008615 if (IndirectMemberDecl) {
8616 for (IndirectFieldDecl::chain_iterator FI =
8617 IndirectMemberDecl->chain_begin(),
8618 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8619 assert(isa<FieldDecl>(*FI));
8620 Comps.push_back(OffsetOfNode(OC.LocStart,
8621 cast<FieldDecl>(*FI), OC.LocEnd));
8622 }
8623 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008624 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008625
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008626 CurrentType = MemberDecl->getType().getNonReferenceType();
8627 }
8628
8629 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8630 TInfo, Comps.data(), Comps.size(),
8631 Exprs.data(), Exprs.size(), RParenLoc));
8632}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008633
John McCall60d7b3a2010-08-24 06:29:42 +00008634ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008635 SourceLocation BuiltinLoc,
8636 SourceLocation TypeLoc,
8637 ParsedType argty,
8638 OffsetOfComponent *CompPtr,
8639 unsigned NumComponents,
8640 SourceLocation RPLoc) {
8641
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008642 TypeSourceInfo *ArgTInfo;
8643 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8644 if (ArgTy.isNull())
8645 return ExprError();
8646
Eli Friedman5a15dc12010-08-05 10:15:45 +00008647 if (!ArgTInfo)
8648 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8649
8650 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8651 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008652}
8653
8654
John McCall60d7b3a2010-08-24 06:29:42 +00008655ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008656 Expr *CondExpr,
8657 Expr *LHSExpr, Expr *RHSExpr,
8658 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008659 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8660
John McCallf89e55a2010-11-18 06:31:45 +00008661 ExprValueKind VK = VK_RValue;
8662 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008663 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008664 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008665 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008666 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008667 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008668 } else {
8669 // The conditional expression is required to be a constant expression.
8670 llvm::APSInt condEval(32);
8671 SourceLocation ExpLoc;
8672 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008673 return ExprError(Diag(ExpLoc,
8674 diag::err_typecheck_choose_expr_requires_constant)
8675 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008676
Sebastian Redl28507842009-02-26 14:39:58 +00008677 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008678 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8679
8680 resType = ActiveExpr->getType();
8681 ValueDependent = ActiveExpr->isValueDependent();
8682 VK = ActiveExpr->getValueKind();
8683 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008684 }
8685
Sebastian Redlf53597f2009-03-15 17:47:39 +00008686 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008687 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008688 resType->isDependentType(),
8689 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008690}
8691
Steve Naroff4eb206b2008-09-03 18:15:37 +00008692//===----------------------------------------------------------------------===//
8693// Clang Extensions.
8694//===----------------------------------------------------------------------===//
8695
8696/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00008697void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008698 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8699 PushBlockScope(BlockScope, Block);
8700 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008701 if (BlockScope)
8702 PushDeclContext(BlockScope, Block);
8703 else
8704 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00008705}
8706
Mike Stump98eb8a72009-02-04 22:31:32 +00008707void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008708 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008709 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008710 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008711
John McCallbf1a0282010-06-04 23:28:52 +00008712 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008713 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008714
John McCall711c52b2011-01-05 12:14:39 +00008715 // GetTypeForDeclarator always produces a function type for a block
8716 // literal signature. Furthermore, it is always a FunctionProtoType
8717 // unless the function was written with a typedef.
8718 assert(T->isFunctionType() &&
8719 "GetTypeForDeclarator made a non-function block signature");
8720
8721 // Look for an explicit signature in that function type.
8722 FunctionProtoTypeLoc ExplicitSignature;
8723
8724 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8725 if (isa<FunctionProtoTypeLoc>(tmp)) {
8726 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8727
8728 // Check whether that explicit signature was synthesized by
8729 // GetTypeForDeclarator. If so, don't save that as part of the
8730 // written signature.
8731 if (ExplicitSignature.getLParenLoc() ==
8732 ExplicitSignature.getRParenLoc()) {
8733 // This would be much cheaper if we stored TypeLocs instead of
8734 // TypeSourceInfos.
8735 TypeLoc Result = ExplicitSignature.getResultLoc();
8736 unsigned Size = Result.getFullDataSize();
8737 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8738 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8739
8740 ExplicitSignature = FunctionProtoTypeLoc();
8741 }
John McCall82dc0092010-06-04 11:21:44 +00008742 }
Mike Stump1eb44332009-09-09 15:08:12 +00008743
John McCall711c52b2011-01-05 12:14:39 +00008744 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8745 CurBlock->FunctionType = T;
8746
8747 const FunctionType *Fn = T->getAs<FunctionType>();
8748 QualType RetTy = Fn->getResultType();
8749 bool isVariadic =
8750 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8751
John McCallc71a4912010-06-04 19:02:56 +00008752 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008753
John McCall82dc0092010-06-04 11:21:44 +00008754 // Don't allow returning a objc interface by value.
8755 if (RetTy->isObjCObjectType()) {
8756 Diag(ParamInfo.getSourceRange().getBegin(),
8757 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8758 return;
8759 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008760
John McCall82dc0092010-06-04 11:21:44 +00008761 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008762 // return type. TODO: what should we do with declarators like:
8763 // ^ * { ... }
8764 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00008765 if (RetTy != Context.DependentTy)
8766 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008767
John McCall82dc0092010-06-04 11:21:44 +00008768 // Push block parameters from the declarator if we had them.
John McCallc71a4912010-06-04 19:02:56 +00008769 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008770 if (ExplicitSignature) {
8771 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8772 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008773 if (Param->getIdentifier() == 0 &&
8774 !Param->isImplicit() &&
8775 !Param->isInvalidDecl() &&
8776 !getLangOptions().CPlusPlus)
8777 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008778 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008779 }
John McCall82dc0092010-06-04 11:21:44 +00008780
8781 // Fake up parameter variables if we have a typedef, like
8782 // ^ fntype { ... }
8783 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8784 for (FunctionProtoType::arg_type_iterator
8785 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8786 ParmVarDecl *Param =
8787 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8788 ParamInfo.getSourceRange().getBegin(),
8789 *I);
John McCallc71a4912010-06-04 19:02:56 +00008790 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008791 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008792 }
John McCall82dc0092010-06-04 11:21:44 +00008793
John McCallc71a4912010-06-04 19:02:56 +00008794 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008795 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00008796 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00008797 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8798 CurBlock->TheDecl->param_end(),
8799 /*CheckParameterNames=*/false);
8800 }
8801
John McCall82dc0092010-06-04 11:21:44 +00008802 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008803 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008804
John McCallc71a4912010-06-04 19:02:56 +00008805 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008806 Diag(ParamInfo.getAttributes()->getLoc(),
8807 diag::warn_attribute_sentinel_not_variadic) << 1;
8808 // FIXME: remove the attribute.
8809 }
8810
8811 // Put the parameter variables in scope. We can bail out immediately
8812 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008813 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008814 return;
8815
Steve Naroff090276f2008-10-10 01:28:17 +00008816 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008817 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8818 (*AI)->setOwningFunction(CurBlock->TheDecl);
8819
Steve Naroff090276f2008-10-10 01:28:17 +00008820 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008821 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008822 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008823
Steve Naroff090276f2008-10-10 01:28:17 +00008824 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008825 }
John McCall7a9813c2010-01-22 00:28:27 +00008826 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008827}
8828
8829/// ActOnBlockError - If there is an error parsing a block, this callback
8830/// is invoked to pop the information about the block from the action impl.
8831void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00008832 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008833 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008834 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008835}
8836
8837/// ActOnBlockStmtExpr - This is called when the body of a block statement
8838/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008839ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00008840 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008841 // If blocks are disabled, emit an error.
8842 if (!LangOpts.Blocks)
8843 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008844
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008845 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008846
Steve Naroff090276f2008-10-10 01:28:17 +00008847 PopDeclContext();
8848
Steve Naroff4eb206b2008-09-03 18:15:37 +00008849 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008850 if (!BSI->ReturnType.isNull())
8851 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008852
Mike Stump56925862009-07-28 22:04:01 +00008853 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008854 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008855
John McCall469a1eb2011-02-02 13:00:07 +00008856 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00008857 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8858 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00008859
John McCallc71a4912010-06-04 19:02:56 +00008860 // If the user wrote a function type in some form, try to use that.
8861 if (!BSI->FunctionType.isNull()) {
8862 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8863
8864 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8865 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8866
8867 // Turn protoless block types into nullary block types.
8868 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00008869 FunctionProtoType::ExtProtoInfo EPI;
8870 EPI.ExtInfo = Ext;
8871 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008872
8873 // Otherwise, if we don't need to change anything about the function type,
8874 // preserve its sugar structure.
8875 } else if (FTy->getResultType() == RetTy &&
8876 (!NoReturn || FTy->getNoReturnAttr())) {
8877 BlockTy = BSI->FunctionType;
8878
8879 // Otherwise, make the minimal modifications to the function type.
8880 } else {
8881 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00008882 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8883 EPI.TypeQuals = 0; // FIXME: silently?
8884 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00008885 BlockTy = Context.getFunctionType(RetTy,
8886 FPT->arg_type_begin(),
8887 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00008888 EPI);
John McCallc71a4912010-06-04 19:02:56 +00008889 }
8890
8891 // If we don't have a function type, just build one from nothing.
8892 } else {
John McCalle23cf432010-12-14 08:05:40 +00008893 FunctionProtoType::ExtProtoInfo EPI;
8894 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
8895 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008896 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008897
John McCallc71a4912010-06-04 19:02:56 +00008898 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8899 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00008900 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008901
Chris Lattner17a78302009-04-19 05:28:12 +00008902 // If needed, diagnose invalid gotos and switches in the block.
John McCall781472f2010-08-25 08:40:02 +00008903 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00008904 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00008905
Chris Lattnere476bdc2011-02-17 23:58:47 +00008906 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008907
John McCall469a1eb2011-02-02 13:00:07 +00008908 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCalle0054f62010-08-25 05:56:39 +00008909
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00008910 // Issue any analysis-based warnings.
Ted Kremenekd064fdc2010-03-23 00:13:23 +00008911 const sema::AnalysisBasedWarnings::Policy &WP =
8912 AnalysisWarnings.getDefaultPolicy();
John McCalle0054f62010-08-25 05:56:39 +00008913 AnalysisWarnings.IssueWarnings(WP, Result);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00008914
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008915 PopFunctionOrBlockScope();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008916 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00008917}
8918
John McCall60d7b3a2010-08-24 06:29:42 +00008919ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00008920 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008921 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008922 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008923 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00008924 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008925}
8926
John McCall60d7b3a2010-08-24 06:29:42 +00008927ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00008928 Expr *E, TypeSourceInfo *TInfo,
8929 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008930 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00008931
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008932 // Get the va_list type
8933 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008934 if (VaListType->isArrayType()) {
8935 // Deal with implicit array decay; for example, on x86-64,
8936 // va_list is an array, but it's supposed to decay to
8937 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008938 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00008939 // Make sure the input expression also decays appropriately.
8940 UsualUnaryConversions(E);
8941 } else {
8942 // Otherwise, the va_list argument must be an l-value because
8943 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00008944 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00008945 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00008946 return ExprError();
8947 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008948
Douglas Gregordd027302009-05-19 23:10:31 +00008949 if (!E->isTypeDependent() &&
8950 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00008951 return ExprError(Diag(E->getLocStart(),
8952 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008953 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00008954 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008955
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008956 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008957 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008958
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008959 QualType T = TInfo->getType().getNonLValueExprType(Context);
8960 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008961}
8962
John McCall60d7b3a2010-08-24 06:29:42 +00008963ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008964 // The type of __null will be int or long, depending on the size of
8965 // pointers on the target.
8966 QualType Ty;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008967 unsigned pw = Context.Target.getPointerWidth(0);
8968 if (pw == Context.Target.getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008969 Ty = Context.IntTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008970 else if (pw == Context.Target.getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008971 Ty = Context.LongTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008972 else if (pw == Context.Target.getLongLongWidth())
8973 Ty = Context.LongLongTy;
8974 else {
8975 assert(!"I don't know size of pointer!");
8976 Ty = Context.IntTy;
8977 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008978
Sebastian Redlf53597f2009-03-15 17:47:39 +00008979 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008980}
8981
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008982static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00008983 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008984 if (!SemaRef.getLangOptions().ObjC1)
8985 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008986
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008987 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8988 if (!PT)
8989 return;
8990
8991 // Check if the destination is of type 'id'.
8992 if (!PT->isObjCIdType()) {
8993 // Check if the destination is the 'NSString' interface.
8994 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8995 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8996 return;
8997 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008998
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008999 // Strip off any parens and casts.
9000 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9001 if (!SL || SL->isWide())
9002 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009003
Douglas Gregor849b2432010-03-31 17:46:05 +00009004 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009005}
9006
Chris Lattner5cf216b2008-01-04 18:04:52 +00009007bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9008 SourceLocation Loc,
9009 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009010 Expr *SrcExpr, AssignmentAction Action,
9011 bool *Complained) {
9012 if (Complained)
9013 *Complained = false;
9014
Chris Lattner5cf216b2008-01-04 18:04:52 +00009015 // Decode the result (notice that AST's are still created for extensions).
9016 bool isInvalid = false;
9017 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00009018 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009019
Chris Lattner5cf216b2008-01-04 18:04:52 +00009020 switch (ConvTy) {
9021 default: assert(0 && "Unknown conversion type");
9022 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009023 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009024 DiagKind = diag::ext_typecheck_convert_pointer_int;
9025 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009026 case IntToPointer:
9027 DiagKind = diag::ext_typecheck_convert_int_pointer;
9028 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009029 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009030 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009031 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9032 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009033 case IncompatiblePointerSign:
9034 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9035 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009036 case FunctionVoidPointer:
9037 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9038 break;
John McCall86c05f32011-02-01 00:10:29 +00009039 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009040 // Perform array-to-pointer decay if necessary.
9041 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9042
John McCall86c05f32011-02-01 00:10:29 +00009043 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9044 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9045 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9046 DiagKind = diag::err_typecheck_incompatible_address_space;
9047 break;
9048 }
9049
9050 llvm_unreachable("unknown error case for discarding qualifiers!");
9051 // fallthrough
9052 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009053 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009054 // If the qualifiers lost were because we were applying the
9055 // (deprecated) C++ conversion from a string literal to a char*
9056 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9057 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009058 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009059 // bit of refactoring (so that the second argument is an
9060 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009061 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009062 // C++ semantics.
9063 if (getLangOptions().CPlusPlus &&
9064 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9065 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009066 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9067 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009068 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009069 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009070 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009071 case IntToBlockPointer:
9072 DiagKind = diag::err_int_to_block_pointer;
9073 break;
9074 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009075 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009076 break;
Steve Naroff39579072008-10-14 22:18:38 +00009077 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009078 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009079 // it can give a more specific diagnostic.
9080 DiagKind = diag::warn_incompatible_qualified_id;
9081 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009082 case IncompatibleVectors:
9083 DiagKind = diag::warn_incompatible_vectors;
9084 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009085 case Incompatible:
9086 DiagKind = diag::err_typecheck_convert_incompatible;
9087 isInvalid = true;
9088 break;
9089 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009090
Douglas Gregord4eea832010-04-09 00:35:39 +00009091 QualType FirstType, SecondType;
9092 switch (Action) {
9093 case AA_Assigning:
9094 case AA_Initializing:
9095 // The destination type comes first.
9096 FirstType = DstType;
9097 SecondType = SrcType;
9098 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009099
Douglas Gregord4eea832010-04-09 00:35:39 +00009100 case AA_Returning:
9101 case AA_Passing:
9102 case AA_Converting:
9103 case AA_Sending:
9104 case AA_Casting:
9105 // The source type comes first.
9106 FirstType = SrcType;
9107 SecondType = DstType;
9108 break;
9109 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009110
Douglas Gregord4eea832010-04-09 00:35:39 +00009111 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009112 << SrcExpr->getSourceRange() << Hint;
Douglas Gregora41a8c52010-04-22 00:20:18 +00009113 if (Complained)
9114 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009115 return isInvalid;
9116}
Anders Carlssone21555e2008-11-30 19:50:32 +00009117
Chris Lattner3bf68932009-04-25 21:59:05 +00009118bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009119 llvm::APSInt ICEResult;
9120 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9121 if (Result)
9122 *Result = ICEResult;
9123 return false;
9124 }
9125
Anders Carlssone21555e2008-11-30 19:50:32 +00009126 Expr::EvalResult EvalResult;
9127
Mike Stumpeed9cac2009-02-19 03:04:26 +00009128 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009129 EvalResult.HasSideEffects) {
9130 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9131
9132 if (EvalResult.Diag) {
9133 // We only show the note if it's not the usual "invalid subexpression"
9134 // or if it's actually in a subexpression.
9135 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9136 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9137 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9138 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009139
Anders Carlssone21555e2008-11-30 19:50:32 +00009140 return true;
9141 }
9142
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009143 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9144 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009145
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009146 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009147 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9148 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009149 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009150
Anders Carlssone21555e2008-11-30 19:50:32 +00009151 if (Result)
9152 *Result = EvalResult.Val.getInt();
9153 return false;
9154}
Douglas Gregore0762c92009-06-19 23:52:42 +00009155
Douglas Gregor2afce722009-11-26 00:44:06 +00009156void
Mike Stump1eb44332009-09-09 15:08:12 +00009157Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009158 ExprEvalContexts.push_back(
9159 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00009160}
9161
Mike Stump1eb44332009-09-09 15:08:12 +00009162void
Douglas Gregor2afce722009-11-26 00:44:06 +00009163Sema::PopExpressionEvaluationContext() {
9164 // Pop the current expression evaluation context off the stack.
9165 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9166 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009167
Douglas Gregor06d33692009-12-12 07:57:52 +00009168 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9169 if (Rec.PotentiallyReferenced) {
9170 // Mark any remaining declarations in the current position of the stack
9171 // as "referenced". If they were not meant to be referenced, semantic
9172 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009173 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009174 I = Rec.PotentiallyReferenced->begin(),
9175 IEnd = Rec.PotentiallyReferenced->end();
9176 I != IEnd; ++I)
9177 MarkDeclarationReferenced(I->first, I->second);
9178 }
9179
9180 if (Rec.PotentiallyDiagnosed) {
9181 // Emit any pending diagnostics.
9182 for (PotentiallyEmittedDiagnostics::iterator
9183 I = Rec.PotentiallyDiagnosed->begin(),
9184 IEnd = Rec.PotentiallyDiagnosed->end();
9185 I != IEnd; ++I)
9186 Diag(I->first, I->second);
9187 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009188 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009189
9190 // When are coming out of an unevaluated context, clear out any
9191 // temporaries that we may have created as part of the evaluation of
9192 // the expression in that context: they aren't relevant because they
9193 // will never be constructed.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009194 if (Rec.Context == Unevaluated &&
Douglas Gregor2afce722009-11-26 00:44:06 +00009195 ExprTemporaries.size() > Rec.NumTemporaries)
9196 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9197 ExprTemporaries.end());
9198
9199 // Destroy the popped expression evaluation record.
9200 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009201}
Douglas Gregore0762c92009-06-19 23:52:42 +00009202
9203/// \brief Note that the given declaration was referenced in the source code.
9204///
9205/// This routine should be invoke whenever a given declaration is referenced
9206/// in the source code, and where that reference occurred. If this declaration
9207/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9208/// C99 6.9p3), then the declaration will be marked as used.
9209///
9210/// \param Loc the location where the declaration was referenced.
9211///
9212/// \param D the declaration that has been referenced by the source code.
9213void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9214 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009215
Douglas Gregorc070cc62010-06-17 23:14:26 +00009216 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009217 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009218
Douglas Gregorb5352cf2009-10-08 21:35:42 +00009219 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9220 // template or not. The reason for this is that unevaluated expressions
9221 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9222 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009223 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009224 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009225 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009226 return;
9227 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009228
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009229 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9230 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009231
Douglas Gregore0762c92009-06-19 23:52:42 +00009232 // Do not mark anything as "used" within a dependent context; wait for
9233 // an instantiation.
9234 if (CurContext->isDependentContext())
9235 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009236
Douglas Gregor2afce722009-11-26 00:44:06 +00009237 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009238 case Unevaluated:
9239 // We are in an expression that is not potentially evaluated; do nothing.
9240 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009241
Douglas Gregorac7610d2009-06-22 20:57:11 +00009242 case PotentiallyEvaluated:
9243 // We are in a potentially-evaluated expression, so this declaration is
9244 // "used"; handle this below.
9245 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009246
Douglas Gregorac7610d2009-06-22 20:57:11 +00009247 case PotentiallyPotentiallyEvaluated:
9248 // We are in an expression that may be potentially evaluated; queue this
9249 // declaration reference until we know whether the expression is
9250 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009251 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009252 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009253
9254 case PotentiallyEvaluatedIfUsed:
9255 // Referenced declarations will only be used if the construct in the
9256 // containing expression is used.
9257 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009258 }
Mike Stump1eb44332009-09-09 15:08:12 +00009259
Douglas Gregore0762c92009-06-19 23:52:42 +00009260 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009261 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009262 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00009263 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00009264 if (Constructor->getParent()->hasTrivialConstructor())
9265 return;
9266 if (!Constructor->isUsed(false))
9267 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00009268 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00009269 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009270 if (!Constructor->isUsed(false))
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009271 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9272 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009273
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009274 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009275 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009276 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009277 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009278 if (Destructor->isVirtual())
9279 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009280 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9281 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9282 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009283 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +00009284 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009285 } else if (MethodDecl->isVirtual())
9286 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009287 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009288 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009289 // Recursive functions should be marked when used from another function.
9290 if (CurContext == Function) return;
9291
Mike Stump1eb44332009-09-09 15:08:12 +00009292 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009293 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009294 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009295 bool AlreadyInstantiated = false;
9296 if (FunctionTemplateSpecializationInfo *SpecInfo
9297 = Function->getTemplateSpecializationInfo()) {
9298 if (SpecInfo->getPointOfInstantiation().isInvalid())
9299 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009300 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009301 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009302 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009303 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009304 = Function->getMemberSpecializationInfo()) {
9305 if (MSInfo->getPointOfInstantiation().isInvalid())
9306 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009307 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009308 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009309 AlreadyInstantiated = true;
9310 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009311
Douglas Gregor60406be2010-01-16 22:29:39 +00009312 if (!AlreadyInstantiated) {
9313 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9314 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9315 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9316 Loc));
9317 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009318 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009319 }
John McCall15e310a2011-02-19 02:53:41 +00009320 } else {
9321 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00009322 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9323 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009324 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009325 MarkDeclarationReferenced(Loc, *i);
9326 }
John McCall15e310a2011-02-19 02:53:41 +00009327 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009328
John McCall15e310a2011-02-19 02:53:41 +00009329 // Keep track of used but undefined functions.
9330 if (!Function->isPure() && !Function->hasBody() &&
9331 Function->getLinkage() != ExternalLinkage) {
9332 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9333 if (old.isInvalid()) old = Loc;
9334 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009335
John McCall15e310a2011-02-19 02:53:41 +00009336 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00009337 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009338 }
Mike Stump1eb44332009-09-09 15:08:12 +00009339
Douglas Gregore0762c92009-06-19 23:52:42 +00009340 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009341 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009342 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009343 Var->getInstantiatedFromStaticDataMember()) {
9344 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9345 assert(MSInfo && "Missing member specialization information?");
9346 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9347 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9348 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009349 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009350 }
9351 }
Mike Stump1eb44332009-09-09 15:08:12 +00009352
John McCall15e310a2011-02-19 02:53:41 +00009353 // Keep track of used but undefined variables.
9354 if (Var->hasDefinition() == VarDecl::DeclarationOnly
9355 && Var->getLinkage() != ExternalLinkage) {
9356 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9357 if (old.isInvalid()) old = Loc;
9358 }
Douglas Gregor7caa6822009-07-24 20:34:43 +00009359
Douglas Gregore0762c92009-06-19 23:52:42 +00009360 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00009361 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00009362 }
Douglas Gregore0762c92009-06-19 23:52:42 +00009363}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009364
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009365namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009366 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009367 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009368 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009369 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9370 Sema &S;
9371 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009372
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009373 public:
9374 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009375
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009376 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009377
9378 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9379 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009380 };
9381}
9382
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009383bool MarkReferencedDecls::TraverseTemplateArgument(
9384 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009385 if (Arg.getKind() == TemplateArgument::Declaration) {
9386 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9387 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009388
9389 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009390}
9391
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009392bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009393 if (ClassTemplateSpecializationDecl *Spec
9394 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9395 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00009396 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009397 }
9398
Chandler Carruthe3e210c2010-06-10 10:31:57 +00009399 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009400}
9401
9402void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9403 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009404 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009405}
9406
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009407namespace {
9408 /// \brief Helper class that marks all of the declarations referenced by
9409 /// potentially-evaluated subexpressions as "referenced".
9410 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9411 Sema &S;
9412
9413 public:
9414 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9415
9416 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9417
9418 void VisitDeclRefExpr(DeclRefExpr *E) {
9419 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9420 }
9421
9422 void VisitMemberExpr(MemberExpr *E) {
9423 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009424 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009425 }
9426
9427 void VisitCXXNewExpr(CXXNewExpr *E) {
9428 if (E->getConstructor())
9429 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9430 if (E->getOperatorNew())
9431 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9432 if (E->getOperatorDelete())
9433 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009434 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009435 }
9436
9437 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9438 if (E->getOperatorDelete())
9439 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009440 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9441 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9442 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9443 S.MarkDeclarationReferenced(E->getLocStart(),
9444 S.LookupDestructor(Record));
9445 }
9446
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009447 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009448 }
9449
9450 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9451 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009452 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009453 }
9454
9455 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9456 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9457 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009458
9459 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9460 Visit(E->getExpr());
9461 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009462 };
9463}
9464
9465/// \brief Mark any declarations that appear within this expression or any
9466/// potentially-evaluated subexpressions as "referenced".
9467void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9468 EvaluatedExprMarker(*this).Visit(E);
9469}
9470
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009471/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9472/// of the program being compiled.
9473///
9474/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009475/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009476/// possibility that the code will actually be executable. Code in sizeof()
9477/// expressions, code used only during overload resolution, etc., are not
9478/// potentially evaluated. This routine will suppress such diagnostics or,
9479/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009480/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009481/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009482///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009483/// This routine should be used for all diagnostics that describe the run-time
9484/// behavior of a program, such as passing a non-POD value through an ellipsis.
9485/// Failure to do so will likely result in spurious diagnostics or failures
9486/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009487bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009488 const PartialDiagnostic &PD) {
9489 switch (ExprEvalContexts.back().Context ) {
9490 case Unevaluated:
9491 // The argument will never be evaluated, so don't complain.
9492 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009493
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009494 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009495 case PotentiallyEvaluatedIfUsed:
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009496 Diag(Loc, PD);
9497 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009498
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009499 case PotentiallyPotentiallyEvaluated:
9500 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9501 break;
9502 }
9503
9504 return false;
9505}
9506
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009507bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9508 CallExpr *CE, FunctionDecl *FD) {
9509 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9510 return false;
9511
9512 PartialDiagnostic Note =
9513 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9514 << FD->getDeclName() : PDiag();
9515 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009516
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009517 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009518 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009519 PDiag(diag::err_call_function_incomplete_return)
9520 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009521 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009522 << CE->getSourceRange(),
9523 std::make_pair(NoteLoc, Note)))
9524 return true;
9525
9526 return false;
9527}
9528
Douglas Gregor92c3a042011-01-19 16:50:08 +00009529// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +00009530// will prevent this condition from triggering, which is what we want.
9531void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9532 SourceLocation Loc;
9533
John McCalla52ef082009-11-11 02:41:58 +00009534 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +00009535 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +00009536
John McCall5a881bb2009-10-12 21:59:07 +00009537 if (isa<BinaryOperator>(E)) {
9538 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +00009539 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +00009540 return;
9541
Douglas Gregor92c3a042011-01-19 16:50:08 +00009542 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9543
John McCallc8d8ac52009-11-12 00:06:05 +00009544 // Greylist some idioms by putting them into a warning subcategory.
9545 if (ObjCMessageExpr *ME
9546 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9547 Selector Sel = ME->getSelector();
9548
John McCallc8d8ac52009-11-12 00:06:05 +00009549 // self = [<foo> init...]
Douglas Gregor813d8342011-02-18 22:29:55 +00009550 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +00009551 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9552
9553 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +00009554 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +00009555 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9556 }
John McCalla52ef082009-11-11 02:41:58 +00009557
John McCall5a881bb2009-10-12 21:59:07 +00009558 Loc = Op->getOperatorLoc();
9559 } else if (isa<CXXOperatorCallExpr>(E)) {
9560 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +00009561 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +00009562 return;
9563
Douglas Gregor92c3a042011-01-19 16:50:08 +00009564 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +00009565 Loc = Op->getOperatorLoc();
9566 } else {
9567 // Not an assignment.
9568 return;
9569 }
9570
John McCall5a881bb2009-10-12 21:59:07 +00009571 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00009572 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009573
Douglas Gregor55b38842010-04-14 16:09:52 +00009574 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +00009575
9576 if (IsOrAssign)
9577 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9578 << FixItHint::CreateReplacement(Loc, "!=");
9579 else
9580 Diag(Loc, diag::note_condition_assign_to_comparison)
9581 << FixItHint::CreateReplacement(Loc, "==");
9582
Douglas Gregor55b38842010-04-14 16:09:52 +00009583 Diag(Loc, diag::note_condition_assign_silence)
9584 << FixItHint::CreateInsertion(Open, "(")
9585 << FixItHint::CreateInsertion(Close, ")");
John McCall5a881bb2009-10-12 21:59:07 +00009586}
9587
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009588/// \brief Redundant parentheses over an equality comparison can indicate
9589/// that the user intended an assignment used as condition.
9590void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009591 // Don't warn if the parens came from a macro.
9592 SourceLocation parenLoc = parenE->getLocStart();
9593 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9594 return;
9595
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009596 Expr *E = parenE->IgnoreParens();
9597
9598 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +00009599 if (opE->getOpcode() == BO_EQ &&
9600 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9601 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009602 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +00009603
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009604 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9605 Diag(Loc, diag::note_equality_comparison_to_assign)
9606 << FixItHint::CreateReplacement(Loc, "=");
9607 Diag(Loc, diag::note_equality_comparison_silence)
9608 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9609 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009610 }
9611}
9612
John McCall5a881bb2009-10-12 21:59:07 +00009613bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9614 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009615 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9616 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +00009617
9618 if (!E->isTypeDependent()) {
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009619 if (E->isBoundMemberFunction(Context))
9620 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9621 << E->getSourceRange();
9622
John McCallf6a16482010-12-04 03:47:34 +00009623 if (getLangOptions().CPlusPlus)
9624 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9625
9626 DefaultFunctionArrayLvalueConversion(E);
John McCallabc56c72010-12-04 06:09:13 +00009627
9628 QualType T = E->getType();
John McCallf6a16482010-12-04 03:47:34 +00009629 if (!T->isScalarType()) // C99 6.8.4.1p1
9630 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9631 << T << E->getSourceRange();
John McCall5a881bb2009-10-12 21:59:07 +00009632 }
9633
9634 return false;
9635}
Douglas Gregor586596f2010-05-06 17:25:47 +00009636
John McCall60d7b3a2010-08-24 06:29:42 +00009637ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9638 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +00009639 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +00009640 return ExprError();
9641
Douglas Gregorff331c12010-07-25 18:17:45 +00009642 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregor586596f2010-05-06 17:25:47 +00009643 return ExprError();
Douglas Gregor586596f2010-05-06 17:25:47 +00009644
9645 return Owned(Sub);
9646}
John McCall2a984ca2010-10-12 00:20:44 +00009647
9648/// Check for operands with placeholder types and complain if found.
9649/// Returns true if there was an error and no recovery was possible.
9650ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9651 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9652 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9653
9654 // If this is overload, check for a single overload.
Richard Smith34b41d92011-02-20 03:19:35 +00009655 assert(BT->getKind() == BuiltinType::Overload);
John McCall2a984ca2010-10-12 00:20:44 +00009656
Richard Smith34b41d92011-02-20 03:19:35 +00009657 if (FunctionDecl *Specialization
9658 = ResolveSingleFunctionTemplateSpecialization(E)) {
9659 // The access doesn't really matter in this case.
9660 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9661 Specialization->getAccess());
9662 E = FixOverloadedFunctionReference(E, Found, Specialization);
9663 if (!E) return ExprError();
9664 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +00009665 }
9666
Richard Smith34b41d92011-02-20 03:19:35 +00009667 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
John McCall2a984ca2010-10-12 00:20:44 +00009668 return ExprError();
9669}