blob: 6892424e099d65867787b5dd620339265dd73f06 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/ASTContext.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000023#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000024#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000026#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000027#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000031#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000033#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Designator.h"
35#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000036#include "clang/Sema/ScopeInfo.h"
John McCall19510852010-08-20 18:27:03 +000037#include "clang/Sema/ParsedTemplate.h"
John McCall7cd088e2010-08-24 07:21:54 +000038#include "clang/Sema/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000039using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000040using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000041
David Chisnall0f436562009-08-17 16:35:33 +000042
Douglas Gregor48f3bb92009-02-18 21:56:37 +000043/// \brief Determine whether the use of this declaration is valid, and
44/// emit any corresponding diagnostics.
45///
46/// This routine diagnoses various problems with referencing
47/// declarations that can occur when using a declaration. For example,
48/// it might warn if a deprecated or unavailable declaration is being
49/// used, or produce an error (and return true) if a C++0x deleted
50/// function is being used.
51///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000052/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattner52338262009-10-25 22:31:57 +000053/// decls.
54///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000055/// \returns true if there was an error (this declaration cannot be
56/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000057///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000058bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Peter Collingbourne743b82b2011-01-02 19:53:12 +000059 bool UnknownObjCClass) {
Douglas Gregor9b623632010-10-12 23:32:35 +000060 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
61 // If there were any diagnostics suppressed by template argument deduction,
62 // emit them now.
63 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
64 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
65 if (Pos != SuppressedDiagnostics.end()) {
66 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
67 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
68 Diag(Suppressed[I].first, Suppressed[I].second);
69
70 // Clear out the list of suppressed diagnostics, so that we don't emit
71 // them again for this specialization. However, we don't remove this
72 // entry from the table, because we want to avoid ever emitting these
73 // diagnostics again.
74 Suppressed.clear();
75 }
76 }
77
Chris Lattner76a642f2009-02-15 22:43:40 +000078 // See if the decl is deprecated.
Benjamin Kramerce2d1862010-10-09 15:49:00 +000079 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>())
Peter Collingbourne743b82b2011-01-02 19:53:12 +000080 EmitDeprecationWarning(D, DA->getMessage(), Loc, UnknownObjCClass);
Chris Lattner76a642f2009-02-15 22:43:40 +000081
Chris Lattnerffb93682009-10-25 17:21:40 +000082 // See if the decl is unavailable
Fariborz Jahanianc784dc12010-10-06 23:12:32 +000083 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) {
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000084 if (UA->getMessage().empty()) {
Peter Collingbourne743b82b2011-01-02 19:53:12 +000085 if (!UnknownObjCClass)
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000086 Diag(Loc, diag::err_unavailable) << D->getDeclName();
87 else
88 Diag(Loc, diag::warn_unavailable_fwdclass_message)
89 << D->getDeclName();
90 }
91 else
Fariborz Jahanianc784dc12010-10-06 23:12:32 +000092 Diag(Loc, diag::err_unavailable_message)
Benjamin Kramerce2d1862010-10-09 15:49:00 +000093 << D->getDeclName() << UA->getMessage();
Chris Lattnerffb93682009-10-25 17:21:40 +000094 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
95 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000096
Douglas Gregor48f3bb92009-02-18 21:56:37 +000097 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000098 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000099 if (FD->isDeleted()) {
100 Diag(Loc, diag::err_deleted_function_use);
101 Diag(D->getLocation(), diag::note_unavailable_here) << true;
102 return true;
103 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000104 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000105
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000106 // Warn if this is used but marked unused.
107 if (D->hasAttr<UnusedAttr>())
108 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
109
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000110 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000111}
112
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000113/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +0000114/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000115/// attribute. It warns if call does not have the sentinel argument.
116///
117void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000118 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000119 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000120 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000121 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000122
123 // FIXME: In C++0x, if any of the arguments are parameter pack
124 // expansions, we can't check for the sentinel now.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000125 int sentinelPos = attr->getSentinel();
126 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +0000127
Mike Stump390b4cc2009-05-16 07:39:55 +0000128 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
129 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000130 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000131 bool warnNotEnoughArgs = false;
132 int isMethod = 0;
133 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
134 // skip over named parameters.
135 ObjCMethodDecl::param_iterator P, E = MD->param_end();
136 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
137 if (nullPos)
138 --nullPos;
139 else
140 ++i;
141 }
142 warnNotEnoughArgs = (P != E || i >= NumArgs);
143 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000144 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000145 // skip over named parameters.
146 ObjCMethodDecl::param_iterator P, E = FD->param_end();
147 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
148 if (nullPos)
149 --nullPos;
150 else
151 ++i;
152 }
153 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000154 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000155 // block or function pointer call.
156 QualType Ty = V->getType();
157 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000158 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000159 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
160 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000161 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
162 unsigned NumArgsInProto = Proto->getNumArgs();
163 unsigned k;
164 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
165 if (nullPos)
166 --nullPos;
167 else
168 ++i;
169 }
170 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
171 }
172 if (Ty->isBlockPointerType())
173 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000174 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000175 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000176 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000177 return;
178
179 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000180 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000181 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000182 return;
183 }
184 int sentinel = i;
185 while (sentinelPos > 0 && i < NumArgs-1) {
186 --sentinelPos;
187 ++i;
188 }
189 if (sentinelPos > 0) {
190 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000191 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000192 return;
193 }
194 while (i < NumArgs-1) {
195 ++i;
196 ++sentinel;
197 }
198 Expr *sentinelExpr = Args[sentinel];
John McCall8eb662e2010-05-06 23:53:00 +0000199 if (!sentinelExpr) return;
200 if (sentinelExpr->isTypeDependent()) return;
201 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000202
203 // nullptr_t is always treated as null.
204 if (sentinelExpr->getType()->isNullPtrType()) return;
205
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000206 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000207 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
208 Expr::NPC_ValueDependentIsNull))
209 return;
210
211 // Unfortunately, __null has type 'int'.
212 if (isa<GNUNullExpr>(sentinelExpr)) return;
213
214 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
215 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000216}
217
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000218SourceRange Sema::getExprRange(ExprTy *E) const {
219 Expr *Ex = (Expr *)E;
220 return Ex? Ex->getSourceRange() : SourceRange();
221}
222
Chris Lattnere7a2e912008-07-25 21:10:04 +0000223//===----------------------------------------------------------------------===//
224// Standard Promotions and Conversions
225//===----------------------------------------------------------------------===//
226
Chris Lattnere7a2e912008-07-25 21:10:04 +0000227/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
228void Sema::DefaultFunctionArrayConversion(Expr *&E) {
229 QualType Ty = E->getType();
230 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
231
Chris Lattnere7a2e912008-07-25 21:10:04 +0000232 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000233 ImpCastExprToType(E, Context.getPointerType(Ty),
John McCall2de56d12010-08-25 11:45:40 +0000234 CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000235 else if (Ty->isArrayType()) {
236 // In C90 mode, arrays only promote to pointers if the array expression is
237 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
238 // type 'array of type' is converted to an expression that has type 'pointer
239 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
240 // that has type 'array of type' ...". The relevant change is "an lvalue"
241 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000242 //
243 // C++ 4.2p1:
244 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
245 // T" can be converted to an rvalue of type "pointer to T".
246 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000247 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
Anders Carlsson112a0a82009-08-07 23:48:20 +0000248 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
John McCall2de56d12010-08-25 11:45:40 +0000249 CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000250 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000251}
252
John McCall409fa9a2010-12-06 20:48:59 +0000253void Sema::DefaultLvalueConversion(Expr *&E) {
John McCall0ae287a2010-12-01 04:43:34 +0000254 // C++ [conv.lval]p1:
255 // A glvalue of a non-function, non-array type T can be
256 // converted to a prvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000257 if (!E->isGLValue()) return;
John McCallf6a16482010-12-04 03:47:34 +0000258
John McCall409fa9a2010-12-06 20:48:59 +0000259 QualType T = E->getType();
260 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000261
John McCall409fa9a2010-12-06 20:48:59 +0000262 // Create a load out of an ObjCProperty l-value, if necessary.
263 if (E->getObjectKind() == OK_ObjCProperty) {
264 ConvertPropertyForRValue(E);
265 if (!E->isGLValue())
John McCallf6a16482010-12-04 03:47:34 +0000266 return;
Douglas Gregora873dfc2010-02-03 00:27:59 +0000267 }
John McCall409fa9a2010-12-06 20:48:59 +0000268
269 // We don't want to throw lvalue-to-rvalue casts on top of
270 // expressions of certain types in C++.
271 if (getLangOptions().CPlusPlus &&
272 (E->getType() == Context.OverloadTy ||
273 T->isDependentType() ||
274 T->isRecordType()))
275 return;
276
277 // The C standard is actually really unclear on this point, and
278 // DR106 tells us what the result should be but not why. It's
279 // generally best to say that void types just doesn't undergo
280 // lvalue-to-rvalue at all. Note that expressions of unqualified
281 // 'void' type are never l-values, but qualified void can be.
282 if (T->isVoidType())
283 return;
284
285 // C++ [conv.lval]p1:
286 // [...] If T is a non-class type, the type of the prvalue is the
287 // cv-unqualified version of T. Otherwise, the type of the
288 // rvalue is T.
289 //
290 // C99 6.3.2.1p2:
291 // If the lvalue has qualified type, the value has the unqualified
292 // version of the type of the lvalue; otherwise, the value has the
293 // type of the lvalue.
294 if (T.hasQualifiers())
295 T = T.getUnqualifiedType();
296
Ted Kremeneka0125d82011-02-16 01:57:07 +0000297 if (const ArraySubscriptExpr *ae = dyn_cast<ArraySubscriptExpr>(E))
298 CheckArrayAccess(ae);
299
John McCall409fa9a2010-12-06 20:48:59 +0000300 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
301 E, 0, VK_RValue);
302}
303
304void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
305 DefaultFunctionArrayConversion(E);
306 DefaultLvalueConversion(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000307}
308
309
Chris Lattnere7a2e912008-07-25 21:10:04 +0000310/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000311/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000312/// sometimes surpressed. For example, the array->pointer conversion doesn't
313/// apply if the array is an argument to the sizeof or address (&) operators.
314/// In these instances, this routine should *not* be called.
John McCall0ae287a2010-12-01 04:43:34 +0000315Expr *Sema::UsualUnaryConversions(Expr *&E) {
316 // First, convert to an r-value.
317 DefaultFunctionArrayLvalueConversion(E);
318
319 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000320 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000321
322 // Try to perform integral promotions if the object has a theoretically
323 // promotable type.
324 if (Ty->isIntegralOrUnscopedEnumerationType()) {
325 // C99 6.3.1.1p2:
326 //
327 // The following may be used in an expression wherever an int or
328 // unsigned int may be used:
329 // - an object or expression with an integer type whose integer
330 // conversion rank is less than or equal to the rank of int
331 // and unsigned int.
332 // - A bit-field of type _Bool, int, signed int, or unsigned int.
333 //
334 // If an int can represent all values of the original type, the
335 // value is converted to an int; otherwise, it is converted to an
336 // unsigned int. These are called the integer promotions. All
337 // other types are unchanged by the integer promotions.
338
339 QualType PTy = Context.isPromotableBitField(E);
340 if (!PTy.isNull()) {
341 ImpCastExprToType(E, PTy, CK_IntegralCast);
342 return E;
343 }
344 if (Ty->isPromotableIntegerType()) {
345 QualType PT = Context.getPromotedIntegerType(Ty);
346 ImpCastExprToType(E, PT, CK_IntegralCast);
347 return E;
348 }
Eli Friedman04e83572009-08-20 04:21:42 +0000349 }
350
John McCall0ae287a2010-12-01 04:43:34 +0000351 return E;
Chris Lattnere7a2e912008-07-25 21:10:04 +0000352}
353
Chris Lattner05faf172008-07-25 22:25:12 +0000354/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000355/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000356/// double. All other argument types are converted by UsualUnaryConversions().
357void Sema::DefaultArgumentPromotion(Expr *&Expr) {
358 QualType Ty = Expr->getType();
359 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000360
John McCall40c29132010-12-06 18:36:11 +0000361 UsualUnaryConversions(Expr);
362
Chris Lattner05faf172008-07-25 22:25:12 +0000363 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000364 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John McCall40c29132010-12-06 18:36:11 +0000365 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
Chris Lattner05faf172008-07-25 22:25:12 +0000366}
367
Chris Lattner312531a2009-04-12 08:11:20 +0000368/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
369/// will warn if the resulting type is not a POD type, and rejects ObjC
370/// interfaces passed by value. This returns true if the argument type is
371/// completely illegal.
Chris Lattner40378332010-05-16 04:01:30 +0000372bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
373 FunctionDecl *FDecl) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000374 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Chris Lattner40378332010-05-16 04:01:30 +0000376 // __builtin_va_start takes the second argument as a "varargs" argument, but
377 // it doesn't actually do anything with it. It doesn't need to be non-pod
378 // etc.
379 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
380 return false;
381
John McCallc12c5bb2010-05-15 11:32:37 +0000382 if (Expr->getType()->isObjCObjectType() &&
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000383 DiagRuntimeBehavior(Expr->getLocStart(),
384 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
385 << Expr->getType() << CT))
386 return true;
Douglas Gregor75b699a2009-12-12 07:25:49 +0000387
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000388 if (!Expr->getType()->isPODType() &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000389 DiagRuntimeBehavior(Expr->getLocStart(),
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000390 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
391 << Expr->getType() << CT))
392 return true;
Chris Lattner312531a2009-04-12 08:11:20 +0000393
394 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000395}
396
Chris Lattnere7a2e912008-07-25 21:10:04 +0000397/// UsualArithmeticConversions - Performs various conversions that are common to
398/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000399/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000400/// responsible for emitting appropriate error diagnostics.
401/// FIXME: verify the conversion rules for "complex int" are consistent with
402/// GCC.
403QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
404 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000405 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000406 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000407
408 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000409
Mike Stump1eb44332009-09-09 15:08:12 +0000410 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000411 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000412 QualType lhs =
413 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000414 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000415 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000416
417 // If both types are identical, no conversion is needed.
418 if (lhs == rhs)
419 return lhs;
420
421 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
422 // The caller can deal with this (e.g. pointer + int).
423 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
424 return lhs;
425
John McCallcf33b242010-11-13 08:17:45 +0000426 // Apply unary and bitfield promotions to the LHS's type.
427 QualType lhs_unpromoted = lhs;
428 if (lhs->isPromotableIntegerType())
429 lhs = Context.getPromotedIntegerType(lhs);
Eli Friedman04e83572009-08-20 04:21:42 +0000430 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000431 if (!LHSBitfieldPromoteTy.isNull())
432 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000433 if (lhs != lhs_unpromoted && !isCompAssign)
434 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000435
John McCallcf33b242010-11-13 08:17:45 +0000436 // If both types are identical, no conversion is needed.
437 if (lhs == rhs)
438 return lhs;
439
440 // At this point, we have two different arithmetic types.
441
442 // Handle complex types first (C99 6.3.1.8p1).
443 bool LHSComplexFloat = lhs->isComplexType();
444 bool RHSComplexFloat = rhs->isComplexType();
445 if (LHSComplexFloat || RHSComplexFloat) {
446 // if we have an integer operand, the result is the complex type.
447
John McCall2bb5d002010-11-13 09:02:35 +0000448 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
449 if (rhs->isIntegerType()) {
450 QualType fp = cast<ComplexType>(lhs)->getElementType();
451 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
452 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
453 } else {
454 assert(rhs->isComplexIntegerType());
John McCallf3ea8cf2010-11-14 08:17:51 +0000455 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000456 }
John McCallcf33b242010-11-13 08:17:45 +0000457 return lhs;
458 }
459
John McCall2bb5d002010-11-13 09:02:35 +0000460 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
461 if (!isCompAssign) {
462 // int -> float -> _Complex float
463 if (lhs->isIntegerType()) {
464 QualType fp = cast<ComplexType>(rhs)->getElementType();
465 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
466 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
467 } else {
468 assert(lhs->isComplexIntegerType());
John McCallf3ea8cf2010-11-14 08:17:51 +0000469 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000470 }
471 }
John McCallcf33b242010-11-13 08:17:45 +0000472 return rhs;
473 }
474
475 // This handles complex/complex, complex/float, or float/complex.
476 // When both operands are complex, the shorter operand is converted to the
477 // type of the longer, and that is the type of the result. This corresponds
478 // to what is done when combining two real floating-point operands.
479 // The fun begins when size promotion occur across type domains.
480 // From H&S 6.3.4: When one operand is complex and the other is a real
481 // floating-point type, the less precise type is converted, within it's
482 // real or complex domain, to the precision of the other type. For example,
483 // when combining a "long double" with a "double _Complex", the
484 // "double _Complex" is promoted to "long double _Complex".
485 int order = Context.getFloatingTypeOrder(lhs, rhs);
486
487 // If both are complex, just cast to the more precise type.
488 if (LHSComplexFloat && RHSComplexFloat) {
489 if (order > 0) {
490 // _Complex float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000491 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000492 return lhs;
493
494 } else if (order < 0) {
495 // _Complex float -> _Complex double
496 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000497 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000498 return rhs;
499 }
500 return lhs;
501 }
502
503 // If just the LHS is complex, the RHS needs to be converted,
504 // and the LHS might need to be promoted.
505 if (LHSComplexFloat) {
506 if (order > 0) { // LHS is wider
507 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000508 QualType fp = cast<ComplexType>(lhs)->getElementType();
509 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
510 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000511 return lhs;
512 }
513
514 // RHS is at least as wide. Find its corresponding complex type.
515 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
516
517 // double -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000518 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000519
520 // _Complex float -> _Complex double
521 if (!isCompAssign && order < 0)
John McCall2bb5d002010-11-13 09:02:35 +0000522 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000523
524 return result;
525 }
526
527 // Just the RHS is complex, so the LHS needs to be converted
528 // and the RHS might need to be promoted.
529 assert(RHSComplexFloat);
530
531 if (order < 0) { // RHS is wider
532 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000533 if (!isCompAssign) {
Argyrios Kyrtzidise1889332011-01-18 18:49:33 +0000534 QualType fp = cast<ComplexType>(rhs)->getElementType();
535 ImpCastExprToType(lhsExpr, fp, CK_FloatingCast);
John McCall2bb5d002010-11-13 09:02:35 +0000536 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
537 }
John McCallcf33b242010-11-13 08:17:45 +0000538 return rhs;
539 }
540
541 // LHS is at least as wide. Find its corresponding complex type.
542 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
543
544 // double -> _Complex double
545 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000546 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000547
548 // _Complex float -> _Complex double
549 if (order > 0)
John McCall2bb5d002010-11-13 09:02:35 +0000550 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000551
552 return result;
553 }
554
555 // Now handle "real" floating types (i.e. float, double, long double).
556 bool LHSFloat = lhs->isRealFloatingType();
557 bool RHSFloat = rhs->isRealFloatingType();
558 if (LHSFloat || RHSFloat) {
559 // If we have two real floating types, convert the smaller operand
560 // to the bigger result.
561 if (LHSFloat && RHSFloat) {
562 int order = Context.getFloatingTypeOrder(lhs, rhs);
563 if (order > 0) {
564 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
565 return lhs;
566 }
567
568 assert(order < 0 && "illegal float comparison");
569 if (!isCompAssign)
570 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
571 return rhs;
572 }
573
574 // If we have an integer operand, the result is the real floating type.
575 if (LHSFloat) {
576 if (rhs->isIntegerType()) {
577 // Convert rhs to the lhs floating point type.
578 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
579 return lhs;
580 }
581
582 // Convert both sides to the appropriate complex float.
583 assert(rhs->isComplexIntegerType());
584 QualType result = Context.getComplexType(lhs);
585
586 // _Complex int -> _Complex float
John McCallf3ea8cf2010-11-14 08:17:51 +0000587 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000588
589 // float -> _Complex float
590 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000591 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000592
593 return result;
594 }
595
596 assert(RHSFloat);
597 if (lhs->isIntegerType()) {
598 // Convert lhs to the rhs floating point type.
599 if (!isCompAssign)
600 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
601 return rhs;
602 }
603
604 // Convert both sides to the appropriate complex float.
605 assert(lhs->isComplexIntegerType());
606 QualType result = Context.getComplexType(rhs);
607
608 // _Complex int -> _Complex float
609 if (!isCompAssign)
John McCallf3ea8cf2010-11-14 08:17:51 +0000610 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000611
612 // float -> _Complex float
John McCall2bb5d002010-11-13 09:02:35 +0000613 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000614
615 return result;
616 }
617
618 // Handle GCC complex int extension.
619 // FIXME: if the operands are (int, _Complex long), we currently
620 // don't promote the complex. Also, signedness?
621 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
622 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
623 if (lhsComplexInt && rhsComplexInt) {
624 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
625 rhsComplexInt->getElementType());
626 assert(order && "inequal types with equal element ordering");
627 if (order > 0) {
628 // _Complex int -> _Complex long
John McCall2bb5d002010-11-13 09:02:35 +0000629 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000630 return lhs;
631 }
632
633 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000634 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000635 return rhs;
636 } else if (lhsComplexInt) {
637 // int -> _Complex int
John McCall2bb5d002010-11-13 09:02:35 +0000638 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000639 return lhs;
640 } else if (rhsComplexInt) {
641 // int -> _Complex int
642 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000643 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000644 return rhs;
645 }
646
647 // Finally, we have two differing integer types.
648 // The rules for this case are in C99 6.3.1.8
649 int compare = Context.getIntegerTypeOrder(lhs, rhs);
650 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
651 rhsSigned = rhs->hasSignedIntegerRepresentation();
652 if (lhsSigned == rhsSigned) {
653 // Same signedness; use the higher-ranked type
654 if (compare >= 0) {
655 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
656 return lhs;
657 } else if (!isCompAssign)
658 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
659 return rhs;
660 } else if (compare != (lhsSigned ? 1 : -1)) {
661 // The unsigned type has greater than or equal rank to the
662 // signed type, so use the unsigned type
663 if (rhsSigned) {
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 (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
670 // The two types are different widths; if we are here, that
671 // means the signed type is larger than the unsigned type, so
672 // use the signed type.
673 if (lhsSigned) {
674 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
675 return lhs;
676 } else if (!isCompAssign)
677 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
678 return rhs;
679 } else {
680 // The signed type is higher-ranked than the unsigned type,
681 // but isn't actually any bigger (like unsigned int and long
682 // on most 32-bit systems). Use the unsigned type corresponding
683 // to the signed type.
684 QualType result =
685 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
686 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
687 if (!isCompAssign)
688 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
689 return result;
690 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000691}
692
Chris Lattnere7a2e912008-07-25 21:10:04 +0000693//===----------------------------------------------------------------------===//
694// Semantic Analysis for various Expression Types
695//===----------------------------------------------------------------------===//
696
697
Steve Narofff69936d2007-09-16 03:34:24 +0000698/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000699/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
700/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
701/// multiple tokens. However, the common case is that StringToks points to one
702/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000703///
John McCall60d7b3a2010-08-24 06:29:42 +0000704ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +0000705Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000706 assert(NumStringToks && "Must have at least one string!");
707
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000708 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000709 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000710 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000711
712 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
713 for (unsigned i = 0; i != NumStringToks; ++i)
714 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000715
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000716 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000717 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000718 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000719
720 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +0000721 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +0000722 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000723
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000724 // Get an array type for the string, according to C99 6.4.5. This includes
725 // the nul terminator character as well as the string length for pascal
726 // strings.
727 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000728 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000729 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +0000732 return Owned(StringLiteral::Create(Context, Literal.GetString(),
733 Literal.GetStringLength(),
734 Literal.AnyWide, StrTy,
735 &StringTokLocs[0],
736 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000737}
738
John McCall469a1eb2011-02-02 13:00:07 +0000739enum CaptureResult {
740 /// No capture is required.
741 CR_NoCapture,
742
743 /// A capture is required.
744 CR_Capture,
745
John McCall6b5a61b2011-02-07 10:33:21 +0000746 /// A by-ref capture is required.
747 CR_CaptureByRef,
748
John McCall469a1eb2011-02-02 13:00:07 +0000749 /// An error occurred when trying to capture the given variable.
750 CR_Error
751};
752
753/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +0000754///
John McCall469a1eb2011-02-02 13:00:07 +0000755/// \param var - the variable referenced
756/// \param DC - the context which we couldn't capture through
757static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +0000758diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +0000759 VarDecl *var, DeclContext *DC) {
760 switch (S.ExprEvalContexts.back().Context) {
761 case Sema::Unevaluated:
762 // The argument will never be evaluated, so don't complain.
763 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +0000764
John McCall469a1eb2011-02-02 13:00:07 +0000765 case Sema::PotentiallyEvaluated:
766 case Sema::PotentiallyEvaluatedIfUsed:
767 break;
Chris Lattner639e2d32008-10-20 05:16:36 +0000768
John McCall469a1eb2011-02-02 13:00:07 +0000769 case Sema::PotentiallyPotentiallyEvaluated:
770 // FIXME: delay these!
771 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000772 }
Mike Stump1eb44332009-09-09 15:08:12 +0000773
John McCall469a1eb2011-02-02 13:00:07 +0000774 // Don't diagnose about capture if we're not actually in code right
775 // now; in general, there are more appropriate places that will
776 // diagnose this.
777 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
778
779 // This particular madness can happen in ill-formed default
780 // arguments; claim it's okay and let downstream code handle it.
781 if (isa<ParmVarDecl>(var) &&
782 S.CurContext == var->getDeclContext()->getParent())
783 return CR_NoCapture;
784
785 DeclarationName functionName;
786 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
787 functionName = fn->getDeclName();
788 // FIXME: variable from enclosing block that we couldn't capture from!
789
790 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
791 << var->getIdentifier() << functionName;
792 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
793 << var->getIdentifier();
794
795 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +0000796}
797
John McCall6b5a61b2011-02-07 10:33:21 +0000798/// There is a well-formed capture at a particular scope level;
799/// propagate it through all the nested blocks.
800static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
801 const BlockDecl::Capture &capture) {
802 VarDecl *var = capture.getVariable();
803
804 // Update all the inner blocks with the capture information.
805 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
806 i != e; ++i) {
807 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
808 innerBlock->Captures.push_back(
809 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
810 /*nested*/ true, capture.getCopyExpr()));
811 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
812 }
813
814 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
815}
816
817/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +0000818/// given value in the current context requires a variable capture.
819///
820/// This also keeps the captures set in the BlockScopeInfo records
821/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +0000822static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +0000823 ValueDecl *value) {
824 // Only variables ever require capture.
825 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +0000826 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +0000827
828 // Fast path: variables from the current context never require capture.
829 DeclContext *DC = S.CurContext;
830 if (var->getDeclContext() == DC) return CR_NoCapture;
831
832 // Only variables with local storage require capture.
833 // FIXME: What about 'const' variables in C++?
834 if (!var->hasLocalStorage()) return CR_NoCapture;
835
836 // Otherwise, we need to capture.
837
838 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +0000839 do {
840 // Only blocks (and eventually C++0x closures) can capture; other
841 // scopes don't work.
842 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +0000843 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +0000844
845 BlockScopeInfo *blockScope =
846 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
847 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
848
John McCall6b5a61b2011-02-07 10:33:21 +0000849 // Check whether we've already captured it in this block. If so,
850 // we're done.
851 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
852 return propagateCapture(S, functionScopesIndex,
853 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +0000854
855 functionScopesIndex--;
856 DC = cast<BlockDecl>(DC)->getDeclContext();
857 } while (var->getDeclContext() != DC);
858
John McCall6b5a61b2011-02-07 10:33:21 +0000859 // Okay, we descended all the way to the block that defines the variable.
860 // Actually try to capture it.
861 QualType type = var->getType();
862
863 // Prohibit variably-modified types.
864 if (type->isVariablyModifiedType()) {
865 S.Diag(loc, diag::err_ref_vm_type);
866 S.Diag(var->getLocation(), diag::note_declared_at);
867 return CR_Error;
868 }
869
870 // Prohibit arrays, even in __block variables, but not references to
871 // them.
872 if (type->isArrayType()) {
873 S.Diag(loc, diag::err_ref_array_type);
874 S.Diag(var->getLocation(), diag::note_declared_at);
875 return CR_Error;
876 }
877
878 S.MarkDeclarationReferenced(loc, var);
879
880 // The BlocksAttr indicates the variable is bound by-reference.
881 bool byRef = var->hasAttr<BlocksAttr>();
882
883 // Build a copy expression.
884 Expr *copyExpr = 0;
885 if (!byRef && S.getLangOptions().CPlusPlus &&
886 !type->isDependentType() && type->isStructureOrClassType()) {
887 // According to the blocks spec, the capture of a variable from
888 // the stack requires a const copy constructor. This is not true
889 // of the copy/move done to move a __block variable to the heap.
890 type.addConst();
891
892 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
893 ExprResult result =
894 S.PerformCopyInitialization(
895 InitializedEntity::InitializeBlock(var->getLocation(),
896 type, false),
897 loc, S.Owned(declRef));
898
899 // Build a full-expression copy expression if initialization
900 // succeeded and used a non-trivial constructor. Recover from
901 // errors by pretending that the copy isn't necessary.
902 if (!result.isInvalid() &&
903 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
904 result = S.MaybeCreateExprWithCleanups(result);
905 copyExpr = result.take();
906 }
907 }
908
909 // We're currently at the declarer; go back to the closure.
910 functionScopesIndex++;
911 BlockScopeInfo *blockScope =
912 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
913
914 // Build a valid capture in this scope.
915 blockScope->Captures.push_back(
916 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
917 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
918
919 // Propagate that to inner captures if necessary.
920 return propagateCapture(S, functionScopesIndex,
921 blockScope->Captures.back());
922}
923
924static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
925 const DeclarationNameInfo &NameInfo,
926 bool byRef) {
927 assert(isa<VarDecl>(vd) && "capturing non-variable");
928
929 VarDecl *var = cast<VarDecl>(vd);
930 assert(var->hasLocalStorage() && "capturing non-local");
931 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
932
933 QualType exprType = var->getType().getNonReferenceType();
934
935 BlockDeclRefExpr *BDRE;
936 if (!byRef) {
937 // The variable will be bound by copy; make it const within the
938 // closure, but record that this was done in the expression.
939 bool constAdded = !exprType.isConstQualified();
940 exprType.addConst();
941
942 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
943 NameInfo.getLoc(), false,
944 constAdded);
945 } else {
946 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
947 NameInfo.getLoc(), true);
948 }
949
950 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +0000951}
Chris Lattner639e2d32008-10-20 05:16:36 +0000952
John McCall60d7b3a2010-08-24 06:29:42 +0000953ExprResult
John McCallf89e55a2010-11-18 06:31:45 +0000954Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +0000955 SourceLocation Loc,
956 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000957 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +0000958 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +0000959}
960
John McCall76a40212011-02-09 01:13:10 +0000961/// BuildDeclRefExpr - Build an expression that references a
962/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +0000963ExprResult
John McCall76a40212011-02-09 01:13:10 +0000964Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +0000965 const DeclarationNameInfo &NameInfo,
966 const CXXScopeSpec *SS) {
John McCall76a40212011-02-09 01:13:10 +0000967 if (Ty == Context.UndeducedAutoTy) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000968 Diag(NameInfo.getLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +0000969 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000970 << D->getDeclName();
971 return ExprError();
972 }
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Abramo Bagnara25777432010-08-11 22:01:17 +0000974 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +0000975
John McCall7eb0a9e2010-11-24 05:12:34 +0000976 Expr *E = DeclRefExpr::Create(Context,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000977 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
John McCall7eb0a9e2010-11-24 05:12:34 +0000978 SS? SS->getRange() : SourceRange(),
979 D, NameInfo, Ty, VK);
980
981 // Just in case we're building an illegal pointer-to-member.
982 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
983 E->setObjectKind(OK_BitField);
984
985 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +0000986}
987
John McCalldfa1edb2010-11-23 20:48:44 +0000988static ExprResult
989BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
990 const CXXScopeSpec &SS, FieldDecl *Field,
991 DeclAccessPair FoundDecl,
992 const DeclarationNameInfo &MemberNameInfo);
993
John McCall60d7b3a2010-08-24 06:29:42 +0000994ExprResult
John McCall5808ce42011-02-03 08:15:49 +0000995Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
996 SourceLocation loc,
997 IndirectFieldDecl *indirectField,
998 Expr *baseObjectExpr,
999 SourceLocation opLoc) {
1000 // First, build the expression that refers to the base object.
1001
1002 bool baseObjectIsPointer = false;
1003 Qualifiers baseQuals;
1004
1005 // Case 1: the base of the indirect field is not a field.
1006 VarDecl *baseVariable = indirectField->getVarDecl();
1007 if (baseVariable) {
1008 assert(baseVariable->getType()->isRecordType());
1009
1010 // In principle we could have a member access expression that
1011 // accesses an anonymous struct/union that's a static member of
1012 // the base object's class. However, under the current standard,
1013 // static data members cannot be anonymous structs or unions.
1014 // Supporting this is as easy as building a MemberExpr here.
1015 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1016
1017 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1018
1019 ExprResult result =
1020 BuildDeclarationNameExpr(SS, baseNameInfo, baseVariable);
1021 if (result.isInvalid()) return ExprError();
1022
1023 baseObjectExpr = result.take();
1024 baseObjectIsPointer = false;
1025 baseQuals = baseObjectExpr->getType().getQualifiers();
1026
1027 // Case 2: the base of the indirect field is a field and the user
1028 // wrote a member expression.
1029 } else if (baseObjectExpr) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001030 // The caller provided the base object expression. Determine
1031 // whether its a pointer and whether it adds any qualifiers to the
1032 // anonymous struct/union fields we're looking into.
John McCall5808ce42011-02-03 08:15:49 +00001033 QualType objectType = baseObjectExpr->getType();
1034
1035 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1036 baseObjectIsPointer = true;
1037 objectType = ptr->getPointeeType();
1038 } else {
1039 baseObjectIsPointer = false;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001040 }
John McCall5808ce42011-02-03 08:15:49 +00001041 baseQuals = objectType.getQualifiers();
1042
1043 // Case 3: the base of the indirect field is a field and we should
1044 // build an implicit member access.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001045 } else {
1046 // We've found a member of an anonymous struct/union that is
1047 // inside a non-anonymous struct/union, so in a well-formed
1048 // program our base object expression is "this".
John McCall5808ce42011-02-03 08:15:49 +00001049 CXXMethodDecl *method = tryCaptureCXXThis();
1050 if (!method) {
1051 Diag(loc, diag::err_invalid_member_use_in_static_method)
1052 << indirectField->getDeclName();
1053 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001054 }
1055
John McCall5808ce42011-02-03 08:15:49 +00001056 // Our base object expression is "this".
1057 baseObjectExpr =
1058 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1059 /*isImplicit=*/ true);
1060 baseObjectIsPointer = true;
1061 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001062 }
1063
1064 // Build the implicit member references to the field of the
1065 // anonymous struct/union.
John McCall5808ce42011-02-03 08:15:49 +00001066 Expr *result = baseObjectExpr;
1067 IndirectFieldDecl::chain_iterator
1068 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCalldfa1edb2010-11-23 20:48:44 +00001069
John McCall5808ce42011-02-03 08:15:49 +00001070 // Build the first member access in the chain with full information.
1071 if (!baseVariable) {
1072 FieldDecl *field = cast<FieldDecl>(*FI);
John McCalldfa1edb2010-11-23 20:48:44 +00001073
John McCall5808ce42011-02-03 08:15:49 +00001074 // FIXME: use the real found-decl info!
1075 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall0953e762009-09-24 19:53:00 +00001076
John McCall5808ce42011-02-03 08:15:49 +00001077 // Make a nameInfo that properly uses the anonymous name.
1078 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall0953e762009-09-24 19:53:00 +00001079
John McCall5808ce42011-02-03 08:15:49 +00001080 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
1081 SS, field, foundDecl,
1082 memberNameInfo).take();
1083 baseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +00001084
John McCall5808ce42011-02-03 08:15:49 +00001085 // FIXME: check qualified member access
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001086 }
1087
John McCall5808ce42011-02-03 08:15:49 +00001088 // In all cases, we should now skip the first declaration in the chain.
1089 ++FI;
1090
1091 for (; FI != FEnd; FI++) {
1092 FieldDecl *field = cast<FieldDecl>(*FI);
1093
1094 // FIXME: these are somewhat meaningless
1095 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1096 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
1097 CXXScopeSpec memberSS;
1098
1099 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
1100 memberSS, field, foundDecl, memberNameInfo)
1101 .take();
1102 }
1103
1104 return Owned(result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001105}
1106
Abramo Bagnara25777432010-08-11 22:01:17 +00001107/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001108/// possibly a list of template arguments.
1109///
1110/// If this produces template arguments, it is permitted to call
1111/// DecomposeTemplateName.
1112///
1113/// This actually loses a lot of source location information for
1114/// non-standard name kinds; we should consider preserving that in
1115/// some way.
1116static void DecomposeUnqualifiedId(Sema &SemaRef,
1117 const UnqualifiedId &Id,
1118 TemplateArgumentListInfo &Buffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00001119 DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00001120 const TemplateArgumentListInfo *&TemplateArgs) {
1121 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1122 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1123 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1124
1125 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1126 Id.TemplateId->getTemplateArgs(),
1127 Id.TemplateId->NumArgs);
1128 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1129 TemplateArgsPtr.release();
1130
John McCall2b5289b2010-08-23 07:28:44 +00001131 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001132 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1133 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001134 TemplateArgs = &Buffer;
1135 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001136 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001137 TemplateArgs = 0;
1138 }
1139}
1140
John McCallaa81e162009-12-01 22:10:20 +00001141/// Determines if the given class is provably not derived from all of
1142/// the prospective base classes.
1143static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1144 CXXRecordDecl *Record,
1145 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +00001146 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +00001147 return false;
1148
Douglas Gregor952b0172010-02-11 01:04:33 +00001149 RecordDecl *RD = Record->getDefinition();
John McCallb1b42562009-12-01 22:28:41 +00001150 if (!RD) return false;
1151 Record = cast<CXXRecordDecl>(RD);
1152
John McCallaa81e162009-12-01 22:10:20 +00001153 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1154 E = Record->bases_end(); I != E; ++I) {
1155 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1156 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1157 if (!BaseRT) return false;
1158
1159 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +00001160 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1161 return false;
1162 }
1163
1164 return true;
1165}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001166
John McCallaa81e162009-12-01 22:10:20 +00001167enum IMAKind {
1168 /// The reference is definitely not an instance member access.
1169 IMA_Static,
1170
1171 /// The reference may be an implicit instance member access.
1172 IMA_Mixed,
1173
1174 /// The reference may be to an instance member, but it is invalid if
1175 /// so, because the context is not an instance method.
1176 IMA_Mixed_StaticContext,
1177
1178 /// The reference may be to an instance member, but it is invalid if
1179 /// so, because the context is from an unrelated class.
1180 IMA_Mixed_Unrelated,
1181
1182 /// The reference is definitely an implicit instance member access.
1183 IMA_Instance,
1184
1185 /// The reference may be to an unresolved using declaration.
1186 IMA_Unresolved,
1187
1188 /// The reference may be to an unresolved using declaration and the
1189 /// context is not an instance method.
1190 IMA_Unresolved_StaticContext,
1191
John McCallaa81e162009-12-01 22:10:20 +00001192 /// All possible referrents are instance members and the current
1193 /// context is not an instance method.
1194 IMA_Error_StaticContext,
1195
1196 /// All possible referrents are instance members of an unrelated
1197 /// class.
1198 IMA_Error_Unrelated
1199};
1200
1201/// The given lookup names class member(s) and is not being used for
1202/// an address-of-member expression. Classify the type of access
1203/// according to whether it's possible that this reference names an
1204/// instance member. This is best-effort; it is okay to
1205/// conservatively answer "yes", in which case some errors will simply
1206/// not be caught until template-instantiation.
1207static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1208 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +00001209 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +00001210
John McCallea1471e2010-05-20 01:18:31 +00001211 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCallaa81e162009-12-01 22:10:20 +00001212 bool isStaticContext =
John McCallea1471e2010-05-20 01:18:31 +00001213 (!isa<CXXMethodDecl>(DC) ||
1214 cast<CXXMethodDecl>(DC)->isStatic());
John McCallaa81e162009-12-01 22:10:20 +00001215
1216 if (R.isUnresolvableResult())
1217 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1218
1219 // Collect all the declaring classes of instance members we find.
1220 bool hasNonInstance = false;
Sebastian Redlf9780002010-11-26 16:28:07 +00001221 bool hasField = false;
John McCallaa81e162009-12-01 22:10:20 +00001222 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1223 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall161755a2010-04-06 21:38:20 +00001224 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00001225
John McCall161755a2010-04-06 21:38:20 +00001226 if (D->isCXXInstanceMember()) {
Sebastian Redlf9780002010-11-26 16:28:07 +00001227 if (dyn_cast<FieldDecl>(D))
1228 hasField = true;
1229
John McCallaa81e162009-12-01 22:10:20 +00001230 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCallaa81e162009-12-01 22:10:20 +00001231 Classes.insert(R->getCanonicalDecl());
1232 }
1233 else
1234 hasNonInstance = true;
1235 }
1236
1237 // If we didn't find any instance members, it can't be an implicit
1238 // member reference.
1239 if (Classes.empty())
1240 return IMA_Static;
1241
1242 // If the current context is not an instance method, it can't be
1243 // an implicit member reference.
Sebastian Redlf9780002010-11-26 16:28:07 +00001244 if (isStaticContext) {
1245 if (hasNonInstance)
1246 return IMA_Mixed_StaticContext;
1247
1248 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1249 // C++0x [expr.prim.general]p10:
1250 // An id-expression that denotes a non-static data member or non-static
1251 // member function of a class can only be used:
1252 // (...)
1253 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1254 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1255 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1256 if (isUnevaluatedExpression)
1257 return IMA_Mixed_StaticContext;
1258 }
1259
1260 return IMA_Error_StaticContext;
1261 }
John McCallaa81e162009-12-01 22:10:20 +00001262
1263 // If we can prove that the current context is unrelated to all the
1264 // declaring classes, it can't be an implicit member reference (in
1265 // which case it's an error if any of those members are selected).
1266 if (IsProvablyNotDerivedFrom(SemaRef,
John McCallea1471e2010-05-20 01:18:31 +00001267 cast<CXXMethodDecl>(DC)->getParent(),
John McCallaa81e162009-12-01 22:10:20 +00001268 Classes))
1269 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1270
1271 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1272}
1273
1274/// Diagnose a reference to a field with no object available.
1275static void DiagnoseInstanceReference(Sema &SemaRef,
1276 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00001277 NamedDecl *rep,
1278 const DeclarationNameInfo &nameInfo) {
1279 SourceLocation Loc = nameInfo.getLoc();
John McCallaa81e162009-12-01 22:10:20 +00001280 SourceRange Range(Loc);
1281 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1282
John McCall5808ce42011-02-03 08:15:49 +00001283 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCallaa81e162009-12-01 22:10:20 +00001284 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1285 if (MD->isStatic()) {
1286 // "invalid use of member 'x' in static member function"
1287 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCall5808ce42011-02-03 08:15:49 +00001288 << Range << nameInfo.getName();
John McCallaa81e162009-12-01 22:10:20 +00001289 return;
1290 }
1291 }
1292
1293 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCall5808ce42011-02-03 08:15:49 +00001294 << nameInfo.getName() << Range;
John McCallaa81e162009-12-01 22:10:20 +00001295 return;
1296 }
1297
1298 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +00001299}
1300
John McCall578b69b2009-12-16 08:11:27 +00001301/// Diagnose an empty lookup.
1302///
1303/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001304bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1305 CorrectTypoContext CTC) {
John McCall578b69b2009-12-16 08:11:27 +00001306 DeclarationName Name = R.getLookupName();
1307
John McCall578b69b2009-12-16 08:11:27 +00001308 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001309 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001310 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1311 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001312 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001313 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001314 diagnostic_suggest = diag::err_undeclared_use_suggest;
1315 }
John McCall578b69b2009-12-16 08:11:27 +00001316
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001317 // If the original lookup was an unqualified lookup, fake an
1318 // unqualified lookup. This is useful when (for example) the
1319 // original lookup would not have found something because it was a
1320 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001321 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001322 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001323 if (isa<CXXRecordDecl>(DC)) {
1324 LookupQualifiedName(R, DC);
1325
1326 if (!R.empty()) {
1327 // Don't give errors about ambiguities in this lookup.
1328 R.suppressDiagnostics();
1329
1330 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1331 bool isInstance = CurMethod &&
1332 CurMethod->isInstance() &&
1333 DC == CurMethod->getParent();
1334
1335 // Give a code modification hint to insert 'this->'.
1336 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1337 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001338 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001339 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1340 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001341 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001342 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001343 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001344 Diag(R.getNameLoc(), diagnostic) << Name
1345 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1346 QualType DepThisType = DepMethod->getThisType(Context);
1347 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1348 R.getNameLoc(), DepThisType, false);
1349 TemplateArgumentListInfo TList;
1350 if (ULE->hasExplicitTemplateArgs())
1351 ULE->copyTemplateArgumentsInto(TList);
1352 CXXDependentScopeMemberExpr *DepExpr =
1353 CXXDependentScopeMemberExpr::Create(
1354 Context, DepThis, DepThisType, true, SourceLocation(),
1355 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
1356 R.getLookupNameInfo(), &TList);
1357 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001358 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001359 // FIXME: we should be able to handle this case too. It is correct
1360 // to add this-> here. This is a workaround for PR7947.
1361 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001362 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001363 } else {
John McCall578b69b2009-12-16 08:11:27 +00001364 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001365 }
John McCall578b69b2009-12-16 08:11:27 +00001366
1367 // Do we really want to note all of these?
1368 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1369 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1370
1371 // Tell the callee to try to recover.
1372 return false;
1373 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001374
1375 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001376 }
1377 }
1378
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001379 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001380 DeclarationName Corrected;
Daniel Dunbardc32cdf2010-06-02 15:46:52 +00001381 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001382 if (!R.empty()) {
1383 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1384 if (SS.isEmpty())
1385 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1386 << FixItHint::CreateReplacement(R.getNameLoc(),
1387 R.getLookupName().getAsString());
1388 else
1389 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1390 << Name << computeDeclContext(SS, false) << R.getLookupName()
1391 << SS.getRange()
1392 << FixItHint::CreateReplacement(R.getNameLoc(),
1393 R.getLookupName().getAsString());
1394 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1395 Diag(ND->getLocation(), diag::note_previous_decl)
1396 << ND->getDeclName();
1397
1398 // Tell the callee to try to recover.
1399 return false;
1400 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001401
Douglas Gregoraaf87162010-04-14 20:04:41 +00001402 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1403 // FIXME: If we ended up with a typo for a type name or
1404 // Objective-C class name, we're in trouble because the parser
1405 // is in the wrong place to recover. Suggest the typo
1406 // correction, but don't make it a fix-it since we're not going
1407 // to recover well anyway.
1408 if (SS.isEmpty())
1409 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1410 else
1411 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1412 << Name << computeDeclContext(SS, false) << R.getLookupName()
1413 << SS.getRange();
1414
1415 // Don't try to recover; it won't work.
1416 return true;
1417 }
1418 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001419 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001420 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001421 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +00001422 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001423 else
Douglas Gregord203a162010-01-01 00:15:04 +00001424 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001425 << Name << computeDeclContext(SS, false) << Corrected
1426 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001427 return true;
1428 }
Douglas Gregord203a162010-01-01 00:15:04 +00001429 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001430 }
1431
1432 // Emit a special diagnostic for failed member lookups.
1433 // FIXME: computing the declaration context might fail here (?)
1434 if (!SS.isEmpty()) {
1435 Diag(R.getNameLoc(), diag::err_no_member)
1436 << Name << computeDeclContext(SS, false)
1437 << SS.getRange();
1438 return true;
1439 }
1440
John McCall578b69b2009-12-16 08:11:27 +00001441 // Give up, we can't recover.
1442 Diag(R.getNameLoc(), diagnostic) << Name;
1443 return true;
1444}
1445
Douglas Gregorca45da02010-11-02 20:36:02 +00001446ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1447 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001448 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1449 if (!IDecl)
1450 return 0;
1451 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1452 if (!ClassImpDecl)
1453 return 0;
Douglas Gregorca45da02010-11-02 20:36:02 +00001454 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001455 if (!property)
1456 return 0;
1457 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregorca45da02010-11-02 20:36:02 +00001458 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1459 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001460 return 0;
1461 return property;
1462}
1463
Douglas Gregorca45da02010-11-02 20:36:02 +00001464bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1465 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1466 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1467 if (!IDecl)
1468 return false;
1469 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1470 if (!ClassImpDecl)
1471 return false;
1472 if (ObjCPropertyImplDecl *PIDecl
1473 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1474 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1475 PIDecl->getPropertyIvarDecl())
1476 return false;
1477
1478 return true;
1479}
1480
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001481static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001482 LookupResult &Lookup,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001483 IdentifierInfo *II,
1484 SourceLocation NameLoc) {
1485 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001486 bool LookForIvars;
1487 if (Lookup.empty())
1488 LookForIvars = true;
1489 else if (CurMeth->isClassMethod())
1490 LookForIvars = false;
1491 else
1492 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahaniand0fbadd2011-01-26 00:57:01 +00001493 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1494 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001495 if (!LookForIvars)
1496 return 0;
1497
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001498 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1499 if (!IDecl)
1500 return 0;
1501 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001502 if (!ClassImpDecl)
1503 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001504 bool DynamicImplSeen = false;
1505 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1506 if (!property)
1507 return 0;
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001508 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001509 DynamicImplSeen =
1510 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001511 // property implementation has a designated ivar. No need to assume a new
1512 // one.
1513 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1514 return 0;
1515 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001516 if (!DynamicImplSeen) {
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001517 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1518 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001519 NameLoc,
1520 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian75049662010-12-15 23:29:04 +00001521 ObjCIvarDecl::Private,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001522 (Expr *)0, true);
1523 ClassImpDecl->addDecl(Ivar);
1524 IDecl->makeDeclVisibleInContext(Ivar, false);
1525 property->setPropertyIvarDecl(Ivar);
1526 return Ivar;
1527 }
1528 return 0;
1529}
1530
John McCall60d7b3a2010-08-24 06:29:42 +00001531ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001532 CXXScopeSpec &SS,
1533 UnqualifiedId &Id,
1534 bool HasTrailingLParen,
1535 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001536 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1537 "cannot be direct & operand and have a trailing lparen");
1538
1539 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001540 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001541
John McCall129e2df2009-11-30 22:42:35 +00001542 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001543
1544 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001545 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001546 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnara25777432010-08-11 22:01:17 +00001547 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001548
Abramo Bagnara25777432010-08-11 22:01:17 +00001549 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001550 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001551 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001552
John McCallf7a1a742009-11-24 19:00:30 +00001553 // C++ [temp.dep.expr]p3:
1554 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001555 // -- an identifier that was declared with a dependent type,
1556 // (note: handled after lookup)
1557 // -- a template-id that is dependent,
1558 // (note: handled in BuildTemplateIdExpr)
1559 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001560 // -- a nested-name-specifier that contains a class-name that
1561 // names a dependent type.
1562 // Determine whether this is a member of an unknown specialization;
1563 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001564 bool DependentID = false;
1565 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1566 Name.getCXXNameType()->isDependentType()) {
1567 DependentID = true;
1568 } else if (SS.isSet()) {
1569 DeclContext *DC = computeDeclContext(SS, false);
1570 if (DC) {
1571 if (RequireCompleteDeclContext(SS, DC))
1572 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001573 } else {
1574 DependentID = true;
1575 }
1576 }
1577
1578 if (DependentID) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001579 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001580 TemplateArgs);
1581 }
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001582 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001583 // Perform the required lookup.
Abramo Bagnara25777432010-08-11 22:01:17 +00001584 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001585 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001586 // Lookup the template name again to correctly establish the context in
1587 // which it was found. This is really unfortunate as we already did the
1588 // lookup to determine that it was a template name in the first place. If
1589 // this becomes a performance hit, we can work harder to preserve those
1590 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001591 bool MemberOfUnknownSpecialization;
1592 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1593 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001594
1595 if (MemberOfUnknownSpecialization ||
1596 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1597 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1598 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001599 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001600 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001601 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001603 // If the result might be in a dependent base class, this is a dependent
1604 // id-expression.
1605 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1606 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1607 TemplateArgs);
1608
John McCallf7a1a742009-11-24 19:00:30 +00001609 // If this reference is in an Objective-C method, then we need to do
1610 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001611 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001612 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001613 if (E.isInvalid())
1614 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001615
John McCallf7a1a742009-11-24 19:00:30 +00001616 Expr *Ex = E.takeAs<Expr>();
1617 if (Ex) return Owned(Ex);
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001618 // Synthesize ivars lazily
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001619 if (getLangOptions().ObjCDefaultSynthProperties &&
1620 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahaniande267602010-11-17 19:41:23 +00001621 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1622 if (const ObjCPropertyDecl *Property =
1623 canSynthesizeProvisionalIvar(II)) {
1624 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1625 Diag(Property->getLocation(), diag::note_property_declare);
1626 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001627 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1628 isAddressOfOperand);
Fariborz Jahaniande267602010-11-17 19:41:23 +00001629 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001630 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001631 // for further use, this must be set to false if in class method.
1632 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001633 }
Chris Lattner8a934232008-03-31 00:36:02 +00001634 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001635
John McCallf7a1a742009-11-24 19:00:30 +00001636 if (R.isAmbiguous())
1637 return ExprError();
1638
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001639 // Determine whether this name might be a candidate for
1640 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001641 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001642
John McCallf7a1a742009-11-24 19:00:30 +00001643 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001644 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001645 // in C90, extension in C99, forbidden in C++).
1646 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1647 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1648 if (D) R.addDecl(D);
1649 }
1650
1651 // If this name wasn't predeclared and if this is not a function
1652 // call, diagnose the problem.
1653 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001654 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001655 return ExprError();
1656
1657 assert(!R.empty() &&
1658 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001659
1660 // If we found an Objective-C instance variable, let
1661 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001662 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001663 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1664 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001665 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001666 assert(E.isInvalid() || E.get());
1667 return move(E);
1668 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 }
1670 }
Mike Stump1eb44332009-09-09 15:08:12 +00001671
John McCallf7a1a742009-11-24 19:00:30 +00001672 // This is guaranteed from this point on.
1673 assert(!R.empty() || ADL);
1674
1675 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001676 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001677 !(getLangOptions().ObjCDefaultSynthProperties &&
1678 getLangOptions().ObjCNonFragileABI2) &&
Fariborz Jahanianb1d58e32010-07-29 16:53:53 +00001679 Var->isFileVarDecl()) {
Douglas Gregorca45da02010-11-02 20:36:02 +00001680 ObjCPropertyDecl *Property = canSynthesizeProvisionalIvar(II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001681 if (Property) {
1682 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1683 Diag(Property->getLocation(), diag::note_property_declare);
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001684 Diag(Var->getLocation(), diag::note_global_declared_at);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001685 }
1686 }
Douglas Gregor751f9a42009-06-30 15:47:41 +00001687 }
Mike Stump1eb44332009-09-09 15:08:12 +00001688
John McCallaa81e162009-12-01 22:10:20 +00001689 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001690 // C++ [class.mfct.non-static]p3:
1691 // When an id-expression that is not part of a class member access
1692 // syntax and not used to form a pointer to member is used in the
1693 // body of a non-static member function of class X, if name lookup
1694 // resolves the name in the id-expression to a non-static non-type
1695 // member of some class C, the id-expression is transformed into a
1696 // class member access expression using (*this) as the
1697 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001698 //
1699 // But we don't actually need to do this for '&' operands if R
1700 // resolved to a function or overloaded function set, because the
1701 // expression is ill-formed if it actually works out to be a
1702 // non-static member function:
1703 //
1704 // C++ [expr.ref]p4:
1705 // Otherwise, if E1.E2 refers to a non-static member function. . .
1706 // [t]he expression can be used only as the left-hand operand of a
1707 // member function call.
1708 //
1709 // There are other safeguards against such uses, but it's important
1710 // to get this right here so that we don't end up making a
1711 // spuriously dependent expression if we're inside a dependent
1712 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001713 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001714 bool MightBeImplicitMember;
1715 if (!isAddressOfOperand)
1716 MightBeImplicitMember = true;
1717 else if (!SS.isEmpty())
1718 MightBeImplicitMember = false;
1719 else if (R.isOverloadedResult())
1720 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001721 else if (R.isUnresolvableResult())
1722 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001723 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001724 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1725 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001726
1727 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001728 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001729 }
1730
John McCallf7a1a742009-11-24 19:00:30 +00001731 if (TemplateArgs)
1732 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001733
John McCallf7a1a742009-11-24 19:00:30 +00001734 return BuildDeclarationNameExpr(SS, R, ADL);
1735}
1736
John McCall3b4294e2009-12-16 12:17:52 +00001737/// Builds an expression which might be an implicit member expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001738ExprResult
John McCall3b4294e2009-12-16 12:17:52 +00001739Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1740 LookupResult &R,
1741 const TemplateArgumentListInfo *TemplateArgs) {
1742 switch (ClassifyImplicitMemberAccess(*this, R)) {
1743 case IMA_Instance:
1744 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1745
John McCall3b4294e2009-12-16 12:17:52 +00001746 case IMA_Mixed:
1747 case IMA_Mixed_Unrelated:
1748 case IMA_Unresolved:
1749 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1750
1751 case IMA_Static:
1752 case IMA_Mixed_StaticContext:
1753 case IMA_Unresolved_StaticContext:
1754 if (TemplateArgs)
1755 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1756 return BuildDeclarationNameExpr(SS, R, false);
1757
1758 case IMA_Error_StaticContext:
1759 case IMA_Error_Unrelated:
John McCall5808ce42011-02-03 08:15:49 +00001760 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1761 R.getLookupNameInfo());
John McCall3b4294e2009-12-16 12:17:52 +00001762 return ExprError();
1763 }
1764
1765 llvm_unreachable("unexpected instance member access kind");
1766 return ExprError();
1767}
1768
John McCall129e2df2009-11-30 22:42:35 +00001769/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1770/// declaration name, generally during template instantiation.
1771/// There's a large number of things which don't need to be done along
1772/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001773ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001774Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001775 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001776 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001777 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001778 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001779
John McCall77bb1aa2010-05-01 00:40:08 +00001780 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001781 return ExprError();
1782
Abramo Bagnara25777432010-08-11 22:01:17 +00001783 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001784 LookupQualifiedName(R, DC);
1785
1786 if (R.isAmbiguous())
1787 return ExprError();
1788
1789 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001790 Diag(NameInfo.getLoc(), diag::err_no_member)
1791 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001792 return ExprError();
1793 }
1794
1795 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1796}
1797
1798/// LookupInObjCMethod - The parser has read a name in, and Sema has
1799/// detected that we're currently inside an ObjC method. Perform some
1800/// additional lookup.
1801///
1802/// Ideally, most of this would be done by lookup, but there's
1803/// actually quite a lot of extra work involved.
1804///
1805/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001806ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001807Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001808 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001809 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001810 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001811
John McCallf7a1a742009-11-24 19:00:30 +00001812 // There are two cases to handle here. 1) scoped lookup could have failed,
1813 // in which case we should look for an ivar. 2) scoped lookup could have
1814 // found a decl, but that decl is outside the current instance method (i.e.
1815 // a global variable). In these two cases, we do a lookup for an ivar with
1816 // this name, if the lookup sucedes, we replace it our current decl.
1817
1818 // If we're in a class method, we don't normally want to look for
1819 // ivars. But if we don't find anything else, and there's an
1820 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001821 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001822
1823 bool LookForIvars;
1824 if (Lookup.empty())
1825 LookForIvars = true;
1826 else if (IsClassMethod)
1827 LookForIvars = false;
1828 else
1829 LookForIvars = (Lookup.isSingleResult() &&
1830 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001831 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001832 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001833 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001834 ObjCInterfaceDecl *ClassDeclared;
1835 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1836 // Diagnose using an ivar in a class method.
1837 if (IsClassMethod)
1838 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1839 << IV->getDeclName());
1840
1841 // If we're referencing an invalid decl, just return this as a silent
1842 // error node. The error diagnostic was already emitted on the decl.
1843 if (IV->isInvalidDecl())
1844 return ExprError();
1845
1846 // Check if referencing a field with __attribute__((deprecated)).
1847 if (DiagnoseUseOfDecl(IV, Loc))
1848 return ExprError();
1849
1850 // Diagnose the use of an ivar outside of the declaring class.
1851 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1852 ClassDeclared != IFace)
1853 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1854
1855 // FIXME: This should use a new expr for a direct reference, don't
1856 // turn this into Self->ivar, just return a BareIVarExpr or something.
1857 IdentifierInfo &II = Context.Idents.get("self");
1858 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001859 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00001860 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001861 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001862 SelfName, false, false);
1863 if (SelfExpr.isInvalid())
1864 return ExprError();
1865
John McCall409fa9a2010-12-06 20:48:59 +00001866 Expr *SelfE = SelfExpr.take();
1867 DefaultLvalueConversion(SelfE);
1868
John McCallf7a1a742009-11-24 19:00:30 +00001869 MarkDeclarationReferenced(Loc, IV);
1870 return Owned(new (Context)
1871 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall409fa9a2010-12-06 20:48:59 +00001872 SelfE, true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001873 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001874 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001875 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001876 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001877 ObjCInterfaceDecl *ClassDeclared;
1878 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1879 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1880 IFace == ClassDeclared)
1881 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1882 }
1883 }
1884
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001885 if (Lookup.empty() && II && AllowBuiltinCreation) {
1886 // FIXME. Consolidate this with similar code in LookupName.
1887 if (unsigned BuiltinID = II->getBuiltinID()) {
1888 if (!(getLangOptions().CPlusPlus &&
1889 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1890 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1891 S, Lookup.isForRedeclaration(),
1892 Lookup.getNameLoc());
1893 if (D) Lookup.addDecl(D);
1894 }
1895 }
1896 }
John McCallf7a1a742009-11-24 19:00:30 +00001897 // Sentinel value saying that we didn't do anything special.
1898 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001899}
John McCallba135432009-11-21 08:51:07 +00001900
John McCall6bb80172010-03-30 21:47:33 +00001901/// \brief Cast a base object to a member's actual type.
1902///
1903/// Logically this happens in three phases:
1904///
1905/// * First we cast from the base type to the naming class.
1906/// The naming class is the class into which we were looking
1907/// when we found the member; it's the qualifier type if a
1908/// qualifier was provided, and otherwise it's the base type.
1909///
1910/// * Next we cast from the naming class to the declaring class.
1911/// If the member we found was brought into a class's scope by
1912/// a using declaration, this is that class; otherwise it's
1913/// the class declaring the member.
1914///
1915/// * Finally we cast from the declaring class to the "true"
1916/// declaring class of the member. This conversion does not
1917/// obey access control.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001918bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00001919Sema::PerformObjectMemberConversion(Expr *&From,
1920 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001921 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001922 NamedDecl *Member) {
1923 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1924 if (!RD)
1925 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001926
Douglas Gregor5fccd362010-03-03 23:55:11 +00001927 QualType DestRecordType;
1928 QualType DestType;
1929 QualType FromRecordType;
1930 QualType FromType = From->getType();
1931 bool PointerConversions = false;
1932 if (isa<FieldDecl>(Member)) {
1933 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001934
Douglas Gregor5fccd362010-03-03 23:55:11 +00001935 if (FromType->getAs<PointerType>()) {
1936 DestType = Context.getPointerType(DestRecordType);
1937 FromRecordType = FromType->getPointeeType();
1938 PointerConversions = true;
1939 } else {
1940 DestType = DestRecordType;
1941 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001942 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001943 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1944 if (Method->isStatic())
1945 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001946
Douglas Gregor5fccd362010-03-03 23:55:11 +00001947 DestType = Method->getThisType(Context);
1948 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001949
Douglas Gregor5fccd362010-03-03 23:55:11 +00001950 if (FromType->getAs<PointerType>()) {
1951 FromRecordType = FromType->getPointeeType();
1952 PointerConversions = true;
1953 } else {
1954 FromRecordType = FromType;
1955 DestType = DestRecordType;
1956 }
1957 } else {
1958 // No conversion necessary.
1959 return false;
1960 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001961
Douglas Gregor5fccd362010-03-03 23:55:11 +00001962 if (DestType->isDependentType() || FromType->isDependentType())
1963 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001964
Douglas Gregor5fccd362010-03-03 23:55:11 +00001965 // If the unqualified types are the same, no conversion is necessary.
1966 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1967 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001968
John McCall6bb80172010-03-30 21:47:33 +00001969 SourceRange FromRange = From->getSourceRange();
1970 SourceLocation FromLoc = FromRange.getBegin();
1971
John McCall5baba9d2010-08-25 10:28:54 +00001972 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00001973
Douglas Gregor5fccd362010-03-03 23:55:11 +00001974 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001975 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00001976 // class name.
1977 //
1978 // If the member was a qualified name and the qualified referred to a
1979 // specific base subobject type, we'll cast to that intermediate type
1980 // first and then to the object in which the member is declared. That allows
1981 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1982 //
1983 // class Base { public: int x; };
1984 // class Derived1 : public Base { };
1985 // class Derived2 : public Base { };
1986 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1987 //
1988 // void VeryDerived::f() {
1989 // x = 17; // error: ambiguous base subobjects
1990 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1991 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001992 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00001993 QualType QType = QualType(Qualifier->getAsType(), 0);
1994 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1995 assert(QType->isRecordType() && "lookup done with non-record type");
1996
1997 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1998
1999 // In C++98, the qualifier type doesn't actually have to be a base
2000 // type of the object type, in which case we just ignore it.
2001 // Otherwise build the appropriate casts.
2002 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002003 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002004 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002005 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00002006 return true;
2007
Douglas Gregor5fccd362010-03-03 23:55:11 +00002008 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002009 QType = Context.getPointerType(QType);
John McCall5baba9d2010-08-25 10:28:54 +00002010 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2011 VK, &BasePath);
John McCall6bb80172010-03-30 21:47:33 +00002012
2013 FromType = QType;
2014 FromRecordType = QRecordType;
2015
2016 // If the qualifier type was the same as the destination type,
2017 // we're done.
2018 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2019 return false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002020 }
2021 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002022
John McCall6bb80172010-03-30 21:47:33 +00002023 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002024
John McCall6bb80172010-03-30 21:47:33 +00002025 // If we actually found the member through a using declaration, cast
2026 // down to the using declaration's type.
2027 //
2028 // Pointer equality is fine here because only one declaration of a
2029 // class ever has member declarations.
2030 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2031 assert(isa<UsingShadowDecl>(FoundDecl));
2032 QualType URecordType = Context.getTypeDeclType(
2033 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2034
2035 // We only need to do this if the naming-class to declaring-class
2036 // conversion is non-trivial.
2037 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2038 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002039 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002040 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002041 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00002042 return true;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002043
John McCall6bb80172010-03-30 21:47:33 +00002044 QualType UType = URecordType;
2045 if (PointerConversions)
2046 UType = Context.getPointerType(UType);
John McCall2de56d12010-08-25 11:45:40 +00002047 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00002048 VK, &BasePath);
John McCall6bb80172010-03-30 21:47:33 +00002049 FromType = UType;
2050 FromRecordType = URecordType;
2051 }
2052
2053 // We don't do access control for the conversion from the
2054 // declaring class to the true declaring class.
2055 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002056 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002057
John McCallf871d0c2010-08-07 06:22:56 +00002058 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002059 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2060 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002061 IgnoreAccess))
Douglas Gregor5fccd362010-03-03 23:55:11 +00002062 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002063
John McCall2de56d12010-08-25 11:45:40 +00002064 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00002065 VK, &BasePath);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00002066 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002067}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002068
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002069/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00002070static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00002071 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00002072 DeclAccessPair FoundDecl,
Abramo Bagnara25777432010-08-11 22:01:17 +00002073 const DeclarationNameInfo &MemberNameInfo,
2074 QualType Ty,
John McCallf89e55a2010-11-18 06:31:45 +00002075 ExprValueKind VK, ExprObjectKind OK,
John McCallf7a1a742009-11-24 19:00:30 +00002076 const TemplateArgumentListInfo *TemplateArgs = 0) {
2077 NestedNameSpecifier *Qualifier = 0;
2078 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00002079 if (SS.isSet()) {
2080 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
2081 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002082 }
Mike Stump1eb44332009-09-09 15:08:12 +00002083
John McCallf7a1a742009-11-24 19:00:30 +00002084 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00002085 Member, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002086 TemplateArgs, Ty, VK, OK);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002087}
2088
John McCalldfa1edb2010-11-23 20:48:44 +00002089static ExprResult
2090BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2091 const CXXScopeSpec &SS, FieldDecl *Field,
2092 DeclAccessPair FoundDecl,
2093 const DeclarationNameInfo &MemberNameInfo) {
2094 // x.a is an l-value if 'a' has a reference type. Otherwise:
2095 // x.a is an l-value/x-value/pr-value if the base is (and note
2096 // that *x is always an l-value), except that if the base isn't
2097 // an ordinary object then we must have an rvalue.
2098 ExprValueKind VK = VK_LValue;
2099 ExprObjectKind OK = OK_Ordinary;
2100 if (!IsArrow) {
2101 if (BaseExpr->getObjectKind() == OK_Ordinary)
2102 VK = BaseExpr->getValueKind();
2103 else
2104 VK = VK_RValue;
2105 }
2106 if (VK != VK_RValue && Field->isBitField())
2107 OK = OK_BitField;
2108
2109 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2110 QualType MemberType = Field->getType();
2111 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2112 MemberType = Ref->getPointeeType();
2113 VK = VK_LValue;
2114 } else {
2115 QualType BaseType = BaseExpr->getType();
2116 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2117
2118 Qualifiers BaseQuals = BaseType.getQualifiers();
2119
2120 // GC attributes are never picked up by members.
2121 BaseQuals.removeObjCGCAttr();
2122
2123 // CVR attributes from the base are picked up by members,
2124 // except that 'mutable' members don't pick up 'const'.
2125 if (Field->isMutable()) BaseQuals.removeConst();
2126
2127 Qualifiers MemberQuals
2128 = S.Context.getCanonicalType(MemberType).getQualifiers();
2129
2130 // TR 18037 does not allow fields to be declared with address spaces.
2131 assert(!MemberQuals.hasAddressSpace());
2132
2133 Qualifiers Combined = BaseQuals + MemberQuals;
2134 if (Combined != MemberQuals)
2135 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2136 }
2137
2138 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2139 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2140 FoundDecl, Field))
2141 return ExprError();
2142 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2143 Field, FoundDecl, MemberNameInfo,
2144 MemberType, VK, OK));
2145}
2146
John McCallaa81e162009-12-01 22:10:20 +00002147/// Builds an implicit member access expression. The current context
2148/// is known to be an instance method, and the given unqualified lookup
2149/// set is known to contain only instance members, at least one of which
2150/// is from an appropriate type.
John McCall60d7b3a2010-08-24 06:29:42 +00002151ExprResult
John McCallaa81e162009-12-01 22:10:20 +00002152Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2153 LookupResult &R,
2154 const TemplateArgumentListInfo *TemplateArgs,
2155 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00002156 assert(!R.empty() && !R.isAmbiguous());
2157
John McCall5808ce42011-02-03 08:15:49 +00002158 SourceLocation loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00002159
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002160 // We may have found a field within an anonymous union or struct
2161 // (C++ [class.union]).
John McCallf7a1a742009-11-24 19:00:30 +00002162 // FIXME: template-ids inside anonymous structs?
Francois Pichet87c2e122010-11-21 06:08:52 +00002163 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCall5808ce42011-02-03 08:15:49 +00002164 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet87c2e122010-11-21 06:08:52 +00002165
John McCall5808ce42011-02-03 08:15:49 +00002166 // If this is known to be an instance access, go ahead and build an
2167 // implicit 'this' expression now.
John McCallaa81e162009-12-01 22:10:20 +00002168 // 'this' expression now.
John McCall5808ce42011-02-03 08:15:49 +00002169 CXXMethodDecl *method = tryCaptureCXXThis();
2170 assert(method && "didn't correctly pre-flight capture of 'this'");
2171
2172 QualType thisType = method->getThisType(Context);
2173 Expr *baseExpr = 0; // null signifies implicit access
John McCallaa81e162009-12-01 22:10:20 +00002174 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00002175 SourceLocation Loc = R.getNameLoc();
2176 if (SS.getRange().isValid())
2177 Loc = SS.getRange().getBegin();
John McCall5808ce42011-02-03 08:15:49 +00002178 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00002179 }
2180
John McCall5808ce42011-02-03 08:15:49 +00002181 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCallaa81e162009-12-01 22:10:20 +00002182 /*OpLoc*/ SourceLocation(),
2183 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00002184 SS,
2185 /*FirstQualifierInScope*/ 0,
2186 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00002187}
2188
John McCallf7a1a742009-11-24 19:00:30 +00002189bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002190 const LookupResult &R,
2191 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002192 // Only when used directly as the postfix-expression of a call.
2193 if (!HasTrailingLParen)
2194 return false;
2195
2196 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002197 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002198 return false;
2199
2200 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002201 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002202 return false;
2203
2204 // Turn off ADL when we find certain kinds of declarations during
2205 // normal lookup:
2206 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2207 NamedDecl *D = *I;
2208
2209 // C++0x [basic.lookup.argdep]p3:
2210 // -- a declaration of a class member
2211 // Since using decls preserve this property, we check this on the
2212 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002213 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002214 return false;
2215
2216 // C++0x [basic.lookup.argdep]p3:
2217 // -- a block-scope function declaration that is not a
2218 // using-declaration
2219 // NOTE: we also trigger this for function templates (in fact, we
2220 // don't check the decl type at all, since all other decl types
2221 // turn off ADL anyway).
2222 if (isa<UsingShadowDecl>(D))
2223 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2224 else if (D->getDeclContext()->isFunctionOrMethod())
2225 return false;
2226
2227 // C++0x [basic.lookup.argdep]p3:
2228 // -- a declaration that is neither a function or a function
2229 // template
2230 // And also for builtin functions.
2231 if (isa<FunctionDecl>(D)) {
2232 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2233
2234 // But also builtin functions.
2235 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2236 return false;
2237 } else if (!isa<FunctionTemplateDecl>(D))
2238 return false;
2239 }
2240
2241 return true;
2242}
2243
2244
John McCallba135432009-11-21 08:51:07 +00002245/// Diagnoses obvious problems with the use of the given declaration
2246/// as an expression. This is only actually called for lookups that
2247/// were not overloaded, and it doesn't promise that the declaration
2248/// will in fact be used.
2249static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2250 if (isa<TypedefDecl>(D)) {
2251 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2252 return true;
2253 }
2254
2255 if (isa<ObjCInterfaceDecl>(D)) {
2256 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2257 return true;
2258 }
2259
2260 if (isa<NamespaceDecl>(D)) {
2261 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2262 return true;
2263 }
2264
2265 return false;
2266}
2267
John McCall60d7b3a2010-08-24 06:29:42 +00002268ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002269Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002270 LookupResult &R,
2271 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002272 // If this is a single, fully-resolved result and we don't need ADL,
2273 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002274 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002275 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2276 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002277
2278 // We only need to check the declaration if there's exactly one
2279 // result, because in the overloaded case the results can only be
2280 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002281 if (R.isSingleResult() &&
2282 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002283 return ExprError();
2284
John McCallc373d482010-01-27 01:50:18 +00002285 // Otherwise, just build an unresolved lookup expression. Suppress
2286 // any lookup-related diagnostics; we'll hash these out later, when
2287 // we've picked a target.
2288 R.suppressDiagnostics();
2289
John McCallba135432009-11-21 08:51:07 +00002290 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002291 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00002292 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002293 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002294 NeedsADL, R.isOverloadedResult(),
2295 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002296
2297 return Owned(ULE);
2298}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002299
John McCallba135432009-11-21 08:51:07 +00002300/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002301ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002302Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002303 const DeclarationNameInfo &NameInfo,
2304 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002305 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002306 assert(!isa<FunctionTemplateDecl>(D) &&
2307 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002308
Abramo Bagnara25777432010-08-11 22:01:17 +00002309 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002310 if (CheckDeclInExpr(*this, Loc, D))
2311 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002312
Douglas Gregor9af2f522009-12-01 16:58:18 +00002313 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2314 // Specifically diagnose references to class templates that are missing
2315 // a template argument list.
2316 Diag(Loc, diag::err_template_decl_ref)
2317 << Template << SS.getRange();
2318 Diag(Template->getLocation(), diag::note_template_decl_here);
2319 return ExprError();
2320 }
2321
2322 // Make sure that we're referring to a value.
2323 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2324 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002325 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002326 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002327 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002328 return ExprError();
2329 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002330
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002331 // Check whether this declaration can be used. Note that we suppress
2332 // this check when we're going to perform argument-dependent lookup
2333 // on this function name, because this might not be the function
2334 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002335 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002336 return ExprError();
2337
Steve Naroffdd972f22008-09-05 22:11:13 +00002338 // Only create DeclRefExpr's for valid Decl's.
2339 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002340 return ExprError();
2341
John McCall5808ce42011-02-03 08:15:49 +00002342 // Handle members of anonymous structs and unions. If we got here,
2343 // and the reference is to a class member indirect field, then this
2344 // must be the subject of a pointer-to-member expression.
2345 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2346 if (!indirectField->isCXXClassMember())
2347 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2348 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002349
Chris Lattner639e2d32008-10-20 05:16:36 +00002350 // If the identifier reference is inside a block, and it refers to a value
2351 // that is outside the block, create a BlockDeclRefExpr instead of a
2352 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2353 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002354 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002355 // We do not do this for things like enum constants, global variables, etc,
2356 // as they do not get snapshotted.
2357 //
John McCall6b5a61b2011-02-07 10:33:21 +00002358 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002359 case CR_Error:
2360 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002361
John McCall469a1eb2011-02-02 13:00:07 +00002362 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002363 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2364 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2365
2366 case CR_CaptureByRef:
2367 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2368 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002369
2370 case CR_NoCapture: {
2371 // If this reference is not in a block or if the referenced
2372 // variable is within the block, create a normal DeclRefExpr.
2373
2374 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002375 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002376
2377 switch (D->getKind()) {
2378 // Ignore all the non-ValueDecl kinds.
2379#define ABSTRACT_DECL(kind)
2380#define VALUE(type, base)
2381#define DECL(type, base) \
2382 case Decl::type:
2383#include "clang/AST/DeclNodes.inc"
2384 llvm_unreachable("invalid value decl kind");
2385 return ExprError();
2386
2387 // These shouldn't make it here.
2388 case Decl::ObjCAtDefsField:
2389 case Decl::ObjCIvar:
2390 llvm_unreachable("forming non-member reference to ivar?");
2391 return ExprError();
2392
2393 // Enum constants are always r-values and never references.
2394 // Unresolved using declarations are dependent.
2395 case Decl::EnumConstant:
2396 case Decl::UnresolvedUsingValue:
2397 valueKind = VK_RValue;
2398 break;
2399
2400 // Fields and indirect fields that got here must be for
2401 // pointer-to-member expressions; we just call them l-values for
2402 // internal consistency, because this subexpression doesn't really
2403 // exist in the high-level semantics.
2404 case Decl::Field:
2405 case Decl::IndirectField:
2406 assert(getLangOptions().CPlusPlus &&
2407 "building reference to field in C?");
2408
2409 // These can't have reference type in well-formed programs, but
2410 // for internal consistency we do this anyway.
2411 type = type.getNonReferenceType();
2412 valueKind = VK_LValue;
2413 break;
2414
2415 // Non-type template parameters are either l-values or r-values
2416 // depending on the type.
2417 case Decl::NonTypeTemplateParm: {
2418 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2419 type = reftype->getPointeeType();
2420 valueKind = VK_LValue; // even if the parameter is an r-value reference
2421 break;
2422 }
2423
2424 // For non-references, we need to strip qualifiers just in case
2425 // the template parameter was declared as 'const int' or whatever.
2426 valueKind = VK_RValue;
2427 type = type.getUnqualifiedType();
2428 break;
2429 }
2430
2431 case Decl::Var:
2432 // In C, "extern void blah;" is valid and is an r-value.
2433 if (!getLangOptions().CPlusPlus &&
2434 !type.hasQualifiers() &&
2435 type->isVoidType()) {
2436 valueKind = VK_RValue;
2437 break;
2438 }
2439 // fallthrough
2440
2441 case Decl::ImplicitParam:
2442 case Decl::ParmVar:
2443 // These are always l-values.
2444 valueKind = VK_LValue;
2445 type = type.getNonReferenceType();
2446 break;
2447
2448 case Decl::Function: {
2449 // Functions are l-values in C++.
2450 if (getLangOptions().CPlusPlus) {
2451 valueKind = VK_LValue;
2452 break;
2453 }
2454
2455 // C99 DR 316 says that, if a function type comes from a
2456 // function definition (without a prototype), that type is only
2457 // used for checking compatibility. Therefore, when referencing
2458 // the function, we pretend that we don't have the full function
2459 // type.
2460 if (!cast<FunctionDecl>(VD)->hasPrototype())
2461 if (const FunctionProtoType *proto = type->getAs<FunctionProtoType>())
2462 type = Context.getFunctionNoProtoType(proto->getResultType(),
2463 proto->getExtInfo());
2464
2465 // Functions are r-values in C.
2466 valueKind = VK_RValue;
2467 break;
2468 }
2469
2470 case Decl::CXXMethod:
2471 // C++ methods are l-values if static, r-values if non-static.
2472 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2473 valueKind = VK_LValue;
2474 break;
2475 }
2476 // fallthrough
2477
2478 case Decl::CXXConversion:
2479 case Decl::CXXDestructor:
2480 case Decl::CXXConstructor:
2481 valueKind = VK_RValue;
2482 break;
2483 }
2484
2485 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2486 }
2487
John McCall469a1eb2011-02-02 13:00:07 +00002488 }
John McCallf89e55a2010-11-18 06:31:45 +00002489
John McCall6b5a61b2011-02-07 10:33:21 +00002490 llvm_unreachable("unknown capture result");
2491 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002492}
2493
John McCall60d7b3a2010-08-24 06:29:42 +00002494ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlcd965b92009-01-18 18:53:16 +00002495 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002496 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002497
Reid Spencer5f016e22007-07-11 17:01:13 +00002498 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002499 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002500 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2501 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2502 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002503 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002504
Chris Lattnerfa28b302008-01-12 08:14:25 +00002505 // Pre-defined identifiers are of type char[x], where x is the length of the
2506 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002507
Anders Carlsson3a082d82009-09-08 18:24:21 +00002508 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002509 if (!currentDecl && getCurBlock())
2510 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002511 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002512 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002513 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002514 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002515
Anders Carlsson773f3972009-09-11 01:22:35 +00002516 QualType ResTy;
2517 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2518 ResTy = Context.DependentTy;
2519 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002520 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002521
Anders Carlsson773f3972009-09-11 01:22:35 +00002522 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002523 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002524 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2525 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002526 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002527}
2528
John McCall60d7b3a2010-08-24 06:29:42 +00002529ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002530 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002531 bool Invalid = false;
2532 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2533 if (Invalid)
2534 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002535
Benjamin Kramerddeea562010-02-27 13:44:12 +00002536 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2537 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002538 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002539 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002540
Chris Lattnere8337df2009-12-30 21:19:39 +00002541 QualType Ty;
2542 if (!getLangOptions().CPlusPlus)
2543 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2544 else if (Literal.isWide())
2545 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002546 else if (Literal.isMultiChar())
2547 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002548 else
2549 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002550
Sebastian Redle91b3bc2009-01-20 22:23:13 +00002551 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2552 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00002553 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002554}
2555
John McCall60d7b3a2010-08-24 06:29:42 +00002556ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002557 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002558 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2559 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002560 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00002561 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002562 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002563 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002564 }
Ted Kremenek28396602009-01-13 23:19:12 +00002565
Reid Spencer5f016e22007-07-11 17:01:13 +00002566 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002567 // Add padding so that NumericLiteralParser can overread by one character.
2568 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002569 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002570
Reid Spencer5f016e22007-07-11 17:01:13 +00002571 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002572 bool Invalid = false;
2573 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2574 if (Invalid)
2575 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002576
Mike Stump1eb44332009-09-09 15:08:12 +00002577 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002578 Tok.getLocation(), PP);
2579 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002580 return ExprError();
2581
Chris Lattner5d661452007-08-26 03:42:43 +00002582 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002583
Chris Lattner5d661452007-08-26 03:42:43 +00002584 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002585 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002586 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002587 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002588 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002589 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002590 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002591 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002592
2593 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2594
John McCall94c939d2009-12-24 09:08:04 +00002595 using llvm::APFloat;
2596 APFloat Val(Format);
2597
2598 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002599
2600 // Overflow is always an error, but underflow is only an error if
2601 // we underflowed to zero (APFloat reports denormals as underflow).
2602 if ((result & APFloat::opOverflow) ||
2603 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002604 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002605 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002606 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002607 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002608 APFloat::getLargest(Format).toString(buffer);
2609 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002610 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002611 APFloat::getSmallest(Format).toString(buffer);
2612 }
2613
2614 Diag(Tok.getLocation(), diagnostic)
2615 << Ty
2616 << llvm::StringRef(buffer.data(), buffer.size());
2617 }
2618
2619 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002620 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002621
Peter Collingbourne09821362010-12-04 01:50:56 +00002622 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2623 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2624
Chris Lattner5d661452007-08-26 03:42:43 +00002625 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002626 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002627 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002628 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002629
Neil Boothb9449512007-08-29 22:00:19 +00002630 // long long is a C99 feature.
2631 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002632 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002633 Diag(Tok.getLocation(), diag::ext_longlong);
2634
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00002636 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002637
Reid Spencer5f016e22007-07-11 17:01:13 +00002638 if (Literal.GetIntegerValue(ResultVal)) {
2639 // If this value didn't fit into uintmax_t, warn and force to ull.
2640 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002641 Ty = Context.UnsignedLongLongTy;
2642 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002643 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002644 } else {
2645 // If this value fits into a ULL, try to figure out what else it fits into
2646 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002647
Reid Spencer5f016e22007-07-11 17:01:13 +00002648 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2649 // be an unsigned int.
2650 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2651
2652 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002653 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002654 if (!Literal.isLong && !Literal.isLongLong) {
2655 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002656 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002657
Reid Spencer5f016e22007-07-11 17:01:13 +00002658 // Does it fit in a unsigned int?
2659 if (ResultVal.isIntN(IntSize)) {
2660 // Does it fit in a signed int?
2661 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002662 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002663 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002664 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002665 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002666 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002667 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002668
Reid Spencer5f016e22007-07-11 17:01:13 +00002669 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002670 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002671 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002672
Reid Spencer5f016e22007-07-11 17:01:13 +00002673 // Does it fit in a unsigned long?
2674 if (ResultVal.isIntN(LongSize)) {
2675 // Does it fit in a signed long?
2676 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002677 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002678 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002679 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002680 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002681 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002682 }
2683
Reid Spencer5f016e22007-07-11 17:01:13 +00002684 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002685 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002686 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002687
Reid Spencer5f016e22007-07-11 17:01:13 +00002688 // Does it fit in a unsigned long long?
2689 if (ResultVal.isIntN(LongLongSize)) {
2690 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002691 // To be compatible with MSVC, hex integer literals ending with the
2692 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002693 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2694 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002695 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002696 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002697 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002698 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 }
2700 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002701
Reid Spencer5f016e22007-07-11 17:01:13 +00002702 // If we still couldn't decide a type, we probably have something that
2703 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002704 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002705 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002706 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002707 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002708 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002709
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002710 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002711 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002712 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002713 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002714 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002715
Chris Lattner5d661452007-08-26 03:42:43 +00002716 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2717 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002718 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002719 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002720
2721 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002722}
2723
John McCall60d7b3a2010-08-24 06:29:42 +00002724ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00002725 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002726 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002727 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002728}
2729
2730/// The UsualUnaryConversions() function is *not* called by this routine.
2731/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00002732bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00002733 SourceLocation OpLoc,
John McCall2a984ca2010-10-12 00:20:44 +00002734 SourceRange ExprRange,
Sebastian Redl05189992008-11-11 17:56:53 +00002735 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00002736 if (exprType->isDependentType())
2737 return false;
2738
Sebastian Redl5d484e82009-11-23 17:18:46 +00002739 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2740 // the result is the size of the referenced type."
2741 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2742 // result shall be the alignment of the referenced type."
2743 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2744 exprType = Ref->getPointeeType();
2745
Reid Spencer5f016e22007-07-11 17:01:13 +00002746 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00002747 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002748 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002749 if (isSizeof)
2750 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2751 return false;
2752 }
Mike Stump1eb44332009-09-09 15:08:12 +00002753
Chris Lattner1efaa952009-04-24 00:30:45 +00002754 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002755 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002756 Diag(OpLoc, diag::ext_sizeof_void_type)
2757 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00002758 return false;
2759 }
Mike Stump1eb44332009-09-09 15:08:12 +00002760
Chris Lattner1efaa952009-04-24 00:30:45 +00002761 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002762 PDiag(diag::err_sizeof_alignof_incomplete_type)
2763 << int(!isSizeof) << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002764 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002765
Chris Lattner1efaa952009-04-24 00:30:45 +00002766 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCallc12c5bb2010-05-15 11:32:37 +00002767 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002768 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00002769 << exprType << isSizeof << ExprRange;
2770 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00002771 }
Mike Stump1eb44332009-09-09 15:08:12 +00002772
Chris Lattner1efaa952009-04-24 00:30:45 +00002773 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002774}
2775
John McCall2a984ca2010-10-12 00:20:44 +00002776static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2777 SourceRange ExprRange) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002778 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002779
Mike Stump1eb44332009-09-09 15:08:12 +00002780 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002781 if (isa<DeclRefExpr>(E))
2782 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002783
2784 // Cannot know anything else if the expression is dependent.
2785 if (E->isTypeDependent())
2786 return false;
2787
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002788 if (E->getBitField()) {
John McCall2a984ca2010-10-12 00:20:44 +00002789 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002790 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002791 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002792
2793 // Alignment of a field access is always okay, so long as it isn't a
2794 // bit-field.
2795 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002796 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002797 return false;
2798
John McCall2a984ca2010-10-12 00:20:44 +00002799 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
Chris Lattner31e21e02009-01-24 20:17:12 +00002800}
2801
Douglas Gregorba498172009-03-13 21:01:28 +00002802/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002803ExprResult
John McCalla93c9342009-12-07 02:54:59 +00002804Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00002805 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002806 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002807 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002808 return ExprError();
2809
John McCalla93c9342009-12-07 02:54:59 +00002810 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002811
Douglas Gregorba498172009-03-13 21:01:28 +00002812 if (!T->isDependentType() &&
2813 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2814 return ExprError();
2815
2816 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00002817 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00002818 Context.getSizeType(), OpLoc,
2819 R.getEnd()));
2820}
2821
2822/// \brief Build a sizeof or alignof expression given an expression
2823/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002824ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00002825Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002826 bool isSizeOf, SourceRange R) {
2827 // Verify that the operand is valid.
2828 bool isInvalid = false;
2829 if (E->isTypeDependent()) {
2830 // Delay type-checking for type-dependent expressions.
2831 } else if (!isSizeOf) {
John McCall2a984ca2010-10-12 00:20:44 +00002832 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002833 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00002834 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2835 isInvalid = true;
John McCall2cd11fe2010-10-12 02:09:17 +00002836 } else if (E->getType()->isPlaceholderType()) {
2837 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2838 if (PE.isInvalid()) return ExprError();
2839 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
Douglas Gregorba498172009-03-13 21:01:28 +00002840 } else {
2841 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2842 }
2843
2844 if (isInvalid)
2845 return ExprError();
2846
2847 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2848 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2849 Context.getSizeType(), OpLoc,
2850 R.getEnd()));
2851}
2852
Sebastian Redl05189992008-11-11 17:56:53 +00002853/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2854/// the same for @c alignof and @c __alignof
2855/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00002856ExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00002857Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2858 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002859 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002860 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002861
Sebastian Redl05189992008-11-11 17:56:53 +00002862 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002863 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00002864 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
John McCalla93c9342009-12-07 02:54:59 +00002865 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002866 }
Sebastian Redl05189992008-11-11 17:56:53 +00002867
Douglas Gregorba498172009-03-13 21:01:28 +00002868 Expr *ArgEx = (Expr *)TyOrEx;
John McCall60d7b3a2010-08-24 06:29:42 +00002869 ExprResult Result
Douglas Gregorba498172009-03-13 21:01:28 +00002870 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2871
Douglas Gregorba498172009-03-13 21:01:28 +00002872 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002873}
2874
John McCall09431682010-11-18 19:01:18 +00002875static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2876 bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00002877 if (V->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00002878 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002879
John McCallf6a16482010-12-04 03:47:34 +00002880 // _Real and _Imag are only l-values for normal l-values.
2881 if (V->getObjectKind() != OK_Ordinary)
John McCall409fa9a2010-12-06 20:48:59 +00002882 S.DefaultLvalueConversion(V);
John McCallf6a16482010-12-04 03:47:34 +00002883
Chris Lattnercc26ed72007-08-26 05:39:26 +00002884 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00002885 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002886 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002887
Chris Lattnercc26ed72007-08-26 05:39:26 +00002888 // Otherwise they pass through real integer and floating point types here.
2889 if (V->getType()->isArithmeticType())
2890 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002891
John McCall2cd11fe2010-10-12 02:09:17 +00002892 // Test for placeholders.
John McCall09431682010-11-18 19:01:18 +00002893 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall2cd11fe2010-10-12 02:09:17 +00002894 if (PR.isInvalid()) return QualType();
2895 if (PR.take() != V) {
2896 V = PR.take();
John McCall09431682010-11-18 19:01:18 +00002897 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00002898 }
2899
Chris Lattnercc26ed72007-08-26 05:39:26 +00002900 // Reject anything else.
John McCall09431682010-11-18 19:01:18 +00002901 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002902 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002903 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002904}
2905
2906
Reid Spencer5f016e22007-07-11 17:01:13 +00002907
John McCall60d7b3a2010-08-24 06:29:42 +00002908ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00002909Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002910 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00002911 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00002912 switch (Kind) {
2913 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00002914 case tok::plusplus: Opc = UO_PostInc; break;
2915 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002916 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002917
John McCall9ae2f072010-08-23 23:25:46 +00002918 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002919}
2920
John McCall09431682010-11-18 19:01:18 +00002921/// Expressions of certain arbitrary types are forbidden by C from
2922/// having l-value type. These are:
2923/// - 'void', but not qualified void
2924/// - function types
2925///
2926/// The exact rule here is C99 6.3.2.1:
2927/// An lvalue is an expression with an object type or an incomplete
2928/// type other than void.
2929static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2930 return ((T->isVoidType() && !T.hasQualifiers()) ||
2931 T->isFunctionType());
2932}
2933
John McCall60d7b3a2010-08-24 06:29:42 +00002934ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002935Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2936 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00002937 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00002938 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00002939 if (Result.isInvalid()) return ExprError();
2940 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002941
John McCall9ae2f072010-08-23 23:25:46 +00002942 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00002943
Douglas Gregor337c6b92008-11-19 17:17:41 +00002944 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002945 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002946 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00002947 Context.DependentTy,
2948 VK_LValue, OK_Ordinary,
2949 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002950 }
2951
Mike Stump1eb44332009-09-09 15:08:12 +00002952 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002953 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00002954 LHSExp->getType()->isEnumeralType() ||
2955 RHSExp->getType()->isRecordType() ||
2956 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00002957 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00002958 }
2959
John McCall9ae2f072010-08-23 23:25:46 +00002960 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00002961}
2962
2963
John McCall60d7b3a2010-08-24 06:29:42 +00002964ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002965Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2966 Expr *Idx, SourceLocation RLoc) {
2967 Expr *LHSExp = Base;
2968 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00002969
Chris Lattner12d9ff62007-07-16 00:14:47 +00002970 // Perform default conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002971 if (!LHSExp->getType()->getAs<VectorType>())
2972 DefaultFunctionArrayLvalueConversion(LHSExp);
2973 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002974
Chris Lattner12d9ff62007-07-16 00:14:47 +00002975 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00002976 ExprValueKind VK = VK_LValue;
2977 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00002978
Reid Spencer5f016e22007-07-11 17:01:13 +00002979 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002980 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00002981 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00002982 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00002983 Expr *BaseExpr, *IndexExpr;
2984 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00002985 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2986 BaseExpr = LHSExp;
2987 IndexExpr = RHSExp;
2988 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002989 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00002990 BaseExpr = LHSExp;
2991 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002992 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002993 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00002994 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00002995 BaseExpr = RHSExp;
2996 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002997 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002998 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002999 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003000 BaseExpr = LHSExp;
3001 IndexExpr = RHSExp;
3002 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003003 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003004 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003005 // Handle the uncommon case of "123[Ptr]".
3006 BaseExpr = RHSExp;
3007 IndexExpr = LHSExp;
3008 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003009 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003010 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003011 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003012 VK = LHSExp->getValueKind();
3013 if (VK != VK_RValue)
3014 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003015
Chris Lattner12d9ff62007-07-16 00:14:47 +00003016 // FIXME: need to deal with const...
3017 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003018 } else if (LHSTy->isArrayType()) {
3019 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003020 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003021 // wasn't promoted because of the C90 rule that doesn't
3022 // allow promoting non-lvalue arrays. Warn, then
3023 // force the promotion here.
3024 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3025 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003026 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCall2de56d12010-08-25 11:45:40 +00003027 CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003028 LHSTy = LHSExp->getType();
3029
3030 BaseExpr = LHSExp;
3031 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003032 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003033 } else if (RHSTy->isArrayType()) {
3034 // Same as previous, except for 123[f().a] case
3035 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3036 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003037 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCall2de56d12010-08-25 11:45:40 +00003038 CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003039 RHSTy = RHSExp->getType();
3040
3041 BaseExpr = RHSExp;
3042 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003043 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003044 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003045 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3046 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003047 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003048 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003049 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003050 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3051 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003052
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003053 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003054 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3055 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003056 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3057
Douglas Gregore7450f52009-03-24 19:52:54 +00003058 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003059 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3060 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003061 // incomplete types are not object types.
3062 if (ResultType->isFunctionType()) {
3063 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3064 << ResultType << BaseExpr->getSourceRange();
3065 return ExprError();
3066 }
Mike Stump1eb44332009-09-09 15:08:12 +00003067
Abramo Bagnara46358452010-09-13 06:50:07 +00003068 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3069 // GNU extension: subscripting on pointer to void
3070 Diag(LLoc, diag::ext_gnu_void_ptr)
3071 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003072
3073 // C forbids expressions of unqualified void type from being l-values.
3074 // See IsCForbiddenLValueType.
3075 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003076 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003077 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003078 PDiag(diag::err_subscript_incomplete_type)
3079 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003080 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003081
Chris Lattner1efaa952009-04-24 00:30:45 +00003082 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003083 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003084 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3085 << ResultType << BaseExpr->getSourceRange();
3086 return ExprError();
3087 }
Mike Stump1eb44332009-09-09 15:08:12 +00003088
John McCall09431682010-11-18 19:01:18 +00003089 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3090 !IsCForbiddenLValueType(Context, ResultType));
3091
Mike Stumpeed9cac2009-02-19 03:04:26 +00003092 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003093 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003094}
3095
John McCall09431682010-11-18 19:01:18 +00003096/// Check an ext-vector component access expression.
3097///
3098/// VK should be set in advance to the value kind of the base
3099/// expression.
3100static QualType
3101CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3102 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003103 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00003104 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3105 // see FIXME there.
3106 //
3107 // FIXME: This logic can be greatly simplified by splitting it along
3108 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00003109 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00003110
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003111 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00003112 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003113
Mike Stumpeed9cac2009-02-19 03:04:26 +00003114 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00003115 // special names that indicate a subset of exactly half the elements are
3116 // to be selected.
3117 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003118
Nate Begeman353417a2009-01-18 01:47:54 +00003119 // This flag determines whether or not CompName has an 's' char prefix,
3120 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00003121 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00003122
John McCall09431682010-11-18 19:01:18 +00003123 bool HasRepeated = false;
3124 bool HasIndex[16] = {};
3125
3126 int Idx;
3127
Nate Begeman8a997642008-05-09 06:41:27 +00003128 // Check that we've found one of the special components, or that the component
3129 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003130 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00003131 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3132 HalvingSwizzle = true;
John McCall09431682010-11-18 19:01:18 +00003133 } else if (!HexSwizzle &&
3134 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3135 do {
3136 if (HasIndex[Idx]) HasRepeated = true;
3137 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003138 compStr++;
John McCall09431682010-11-18 19:01:18 +00003139 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3140 } else {
3141 if (HexSwizzle) compStr++;
3142 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3143 if (HasIndex[Idx]) HasRepeated = true;
3144 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003145 compStr++;
John McCall09431682010-11-18 19:01:18 +00003146 }
Chris Lattner88dca042007-08-02 22:33:49 +00003147 }
Nate Begeman353417a2009-01-18 01:47:54 +00003148
Mike Stumpeed9cac2009-02-19 03:04:26 +00003149 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003150 // We didn't get to the end of the string. This means the component names
3151 // didn't come from the same set *or* we encountered an illegal name.
John McCall09431682010-11-18 19:01:18 +00003152 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00003153 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003154 return QualType();
3155 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003156
Nate Begeman353417a2009-01-18 01:47:54 +00003157 // Ensure no component accessor exceeds the width of the vector type it
3158 // operates on.
3159 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00003160 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003161
3162 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003163 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00003164
3165 while (*compStr) {
3166 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall09431682010-11-18 19:01:18 +00003167 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begeman353417a2009-01-18 01:47:54 +00003168 << baseType << SourceRange(CompLoc);
3169 return QualType();
3170 }
3171 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003172 }
Nate Begeman8a997642008-05-09 06:41:27 +00003173
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003174 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003175 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003176 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00003177 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00003178 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00003179 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00003180 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00003181 if (HexSwizzle)
3182 CompSize--;
3183
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003184 if (CompSize == 1)
3185 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003186
John McCall09431682010-11-18 19:01:18 +00003187 if (HasRepeated) VK = VK_RValue;
3188
3189 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003190 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00003191 // diagostics look bad. We want extended vector types to appear built-in.
John McCall09431682010-11-18 19:01:18 +00003192 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3193 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3194 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00003195 }
3196 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003197}
3198
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003199static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003200 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003201 const Selector &Sel,
3202 ASTContext &Context) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003203 if (Member)
3204 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3205 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003206 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003207 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00003208
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003209 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3210 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003211 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3212 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003213 return D;
3214 }
3215 return 0;
3216}
3217
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003218static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3219 IdentifierInfo *Member,
3220 const Selector &Sel,
3221 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003222 // Check protocols on qualified interfaces.
3223 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003224 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003225 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003226 if (Member)
3227 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3228 GDecl = PD;
3229 break;
3230 }
3231 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003232 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003233 GDecl = OMD;
3234 break;
3235 }
3236 }
3237 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003238 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003239 E = QIdTy->qual_end(); I != E; ++I) {
3240 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003241 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3242 Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003243 if (GDecl)
3244 return GDecl;
3245 }
3246 }
3247 return GDecl;
3248}
Chris Lattner76a642f2009-02-15 22:43:40 +00003249
John McCall60d7b3a2010-08-24 06:29:42 +00003250ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003251Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCallaa81e162009-12-01 22:10:20 +00003252 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003253 const CXXScopeSpec &SS,
3254 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003255 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003256 const TemplateArgumentListInfo *TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00003257 // Even in dependent contexts, try to diagnose base expressions with
3258 // obviously wrong types, e.g.:
3259 //
3260 // T* t;
3261 // t.f;
3262 //
3263 // In Obj-C++, however, the above expression is valid, since it could be
3264 // accessing the 'f' property if T is an Obj-C interface. The extra check
3265 // allows this, while still reporting an error if T is a struct pointer.
3266 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00003267 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00003268 if (PT && (!getLangOptions().ObjC1 ||
3269 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00003270 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnara25777432010-08-11 22:01:17 +00003271 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00003272 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00003273 return ExprError();
3274 }
3275 }
3276
Abramo Bagnara25777432010-08-11 22:01:17 +00003277 assert(BaseType->isDependentType() ||
3278 NameInfo.getName().isDependentName() ||
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003279 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00003280
3281 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3282 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00003283 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003284 IsArrow, OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003285 SS.getScopeRep(),
John McCall129e2df2009-11-30 22:42:35 +00003286 SS.getRange(),
3287 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003288 NameInfo, TemplateArgs));
John McCall129e2df2009-11-30 22:42:35 +00003289}
3290
3291/// We know that the given qualified member reference points only to
3292/// declarations which do not belong to the static type of the base
3293/// expression. Diagnose the problem.
3294static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3295 Expr *BaseExpr,
3296 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003297 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00003298 NamedDecl *rep,
3299 const DeclarationNameInfo &nameInfo) {
John McCall2f841ba2009-12-02 03:53:29 +00003300 // If this is an implicit member access, use a different set of
3301 // diagnostics.
3302 if (!BaseExpr)
John McCall5808ce42011-02-03 08:15:49 +00003303 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003304
John McCall5808ce42011-02-03 08:15:49 +00003305 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3306 << SS.getRange() << rep << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00003307}
3308
3309// Check whether the declarations we found through a nested-name
3310// specifier in a member expression are actually members of the base
3311// type. The restriction here is:
3312//
3313// C++ [expr.ref]p2:
3314// ... In these cases, the id-expression shall name a
3315// member of the class or of one of its base classes.
3316//
3317// So it's perfectly legitimate for the nested-name specifier to name
3318// an unrelated class, and for us to find an overload set including
3319// decls from classes which are not superclasses, as long as the decl
3320// we actually pick through overload resolution is from a superclass.
3321bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3322 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003323 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003324 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00003325 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3326 if (!BaseRT) {
3327 // We can't check this yet because the base type is still
3328 // dependent.
3329 assert(BaseType->isDependentType());
3330 return false;
3331 }
3332 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00003333
3334 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00003335 // If this is an implicit member reference and we find a
3336 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00003337 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00003338 return false;
John McCall129e2df2009-11-30 22:42:35 +00003339
John McCallaa81e162009-12-01 22:10:20 +00003340 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman02463762010-07-27 20:51:02 +00003341 DeclContext *DC = (*I)->getDeclContext();
3342 while (DC->isTransparentContext())
3343 DC = DC->getParent();
John McCallaa81e162009-12-01 22:10:20 +00003344
Douglas Gregor9d4bb942010-07-28 22:27:52 +00003345 if (!DC->isRecord())
3346 continue;
3347
John McCallaa81e162009-12-01 22:10:20 +00003348 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman02463762010-07-27 20:51:02 +00003349 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCallaa81e162009-12-01 22:10:20 +00003350
3351 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3352 return false;
3353 }
3354
John McCall5808ce42011-02-03 08:15:49 +00003355 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3356 R.getRepresentativeDecl(),
3357 R.getLookupNameInfo());
John McCallaa81e162009-12-01 22:10:20 +00003358 return true;
3359}
3360
3361static bool
3362LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3363 SourceRange BaseRange, const RecordType *RTy,
John McCallad00b772010-06-16 08:42:20 +00003364 SourceLocation OpLoc, CXXScopeSpec &SS,
3365 bool HasTemplateArgs) {
John McCallaa81e162009-12-01 22:10:20 +00003366 RecordDecl *RDecl = RTy->getDecl();
3367 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003368 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00003369 << BaseRange))
3370 return true;
3371
John McCallad00b772010-06-16 08:42:20 +00003372 if (HasTemplateArgs) {
3373 // LookupTemplateName doesn't expect these both to exist simultaneously.
3374 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3375
3376 bool MOUS;
3377 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3378 return false;
3379 }
3380
John McCallaa81e162009-12-01 22:10:20 +00003381 DeclContext *DC = RDecl;
3382 if (SS.isSet()) {
3383 // If the member name was a qualified-id, look into the
3384 // nested-name-specifier.
3385 DC = SemaRef.computeDeclContext(SS, false);
3386
John McCall77bb1aa2010-05-01 00:40:08 +00003387 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCall2f841ba2009-12-02 03:53:29 +00003388 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3389 << SS.getRange() << DC;
3390 return true;
3391 }
3392
John McCallaa81e162009-12-01 22:10:20 +00003393 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003394
John McCallaa81e162009-12-01 22:10:20 +00003395 if (!isa<TypeDecl>(DC)) {
3396 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3397 << DC << SS.getRange();
3398 return true;
John McCall129e2df2009-11-30 22:42:35 +00003399 }
3400 }
3401
John McCallaa81e162009-12-01 22:10:20 +00003402 // The record definition is complete, now look up the member.
3403 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00003404
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003405 if (!R.empty())
3406 return false;
3407
3408 // We didn't find anything with the given name, so try to correct
3409 // for typos.
3410 DeclarationName Name = R.getLookupName();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003411 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00003412 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003413 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3414 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3415 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003416 << FixItHint::CreateReplacement(R.getNameLoc(),
3417 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003418 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3419 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3420 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003421 return false;
3422 } else {
3423 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003424 R.setLookupName(Name);
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003425 }
3426
John McCall129e2df2009-11-30 22:42:35 +00003427 return false;
3428}
3429
John McCall60d7b3a2010-08-24 06:29:42 +00003430ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003431Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003432 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003433 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003434 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003435 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003436 const TemplateArgumentListInfo *TemplateArgs) {
John McCall2f841ba2009-12-02 03:53:29 +00003437 if (BaseType->isDependentType() ||
3438 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall9ae2f072010-08-23 23:25:46 +00003439 return ActOnDependentMemberExpr(Base, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003440 IsArrow, OpLoc,
3441 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003442 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003443
Abramo Bagnara25777432010-08-11 22:01:17 +00003444 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00003445
John McCallaa81e162009-12-01 22:10:20 +00003446 // Implicit member accesses.
3447 if (!Base) {
3448 QualType RecordTy = BaseType;
3449 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3450 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3451 RecordTy->getAs<RecordType>(),
John McCallad00b772010-06-16 08:42:20 +00003452 OpLoc, SS, TemplateArgs != 0))
John McCallaa81e162009-12-01 22:10:20 +00003453 return ExprError();
3454
3455 // Explicit member accesses.
3456 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00003457 ExprResult Result =
John McCallaa81e162009-12-01 22:10:20 +00003458 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCalld226f652010-08-21 09:40:31 +00003459 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCallaa81e162009-12-01 22:10:20 +00003460
3461 if (Result.isInvalid()) {
3462 Owned(Base);
3463 return ExprError();
3464 }
3465
3466 if (Result.get())
3467 return move(Result);
Sebastian Redlf3e63372010-05-07 09:25:11 +00003468
3469 // LookupMemberExpr can modify Base, and thus change BaseType
3470 BaseType = Base->getType();
John McCall129e2df2009-11-30 22:42:35 +00003471 }
3472
John McCall9ae2f072010-08-23 23:25:46 +00003473 return BuildMemberReferenceExpr(Base, BaseType,
John McCallc2233c52010-01-15 08:34:02 +00003474 OpLoc, IsArrow, SS, FirstQualifierInScope,
3475 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003476}
3477
John McCall60d7b3a2010-08-24 06:29:42 +00003478ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003479Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCallaa81e162009-12-01 22:10:20 +00003480 SourceLocation OpLoc, bool IsArrow,
3481 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00003482 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00003483 LookupResult &R,
Douglas Gregor06a9f362010-05-01 20:49:11 +00003484 const TemplateArgumentListInfo *TemplateArgs,
3485 bool SuppressQualifierCheck) {
John McCallaa81e162009-12-01 22:10:20 +00003486 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00003487 if (IsArrow) {
3488 assert(BaseType->isPointerType());
3489 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3490 }
John McCall161755a2010-04-06 21:38:20 +00003491 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00003492
John McCall9ae2f072010-08-23 23:25:46 +00003493 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara25777432010-08-11 22:01:17 +00003494 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3495 DeclarationName MemberName = MemberNameInfo.getName();
3496 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall129e2df2009-11-30 22:42:35 +00003497
3498 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00003499 return ExprError();
3500
John McCall129e2df2009-11-30 22:42:35 +00003501 if (R.empty()) {
3502 // Rederive where we looked up.
3503 DeclContext *DC = (SS.isSet()
3504 ? computeDeclContext(SS, false)
3505 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00003506
John McCall129e2df2009-11-30 22:42:35 +00003507 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00003508 << MemberName << DC
3509 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00003510 return ExprError();
3511 }
3512
John McCallc2233c52010-01-15 08:34:02 +00003513 // Diagnose lookups that find only declarations from a non-base
3514 // type. This is possible for either qualified lookups (which may
3515 // have been qualified with an unrelated type) or implicit member
3516 // expressions (which were found with unqualified lookup and thus
3517 // may have come from an enclosing scope). Note that it's okay for
3518 // lookup to find declarations from a non-base type as long as those
3519 // aren't the ones picked by overload resolution.
3520 if ((SS.isSet() || !BaseExpr ||
3521 (isa<CXXThisExpr>(BaseExpr) &&
3522 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00003523 !SuppressQualifierCheck &&
John McCallc2233c52010-01-15 08:34:02 +00003524 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00003525 return ExprError();
3526
3527 // Construct an unresolved result if we in fact got an unresolved
3528 // result.
3529 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallc373d482010-01-27 01:50:18 +00003530 // Suppress any lookup-related diagnostics; we'll do these when we
3531 // pick a member.
3532 R.suppressDiagnostics();
3533
John McCall129e2df2009-11-30 22:42:35 +00003534 UnresolvedMemberExpr *MemExpr
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003535 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00003536 BaseExpr, BaseExprType,
3537 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003538 Qualifier, SS.getRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00003539 MemberNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00003540 TemplateArgs, R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00003541
3542 return Owned(MemExpr);
3543 }
3544
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003545 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00003546 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00003547 NamedDecl *MemberDecl = R.getFoundDecl();
3548
3549 // FIXME: diagnose the presence of template arguments now.
3550
3551 // If the decl being referenced had an error, return an error for this
3552 // sub-expr without emitting another error, in order to avoid cascading
3553 // error cases.
3554 if (MemberDecl->isInvalidDecl())
3555 return ExprError();
3556
John McCallaa81e162009-12-01 22:10:20 +00003557 // Handle the implicit-member-access case.
3558 if (!BaseExpr) {
3559 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00003560 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnara25777432010-08-11 22:01:17 +00003561 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCallaa81e162009-12-01 22:10:20 +00003562
Douglas Gregor828a1972010-01-07 23:12:05 +00003563 SourceLocation Loc = R.getNameLoc();
3564 if (SS.getRange().isValid())
3565 Loc = SS.getRange().getBegin();
3566 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003567 }
3568
John McCall129e2df2009-11-30 22:42:35 +00003569 bool ShouldCheckUse = true;
3570 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3571 // Don't diagnose the use of a virtual member function unless it's
3572 // explicitly qualified.
3573 if (MD->isVirtual() && !SS.isSet())
3574 ShouldCheckUse = false;
3575 }
3576
3577 // Check the use of this member.
3578 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3579 Owned(BaseExpr);
3580 return ExprError();
3581 }
3582
John McCallf6a16482010-12-04 03:47:34 +00003583 // Perform a property load on the base regardless of whether we
3584 // actually need it for the declaration.
3585 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3586 ConvertPropertyForRValue(BaseExpr);
3587
John McCalldfa1edb2010-11-23 20:48:44 +00003588 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3589 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3590 SS, FD, FoundDecl, MemberNameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003591
Francois Pichet87c2e122010-11-21 06:08:52 +00003592 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3593 // We may have found a field within an anonymous union or struct
3594 // (C++ [class.union]).
John McCall5808ce42011-02-03 08:15:49 +00003595 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCallf6a16482010-12-04 03:47:34 +00003596 BaseExpr, OpLoc);
Francois Pichet87c2e122010-11-21 06:08:52 +00003597
John McCall129e2df2009-11-30 22:42:35 +00003598 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3599 MarkDeclarationReferenced(MemberLoc, Var);
3600 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003601 Var, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003602 Var->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00003603 VK_LValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003604 }
3605
John McCallf89e55a2010-11-18 06:31:45 +00003606 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall129e2df2009-11-30 22:42:35 +00003607 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3608 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003609 MemberFn, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003610 MemberFn->getType(),
3611 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3612 OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003613 }
John McCallf89e55a2010-11-18 06:31:45 +00003614 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall129e2df2009-11-30 22:42:35 +00003615
3616 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3617 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3618 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003619 Enum, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003620 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003621 }
3622
3623 Owned(BaseExpr);
3624
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003625 // We found something that we didn't expect. Complain.
John McCall129e2df2009-11-30 22:42:35 +00003626 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnara25777432010-08-11 22:01:17 +00003627 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003628 << MemberName << BaseType << int(IsArrow);
3629 else
3630 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3631 << MemberName << BaseType << int(IsArrow);
John McCall129e2df2009-11-30 22:42:35 +00003632
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003633 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3634 << MemberName;
Douglas Gregor2b147f02010-04-25 21:15:30 +00003635 R.suppressDiagnostics();
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003636 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00003637}
3638
John McCall028d3972010-12-15 16:46:44 +00003639/// Given that normal member access failed on the given expression,
3640/// and given that the expression's type involves builtin-id or
3641/// builtin-Class, decide whether substituting in the redefinition
3642/// types would be profitable. The redefinition type is whatever
3643/// this translation unit tried to typedef to id/Class; we store
3644/// it to the side and then re-use it in places like this.
3645static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3646 const ObjCObjectPointerType *opty
3647 = base->getType()->getAs<ObjCObjectPointerType>();
3648 if (!opty) return false;
3649
3650 const ObjCObjectType *ty = opty->getObjectType();
3651
3652 QualType redef;
3653 if (ty->isObjCId()) {
3654 redef = S.Context.ObjCIdRedefinitionType;
3655 } else if (ty->isObjCClass()) {
3656 redef = S.Context.ObjCClassRedefinitionType;
3657 } else {
3658 return false;
3659 }
3660
3661 // Do the substitution as long as the redefinition type isn't just a
3662 // possibly-qualified pointer to builtin-id or builtin-Class again.
3663 opty = redef->getAs<ObjCObjectPointerType>();
3664 if (opty && !opty->getObjectType()->getInterface() != 0)
3665 return false;
3666
3667 S.ImpCastExprToType(base, redef, CK_BitCast);
3668 return true;
3669}
3670
John McCall129e2df2009-11-30 22:42:35 +00003671/// Look up the given member of the given non-type-dependent
3672/// expression. This can return in one of two ways:
3673/// * If it returns a sentinel null-but-valid result, the caller will
3674/// assume that lookup was performed and the results written into
3675/// the provided structure. It will take over from there.
3676/// * Otherwise, the returned expression will be produced in place of
3677/// an ordinary member expression.
3678///
3679/// The ObjCImpDecl bit is a gross hack that will need to be properly
3680/// fixed for ObjC++.
John McCall60d7b3a2010-08-24 06:29:42 +00003681ExprResult
John McCall129e2df2009-11-30 22:42:35 +00003682Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00003683 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003684 CXXScopeSpec &SS,
John McCalld226f652010-08-21 09:40:31 +00003685 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003686 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003687
Steve Naroff3cc4af82007-12-16 21:42:28 +00003688 // Perform default conversions.
3689 DefaultFunctionArrayConversion(BaseExpr);
John McCall5e3c67b2010-12-15 04:42:30 +00003690 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003691
Steve Naroffdfa6aae2007-07-26 03:11:44 +00003692 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00003693 assert(!BaseType->isDependentType());
3694
3695 DeclarationName MemberName = R.getLookupName();
3696 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003697
John McCall028d3972010-12-15 16:46:44 +00003698 // For later type-checking purposes, turn arrow accesses into dot
3699 // accesses. The only access type we support that doesn't follow
3700 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3701 // and those never use arrows, so this is unaffected.
3702 if (IsArrow) {
3703 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3704 BaseType = Ptr->getPointeeType();
3705 else if (const ObjCObjectPointerType *Ptr
3706 = BaseType->getAs<ObjCObjectPointerType>())
3707 BaseType = Ptr->getPointeeType();
3708 else if (BaseType->isRecordType()) {
3709 // Recover from arrow accesses to records, e.g.:
3710 // struct MyRecord foo;
3711 // foo->bar
3712 // This is actually well-formed in C++ if MyRecord has an
3713 // overloaded operator->, but that should have been dealt with
3714 // by now.
3715 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3716 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3717 << FixItHint::CreateReplacement(OpLoc, ".");
3718 IsArrow = false;
3719 } else {
3720 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3721 << BaseType << BaseExpr->getSourceRange();
3722 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003723 }
3724 }
3725
John McCall028d3972010-12-15 16:46:44 +00003726 // Handle field access to simple records.
3727 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3728 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3729 RTy, OpLoc, SS, HasTemplateArgs))
3730 return ExprError();
3731
3732 // Returning valid-but-null is how we indicate to the caller that
3733 // the lookup result was filled in.
3734 return Owned((Expr*) 0);
David Chisnall0f436562009-08-17 16:35:33 +00003735 }
John McCall129e2df2009-11-30 22:42:35 +00003736
John McCall028d3972010-12-15 16:46:44 +00003737 // Handle ivar access to Objective-C objects.
3738 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003739 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall028d3972010-12-15 16:46:44 +00003740
3741 // There are three cases for the base type:
3742 // - builtin id (qualified or unqualified)
3743 // - builtin Class (qualified or unqualified)
3744 // - an interface
3745 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3746 if (!IDecl) {
3747 // There's an implicit 'isa' ivar on all objects.
3748 // But we only actually find it this way on objects of type 'id',
3749 // apparently.
3750 if (OTy->isObjCId() && Member->isStr("isa"))
3751 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3752 Context.getObjCClassType()));
3753
3754 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3755 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3756 ObjCImpDecl, HasTemplateArgs);
3757 goto fail;
3758 }
3759
3760 ObjCInterfaceDecl *ClassDeclared;
3761 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3762
3763 if (!IV) {
3764 // Attempt to correct for typos in ivar names.
3765 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3766 LookupMemberName);
3767 if (CorrectTypo(Res, 0, 0, IDecl, false,
3768 IsArrow ? CTC_ObjCIvarLookup
3769 : CTC_ObjCPropertyLookup) &&
3770 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3771 Diag(R.getNameLoc(),
3772 diag::err_typecheck_member_reference_ivar_suggest)
3773 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3774 << FixItHint::CreateReplacement(R.getNameLoc(),
3775 IV->getNameAsString());
3776 Diag(IV->getLocation(), diag::note_previous_decl)
3777 << IV->getDeclName();
3778 } else {
3779 Res.clear();
3780 Res.setLookupName(Member);
3781
3782 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3783 << IDecl->getDeclName() << MemberName
3784 << BaseExpr->getSourceRange();
3785 return ExprError();
3786 }
3787 }
3788
3789 // If the decl being referenced had an error, return an error for this
3790 // sub-expr without emitting another error, in order to avoid cascading
3791 // error cases.
3792 if (IV->isInvalidDecl())
3793 return ExprError();
3794
3795 // Check whether we can reference this field.
3796 if (DiagnoseUseOfDecl(IV, MemberLoc))
3797 return ExprError();
3798 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3799 IV->getAccessControl() != ObjCIvarDecl::Package) {
3800 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3801 if (ObjCMethodDecl *MD = getCurMethodDecl())
3802 ClassOfMethodDecl = MD->getClassInterface();
3803 else if (ObjCImpDecl && getCurFunctionDecl()) {
3804 // Case of a c-function declared inside an objc implementation.
3805 // FIXME: For a c-style function nested inside an objc implementation
3806 // class, there is no implementation context available, so we pass
3807 // down the context as argument to this routine. Ideally, this context
3808 // need be passed down in the AST node and somehow calculated from the
3809 // AST for a function decl.
3810 if (ObjCImplementationDecl *IMPD =
3811 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3812 ClassOfMethodDecl = IMPD->getClassInterface();
3813 else if (ObjCCategoryImplDecl* CatImplClass =
3814 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3815 ClassOfMethodDecl = CatImplClass->getClassInterface();
3816 }
3817
3818 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3819 if (ClassDeclared != IDecl ||
3820 ClassOfMethodDecl != ClassDeclared)
3821 Diag(MemberLoc, diag::error_private_ivar_access)
3822 << IV->getDeclName();
3823 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3824 // @protected
3825 Diag(MemberLoc, diag::error_protected_ivar_access)
3826 << IV->getDeclName();
3827 }
3828
3829 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3830 MemberLoc, BaseExpr,
3831 IsArrow));
3832 }
3833
3834 // Objective-C property access.
3835 const ObjCObjectPointerType *OPT;
3836 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3837 // This actually uses the base as an r-value.
3838 DefaultLvalueConversion(BaseExpr);
3839 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3840
3841 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3842
3843 const ObjCObjectType *OT = OPT->getObjectType();
3844
3845 // id, with and without qualifiers.
3846 if (OT->isObjCId()) {
3847 // Check protocols on qualified interfaces.
3848 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3849 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3850 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3851 // Check the use of this declaration
3852 if (DiagnoseUseOfDecl(PD, MemberLoc))
3853 return ExprError();
3854
3855 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3856 VK_LValue,
3857 OK_ObjCProperty,
3858 MemberLoc,
3859 BaseExpr));
3860 }
3861
3862 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3863 // Check the use of this method.
3864 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3865 return ExprError();
3866 Selector SetterSel =
3867 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3868 PP.getSelectorTable(), Member);
3869 ObjCMethodDecl *SMD = 0;
3870 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3871 SetterSel, Context))
3872 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3873 QualType PType = OMD->getSendResultType();
3874
3875 ExprValueKind VK = VK_LValue;
3876 if (!getLangOptions().CPlusPlus &&
3877 IsCForbiddenLValueType(Context, PType))
3878 VK = VK_RValue;
3879 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3880
3881 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3882 VK, OK,
3883 MemberLoc, BaseExpr));
3884 }
3885 }
3886
3887 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3888 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3889 ObjCImpDecl, HasTemplateArgs);
3890
3891 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3892 << MemberName << BaseType);
3893 }
3894
3895 // 'Class', unqualified only.
3896 if (OT->isObjCClass()) {
3897 // Only works in a method declaration (??!).
3898 ObjCMethodDecl *MD = getCurMethodDecl();
3899 if (!MD) {
3900 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3901 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3902 ObjCImpDecl, HasTemplateArgs);
3903
3904 goto fail;
3905 }
3906
3907 // Also must look for a getter name which uses property syntax.
3908 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003909 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3910 ObjCMethodDecl *Getter;
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003911 if ((Getter = IFace->lookupClassMethod(Sel))) {
3912 // Check the use of this method.
3913 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3914 return ExprError();
John McCall028d3972010-12-15 16:46:44 +00003915 } else
Fariborz Jahanian74b27562010-12-03 23:37:08 +00003916 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003917 // If we found a getter then this may be a valid dot-reference, we
3918 // will look for the matching setter, in case it is needed.
3919 Selector SetterSel =
John McCall028d3972010-12-15 16:46:44 +00003920 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3921 PP.getSelectorTable(), Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003922 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3923 if (!Setter) {
3924 // If this reference is in an @implementation, also check for 'private'
3925 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00003926 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003927 }
3928 // Look through local category implementations associated with the class.
3929 if (!Setter)
3930 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003931
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003932 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3933 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003934
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003935 if (Getter || Setter) {
3936 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003937
John McCall09431682010-11-18 19:01:18 +00003938 ExprValueKind VK = VK_LValue;
3939 if (Getter) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003940 PType = Getter->getSendResultType();
John McCall09431682010-11-18 19:01:18 +00003941 if (!getLangOptions().CPlusPlus &&
3942 IsCForbiddenLValueType(Context, PType))
3943 VK = VK_RValue;
3944 } else {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003945 // Get the expression type from Setter's incoming parameter.
3946 PType = (*(Setter->param_end() -1))->getType();
John McCall09431682010-11-18 19:01:18 +00003947 }
3948 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3949
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003950 // FIXME: we must check that the setter has property type.
John McCall12f78a62010-12-02 01:19:52 +00003951 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3952 PType, VK, OK,
3953 MemberLoc, BaseExpr));
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003954 }
John McCall028d3972010-12-15 16:46:44 +00003955
3956 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3957 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3958 ObjCImpDecl, HasTemplateArgs);
3959
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003960 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall028d3972010-12-15 16:46:44 +00003961 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00003962 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003963
John McCall028d3972010-12-15 16:46:44 +00003964 // Normal property access.
3965 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3966 SourceLocation(), QualType(), false);
Steve Naroff14108da2009-07-10 23:34:53 +00003967 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003968
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003969 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00003970 if (BaseType->isExtVectorType()) {
John McCall5e3c67b2010-12-15 04:42:30 +00003971 // FIXME: this expr should store IsArrow.
Anders Carlsson8f28f992009-08-26 18:25:21 +00003972 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall5e3c67b2010-12-15 04:42:30 +00003973 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall09431682010-11-18 19:01:18 +00003974 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3975 Member, MemberLoc);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003976 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003977 return ExprError();
John McCall09431682010-11-18 19:01:18 +00003978
3979 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3980 *Member, MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003981 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003982
John McCall028d3972010-12-15 16:46:44 +00003983 // Adjust builtin-sel to the appropriate redefinition type if that's
3984 // not just a pointer to builtin-sel again.
3985 if (IsArrow &&
3986 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
3987 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
3988 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
3989 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3990 ObjCImpDecl, HasTemplateArgs);
3991 }
3992
3993 // Failure cases.
3994 fail:
3995
3996 // There's a possible road to recovery for function types.
3997 const FunctionType *Fun = 0;
Matt Beaumont-Gay26ae5dd2011-02-17 02:54:17 +00003998 SourceLocation ParenInsertionLoc =
3999 PP.getLocForEndOfToken(BaseExpr->getLocEnd());
John McCall028d3972010-12-15 16:46:44 +00004000
4001 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4002 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4003 // fall out, handled below.
4004
4005 // Recover from dot accesses to pointers, e.g.:
4006 // type *foo;
4007 // foo.bar
4008 // This is actually well-formed in two cases:
4009 // - 'type' is an Objective C type
4010 // - 'bar' is a pseudo-destructor name which happens to refer to
4011 // the appropriate pointer type
Argyrios Kyrtzidisdf8dc5d2011-01-25 23:16:36 +00004012 } else if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
John McCall028d3972010-12-15 16:46:44 +00004013 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
4014 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4015 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
4016 << FixItHint::CreateReplacement(OpLoc, "->");
4017
4018 // Recurse as an -> access.
4019 IsArrow = true;
4020 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4021 ObjCImpDecl, HasTemplateArgs);
4022 }
4023 } else {
4024 Fun = BaseType->getAs<FunctionType>();
4025 }
4026
4027 // If the user is trying to apply -> or . to a function pointer
4028 // type, it's probably because they forgot parentheses to call that
4029 // function. Suggest the addition of those parentheses, build the
4030 // call, and continue on.
4031 if (Fun || BaseType == Context.OverloadTy) {
4032 bool TryCall;
4033 if (BaseType == Context.OverloadTy) {
Matt Beaumont-Gay26ae5dd2011-02-17 02:54:17 +00004034 // Plunder the overload set for something that would make the member
4035 // expression valid.
4036 const OverloadExpr *Overloads = cast<OverloadExpr>(BaseExpr);
4037 UnresolvedSet<4> CandidateOverloads;
4038 bool HasZeroArgCandidateOverload = false;
4039 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
4040 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
4041 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*it);
4042 QualType ResultTy = OverloadDecl->getResultType();
4043 if ((!IsArrow && ResultTy->isRecordType()) ||
4044 (IsArrow && ResultTy->isPointerType() &&
4045 ResultTy->getPointeeType()->isRecordType())) {
4046 CandidateOverloads.addDecl(*it);
4047 if (OverloadDecl->getNumParams() == 0) {
4048 HasZeroArgCandidateOverload = true;
4049 }
4050 }
4051 }
4052 if (HasZeroArgCandidateOverload && CandidateOverloads.size() == 1) {
4053 // We have one reasonable overload, and there's only one way to call it,
4054 // so emit a fixit and try to recover
4055 Diag(ParenInsertionLoc, diag::err_member_reference_needs_call)
4056 << 1
4057 << BaseExpr->getSourceRange()
4058 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4059 TryCall = true;
4060 } else {
4061 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
4062 << 0
4063 << BaseExpr->getSourceRange();
4064 int CandidateOverloadCount = CandidateOverloads.size();
4065 int I;
4066 for (I = 0; I < CandidateOverloadCount; ++I) {
4067 // FIXME: Magic number for max shown overloads stolen from
4068 // OverloadCandidateSet::NoteCandidates.
4069 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4070 break;
4071 }
4072 Diag(CandidateOverloads[I].getDecl()->getSourceRange().getBegin(),
4073 diag::note_member_ref_possible_intended_overload);
4074 }
4075 if (I != CandidateOverloadCount) {
4076 Diag(BaseExpr->getExprLoc(), diag::note_ovl_too_many_candidates)
4077 << int(CandidateOverloadCount - I);
4078 }
4079 return ExprError();
4080 }
John McCall028d3972010-12-15 16:46:44 +00004081 } else {
4082 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4083 TryCall = (FPT->getNumArgs() == 0);
4084 } else {
4085 TryCall = true;
4086 }
4087
4088 if (TryCall) {
4089 QualType ResultTy = Fun->getResultType();
4090 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4091 (IsArrow && ResultTy->isPointerType() &&
4092 ResultTy->getAs<PointerType>()->getPointeeType()->isRecordType());
4093 }
4094 }
4095
4096
4097 if (TryCall) {
Matt Beaumont-Gay26ae5dd2011-02-17 02:54:17 +00004098 if (Fun) {
4099 Diag(BaseExpr->getExprLoc(),
4100 diag::err_member_reference_needs_call_zero_arg)
4101 << QualType(Fun, 0)
4102 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4103 }
John McCall028d3972010-12-15 16:46:44 +00004104
4105 ExprResult NewBase
Matt Beaumont-Gay26ae5dd2011-02-17 02:54:17 +00004106 = ActOnCallExpr(0, BaseExpr, ParenInsertionLoc,
4107 MultiExprArg(*this, 0, 0), ParenInsertionLoc);
John McCall028d3972010-12-15 16:46:44 +00004108 if (NewBase.isInvalid())
4109 return ExprError();
4110 BaseExpr = NewBase.takeAs<Expr>();
4111
4112
4113 DefaultFunctionArrayConversion(BaseExpr);
4114 BaseType = BaseExpr->getType();
4115
4116 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4117 ObjCImpDecl, HasTemplateArgs);
4118 }
4119 }
4120
Douglas Gregor214f31a2009-03-27 06:00:30 +00004121 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
4122 << BaseType << BaseExpr->getSourceRange();
4123
Douglas Gregor214f31a2009-03-27 06:00:30 +00004124 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00004125}
4126
John McCall129e2df2009-11-30 22:42:35 +00004127/// The main callback when the parser finds something like
4128/// expression . [nested-name-specifier] identifier
4129/// expression -> [nested-name-specifier] identifier
4130/// where 'identifier' encompasses a fairly broad spectrum of
4131/// possibilities, including destructor and operator references.
4132///
4133/// \param OpKind either tok::arrow or tok::period
4134/// \param HasTrailingLParen whether the next token is '(', which
4135/// is used to diagnose mis-uses of special members that can
4136/// only be called
4137/// \param ObjCImpDecl the current ObjC @implementation decl;
4138/// this is an ugly hack around the fact that ObjC @implementations
4139/// aren't properly put in the context chain
John McCall60d7b3a2010-08-24 06:29:42 +00004140ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall5e3c67b2010-12-15 04:42:30 +00004141 SourceLocation OpLoc,
4142 tok::TokenKind OpKind,
4143 CXXScopeSpec &SS,
4144 UnqualifiedId &Id,
4145 Decl *ObjCImpDecl,
4146 bool HasTrailingLParen) {
John McCall129e2df2009-11-30 22:42:35 +00004147 if (SS.isSet() && SS.isInvalid())
4148 return ExprError();
4149
Francois Pichetdbee3412011-01-18 05:04:39 +00004150 // Warn about the explicit constructor calls Microsoft extension.
4151 if (getLangOptions().Microsoft &&
4152 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4153 Diag(Id.getSourceRange().getBegin(),
4154 diag::ext_ms_explicit_constructor_call);
4155
John McCall129e2df2009-11-30 22:42:35 +00004156 TemplateArgumentListInfo TemplateArgsBuffer;
4157
4158 // Decompose the name into its component parts.
Abramo Bagnara25777432010-08-11 22:01:17 +00004159 DeclarationNameInfo NameInfo;
John McCall129e2df2009-11-30 22:42:35 +00004160 const TemplateArgumentListInfo *TemplateArgs;
4161 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00004162 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004163
Abramo Bagnara25777432010-08-11 22:01:17 +00004164 DeclarationName Name = NameInfo.getName();
John McCall129e2df2009-11-30 22:42:35 +00004165 bool IsArrow = (OpKind == tok::arrow);
4166
4167 NamedDecl *FirstQualifierInScope
4168 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4169 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4170
4171 // This is a postfix expression, so get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004172 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004173 if (Result.isInvalid()) return ExprError();
4174 Base = Result.take();
John McCall129e2df2009-11-30 22:42:35 +00004175
Douglas Gregor01e56ae2010-04-12 20:54:26 +00004176 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4177 isDependentScopeSpecifier(SS)) {
John McCall9ae2f072010-08-23 23:25:46 +00004178 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00004179 IsArrow, OpLoc,
4180 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00004181 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004182 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00004183 LookupResult R(*this, NameInfo, LookupMemberName);
John McCallad00b772010-06-16 08:42:20 +00004184 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
4185 SS, ObjCImpDecl, TemplateArgs != 0);
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004186
John McCallad00b772010-06-16 08:42:20 +00004187 if (Result.isInvalid()) {
4188 Owned(Base);
4189 return ExprError();
4190 }
John McCall129e2df2009-11-30 22:42:35 +00004191
John McCallad00b772010-06-16 08:42:20 +00004192 if (Result.get()) {
4193 // The only way a reference to a destructor can be used is to
4194 // immediately call it, which falls into this case. If the
4195 // next token is not a '(', produce a diagnostic and build the
4196 // call now.
4197 if (!HasTrailingLParen &&
4198 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCall9ae2f072010-08-23 23:25:46 +00004199 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall129e2df2009-11-30 22:42:35 +00004200
John McCallad00b772010-06-16 08:42:20 +00004201 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00004202 }
4203
John McCall9ae2f072010-08-23 23:25:46 +00004204 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00004205 OpLoc, IsArrow, SS, FirstQualifierInScope,
4206 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004207 }
4208
4209 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00004210}
4211
John McCall60d7b3a2010-08-24 06:29:42 +00004212ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00004213 FunctionDecl *FD,
4214 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00004215 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004216 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00004217 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00004218 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004219 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00004220 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004221 return ExprError();
4222 }
4223
4224 if (Param->hasUninstantiatedDefaultArg()) {
4225 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00004226
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004227 // Instantiate the expression.
4228 MultiLevelTemplateArgumentList ArgList
4229 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00004230
Nico Weber08e41a62010-11-29 18:19:25 +00004231 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004232 = ArgList.getInnermost();
4233 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4234 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004235
Nico Weber08e41a62010-11-29 18:19:25 +00004236 ExprResult Result;
4237 {
4238 // C++ [dcl.fct.default]p5:
4239 // The names in the [default argument] expression are bound, and
4240 // the semantic constraints are checked, at the point where the
4241 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00004242 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00004243 Result = SubstExpr(UninstExpr, ArgList);
4244 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004245 if (Result.isInvalid())
4246 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004247
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004248 // Check the expression as an initializer for the parameter.
4249 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004250 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004251 InitializationKind Kind
4252 = InitializationKind::CreateCopy(Param->getLocation(),
4253 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4254 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00004255
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004256 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4257 Result = InitSeq.Perform(*this, Entity, Kind,
4258 MultiExprArg(*this, &ResultE, 1));
4259 if (Result.isInvalid())
4260 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004261
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004262 // Build the default argument expression.
4263 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4264 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004265 }
4266
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004267 // If the default expression creates temporaries, we need to
4268 // push them to the current stack of expression temporaries so they'll
4269 // be properly destroyed.
4270 // FIXME: We should really be rebuilding the default argument with new
4271 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00004272 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4273 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4274 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4275 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4276 ExprTemporaries.push_back(Temporary);
4277 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004278
4279 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00004280 // Just mark all of the declarations in this potentially-evaluated expression
4281 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004282 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00004283 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004284}
4285
Douglas Gregor88a35142008-12-22 05:46:06 +00004286/// ConvertArgumentsForCall - Converts the arguments specified in
4287/// Args/NumArgs to the parameter types of the function FDecl with
4288/// function prototype Proto. Call is the call expression itself, and
4289/// Fn is the function expression. For a C++ member function, this
4290/// routine does not attempt to convert the object argument. Returns
4291/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004292bool
4293Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00004294 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00004295 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00004296 Expr **Args, unsigned NumArgs,
4297 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004298 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00004299 // assignment, to the types of the corresponding parameter, ...
4300 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004301 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004302
Douglas Gregor88a35142008-12-22 05:46:06 +00004303 // If too few arguments are available (and we don't have default
4304 // arguments for the remaining parameters), don't make the call.
4305 if (NumArgs < NumArgsInProto) {
4306 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4307 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004308 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00004309 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004310 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00004311 }
4312
4313 // If too many are passed and not variadic, error on the extras and drop
4314 // them.
4315 if (NumArgs > NumArgsInProto) {
4316 if (!Proto->isVariadic()) {
4317 Diag(Args[NumArgsInProto]->getLocStart(),
4318 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004319 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00004320 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00004321 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4322 Args[NumArgs-1]->getLocEnd());
4323 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004324 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004325 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004326 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004327 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004328 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004329 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004330 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4331 if (Fn->getType()->isBlockPointerType())
4332 CallType = VariadicBlock; // Block
4333 else if (isa<MemberExpr>(Fn))
4334 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004335 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004336 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004337 if (Invalid)
4338 return true;
4339 unsigned TotalNumArgs = AllArgs.size();
4340 for (unsigned i = 0; i < TotalNumArgs; ++i)
4341 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004342
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004343 return false;
4344}
Mike Stumpeed9cac2009-02-19 03:04:26 +00004345
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004346bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4347 FunctionDecl *FDecl,
4348 const FunctionProtoType *Proto,
4349 unsigned FirstProtoArg,
4350 Expr **Args, unsigned NumArgs,
4351 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004352 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004353 unsigned NumArgsInProto = Proto->getNumArgs();
4354 unsigned NumArgsToCheck = NumArgs;
4355 bool Invalid = false;
4356 if (NumArgs != NumArgsInProto)
4357 // Use default arguments for missing arguments
4358 NumArgsToCheck = NumArgsInProto;
4359 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00004360 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004361 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004362 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004363
Douglas Gregor88a35142008-12-22 05:46:06 +00004364 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004365 if (ArgIx < NumArgs) {
4366 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004367
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004368 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4369 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004370 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004371 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004372 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004373
Douglas Gregora188ff22009-12-22 16:09:06 +00004374 // Pass the argument
4375 ParmVarDecl *Param = 0;
4376 if (FDecl && i < FDecl->getNumParams())
4377 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00004378
Douglas Gregora188ff22009-12-22 16:09:06 +00004379 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004380 Param? InitializedEntity::InitializeParameter(Context, Param)
4381 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCall60d7b3a2010-08-24 06:29:42 +00004382 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00004383 SourceLocation(),
4384 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00004385 if (ArgE.isInvalid())
4386 return true;
4387
4388 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004389 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00004390 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004391
John McCall60d7b3a2010-08-24 06:29:42 +00004392 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004393 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004394 if (ArgExpr.isInvalid())
4395 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004396
Anders Carlsson56c5e332009-08-25 03:49:14 +00004397 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004398 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004399 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004400 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004401
Douglas Gregor88a35142008-12-22 05:46:06 +00004402 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004403 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004404 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner40378332010-05-16 04:01:30 +00004405 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004406 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00004407 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004408 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004409 }
4410 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004411 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00004412}
4413
Steve Narofff69936d2007-09-16 03:34:24 +00004414/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00004415/// This provides the location of the left/right parens and a list of comma
4416/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00004417ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004418Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004419 MultiExprArg args, SourceLocation RParenLoc,
4420 Expr *ExecConfig) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00004421 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00004422
4423 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004424 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00004425 if (Result.isInvalid()) return ExprError();
4426 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00004427
John McCall9ae2f072010-08-23 23:25:46 +00004428 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004429
Douglas Gregor88a35142008-12-22 05:46:06 +00004430 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00004431 // If this is a pseudo-destructor expression, build the call immediately.
4432 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4433 if (NumArgs > 0) {
4434 // Pseudo-destructor calls should not have any arguments.
4435 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00004436 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00004437 SourceRange(Args[0]->getLocStart(),
4438 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00004439
Douglas Gregora71d8192009-09-04 17:36:40 +00004440 NumArgs = 0;
4441 }
Mike Stump1eb44332009-09-09 15:08:12 +00004442
Douglas Gregora71d8192009-09-04 17:36:40 +00004443 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00004444 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00004445 }
Mike Stump1eb44332009-09-09 15:08:12 +00004446
Douglas Gregor17330012009-02-04 15:01:18 +00004447 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004448 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00004449 // FIXME: Will need to cache the results of name lookup (including ADL) in
4450 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00004451 bool Dependent = false;
4452 if (Fn->isTypeDependent())
4453 Dependent = true;
4454 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4455 Dependent = true;
4456
Peter Collingbournee08ce652011-02-09 21:07:24 +00004457 if (Dependent) {
4458 if (ExecConfig) {
4459 return Owned(new (Context) CUDAKernelCallExpr(
4460 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4461 Context.DependentTy, VK_RValue, RParenLoc));
4462 } else {
4463 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4464 Context.DependentTy, VK_RValue,
4465 RParenLoc));
4466 }
4467 }
Douglas Gregor17330012009-02-04 15:01:18 +00004468
4469 // Determine whether this is a call to an object (C++ [over.call.object]).
4470 if (Fn->getType()->isRecordType())
4471 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004472 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00004473
John McCall129e2df2009-11-30 22:42:35 +00004474 Expr *NakedFn = Fn->IgnoreParens();
4475
4476 // Determine whether this is a call to an unresolved member function.
4477 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4478 // If lookup was unresolved but not dependent (i.e. didn't find
4479 // an unresolved using declaration), it has to be an overloaded
4480 // function set, which means it must contain either multiple
4481 // declarations (all methods or method templates) or a single
4482 // method template.
4483 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor2b147f02010-04-25 21:15:30 +00004484 isa<FunctionTemplateDecl>(
4485 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00004486 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00004487
John McCallaa81e162009-12-01 22:10:20 +00004488 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004489 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00004490 }
4491
Douglas Gregorfa047642009-02-04 00:32:51 +00004492 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00004493 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00004494 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00004495 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00004496 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004497 RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00004498 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004499
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004500 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00004501 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCall2de56d12010-08-25 11:45:40 +00004502 if (BO->getOpcode() == BO_PtrMemD ||
4503 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00004504 if (const FunctionProtoType *FPT
4505 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004506 QualType ResultTy = FPT->getCallResultType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00004507 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004508
Douglas Gregorfdc13a02011-02-04 12:57:49 +00004509 // Check that the object type isn't more qualified than the
4510 // member function we're calling.
4511 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4512 Qualifiers ObjectQuals
4513 = BO->getOpcode() == BO_PtrMemD
4514 ? BO->getLHS()->getType().getQualifiers()
4515 : BO->getLHS()->getType()->getAs<PointerType>()
4516 ->getPointeeType().getQualifiers();
4517
4518 Qualifiers Difference = ObjectQuals - FuncQuals;
4519 Difference.removeObjCGCAttr();
4520 Difference.removeAddressSpace();
4521 if (Difference) {
4522 std::string QualsString = Difference.getAsString();
4523 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4524 << BO->getType().getUnqualifiedType()
4525 << QualsString
4526 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4527 }
4528
John McCall9ae2f072010-08-23 23:25:46 +00004529 CXXMemberCallExpr *TheCall
Abramo Bagnara6c572f12010-12-03 21:39:42 +00004530 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCallf89e55a2010-11-18 06:31:45 +00004531 NumArgs, ResultTy, VK,
John McCall9ae2f072010-08-23 23:25:46 +00004532 RParenLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004533
4534 if (CheckCallReturnType(FPT->getResultType(),
4535 BO->getRHS()->getSourceRange().getBegin(),
John McCall9ae2f072010-08-23 23:25:46 +00004536 TheCall, 0))
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004537 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00004538
John McCall9ae2f072010-08-23 23:25:46 +00004539 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004540 RParenLoc))
4541 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004542
John McCall9ae2f072010-08-23 23:25:46 +00004543 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004544 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004545 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004546 diag::err_typecheck_call_not_function)
4547 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004548 }
4549 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004550 }
4551
Douglas Gregorfa047642009-02-04 00:32:51 +00004552 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004553 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004554 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004555
Eli Friedmanefa42f72009-12-26 03:35:45 +00004556 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00004557 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4558 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4559 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004560 RParenLoc, ExecConfig);
Douglas Gregoref9b1492010-11-09 20:03:54 +00004561 }
4562
John McCall3b4294e2009-12-16 12:17:52 +00004563 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00004564 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4565 if (UnOp->getOpcode() == UO_AddrOf)
4566 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4567
John McCall3b4294e2009-12-16 12:17:52 +00004568 if (isa<DeclRefExpr>(NakedFn))
4569 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4570
Peter Collingbournee08ce652011-02-09 21:07:24 +00004571 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4572 ExecConfig);
4573}
4574
4575ExprResult
4576Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4577 MultiExprArg execConfig, SourceLocation GGGLoc) {
4578 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4579 if (!ConfigDecl)
4580 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4581 << "cudaConfigureCall");
4582 QualType ConfigQTy = ConfigDecl->getType();
4583
4584 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4585 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4586
4587 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00004588}
4589
John McCall3b4294e2009-12-16 12:17:52 +00004590/// BuildResolvedCallExpr - Build a call to a resolved expression,
4591/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00004592/// unary-convert to an expression of function-pointer or
4593/// block-pointer type.
4594///
4595/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00004596ExprResult
John McCallaa81e162009-12-01 22:10:20 +00004597Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4598 SourceLocation LParenLoc,
4599 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004600 SourceLocation RParenLoc,
4601 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00004602 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4603
Chris Lattner04421082008-04-08 04:40:51 +00004604 // Promote the function operand.
4605 UsualUnaryConversions(Fn);
4606
Chris Lattner925e60d2007-12-28 05:29:59 +00004607 // Make the call expr early, before semantic checks. This guarantees cleanup
4608 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004609 CallExpr *TheCall;
4610 if (Config) {
4611 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4612 cast<CallExpr>(Config),
4613 Args, NumArgs,
4614 Context.BoolTy,
4615 VK_RValue,
4616 RParenLoc);
4617 } else {
4618 TheCall = new (Context) CallExpr(Context, Fn,
4619 Args, NumArgs,
4620 Context.BoolTy,
4621 VK_RValue,
4622 RParenLoc);
4623 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004624
Steve Naroffdd972f22008-09-05 22:11:13 +00004625 const FunctionType *FuncT;
4626 if (!Fn->getType()->isBlockPointerType()) {
4627 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4628 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00004629 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00004630 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00004631 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4632 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00004633 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00004634 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00004635 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00004636 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00004637 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004638 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00004639 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4640 << Fn->getType() << Fn->getSourceRange());
4641
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004642 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004643 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00004644 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004645 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004646 return ExprError();
4647
Chris Lattner925e60d2007-12-28 05:29:59 +00004648 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004649 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004650 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004651
Douglas Gregor72564e72009-02-26 23:50:07 +00004652 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00004653 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00004654 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004655 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004656 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004657 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004658
Douglas Gregor74734d52009-04-02 15:37:10 +00004659 if (FDecl) {
4660 // Check if we have too few/too many template arguments, based
4661 // on our knowledge of the function definition.
4662 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004663 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004664 const FunctionProtoType *Proto
4665 = Def->getType()->getAs<FunctionProtoType>();
4666 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004667 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4668 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004669 }
Douglas Gregor46542412010-10-25 20:39:23 +00004670
4671 // If the function we're calling isn't a function prototype, but we have
4672 // a function prototype from a prior declaratiom, use that prototype.
4673 if (!FDecl->hasPrototype())
4674 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004675 }
4676
Steve Naroffb291ab62007-08-28 23:30:39 +00004677 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004678 for (unsigned i = 0; i != NumArgs; i++) {
4679 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004680
4681 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004682 InitializedEntity Entity
4683 = InitializedEntity::InitializeParameter(Context,
4684 Proto->getArgType(i));
4685 ExprResult ArgE = PerformCopyInitialization(Entity,
4686 SourceLocation(),
4687 Owned(Arg));
4688 if (ArgE.isInvalid())
4689 return true;
4690
4691 Arg = ArgE.takeAs<Expr>();
4692
4693 } else {
4694 DefaultArgumentPromotion(Arg);
Douglas Gregor46542412010-10-25 20:39:23 +00004695 }
4696
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004697 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4698 Arg->getType(),
4699 PDiag(diag::err_call_incomplete_argument)
4700 << Arg->getSourceRange()))
4701 return ExprError();
4702
Chris Lattner925e60d2007-12-28 05:29:59 +00004703 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004704 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004705 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004706
Douglas Gregor88a35142008-12-22 05:46:06 +00004707 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4708 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004709 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4710 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004711
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004712 // Check for sentinels
4713 if (NDecl)
4714 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004715
Chris Lattner59907c42007-08-10 20:18:51 +00004716 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004717 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00004718 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00004719 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004720
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004721 if (unsigned BuiltinID = FDecl->getBuiltinID())
4722 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004723 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00004724 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00004725 return ExprError();
4726 }
Chris Lattner59907c42007-08-10 20:18:51 +00004727
John McCall9ae2f072010-08-23 23:25:46 +00004728 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004729}
4730
John McCall60d7b3a2010-08-24 06:29:42 +00004731ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004732Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004733 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004734 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004735 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004736 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004737
4738 TypeSourceInfo *TInfo;
4739 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4740 if (!TInfo)
4741 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4742
John McCall9ae2f072010-08-23 23:25:46 +00004743 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004744}
4745
John McCall60d7b3a2010-08-24 06:29:42 +00004746ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004747Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00004748 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004749 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004750
Eli Friedman6223c222008-05-20 05:22:08 +00004751 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004752 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4753 PDiag(diag::err_illegal_decl_array_incomplete_type)
4754 << SourceRange(LParenLoc,
4755 literalExpr->getSourceRange().getEnd())))
4756 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004757 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004758 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4759 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004760 } else if (!literalType->isDependentType() &&
4761 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004762 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00004763 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00004764 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004765 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004766
Douglas Gregor99a2e602009-12-16 01:38:02 +00004767 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004768 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004769 InitializationKind Kind
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004770 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004771 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00004772 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00004773 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00004774 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00004775 &literalType);
4776 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004777 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004778 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004779
Chris Lattner371f2582008-12-04 23:50:19 +00004780 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004781 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00004782 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004783 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004784 }
Eli Friedman08544622009-12-22 02:35:53 +00004785
John McCallf89e55a2010-11-18 06:31:45 +00004786 // In C, compound literals are l-values for some reason.
4787 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4788
John McCall1d7d8d62010-01-19 22:33:45 +00004789 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCallf89e55a2010-11-18 06:31:45 +00004790 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004791}
4792
John McCall60d7b3a2010-08-24 06:29:42 +00004793ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004794Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004795 SourceLocation RBraceLoc) {
4796 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00004797 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00004798
Steve Naroff08d92e42007-09-15 18:49:24 +00004799 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004800 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004801
Ted Kremenek709210f2010-04-13 23:39:13 +00004802 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4803 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004804 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004805 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004806}
4807
John McCallf3ea8cf2010-11-14 08:17:51 +00004808/// Prepares for a scalar cast, performing all the necessary stages
4809/// except the final cast and returning the kind required.
4810static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4811 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4812 // Also, callers should have filtered out the invalid cases with
4813 // pointers. Everything else should be possible.
4814
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004815 QualType SrcTy = Src->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00004816 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004817 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004818
John McCalldaa8e4e2010-11-15 09:13:47 +00004819 switch (SrcTy->getScalarTypeKind()) {
4820 case Type::STK_MemberPointer:
4821 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004822
John McCalldaa8e4e2010-11-15 09:13:47 +00004823 case Type::STK_Pointer:
4824 switch (DestTy->getScalarTypeKind()) {
4825 case Type::STK_Pointer:
4826 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00004827 CK_AnyPointerToObjCPointerCast :
4828 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004829 case Type::STK_Bool:
4830 return CK_PointerToBoolean;
4831 case Type::STK_Integral:
4832 return CK_PointerToIntegral;
4833 case Type::STK_Floating:
4834 case Type::STK_FloatingComplex:
4835 case Type::STK_IntegralComplex:
4836 case Type::STK_MemberPointer:
4837 llvm_unreachable("illegal cast from pointer");
4838 }
4839 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004840
John McCalldaa8e4e2010-11-15 09:13:47 +00004841 case Type::STK_Bool: // casting from bool is like casting from an integer
4842 case Type::STK_Integral:
4843 switch (DestTy->getScalarTypeKind()) {
4844 case Type::STK_Pointer:
John McCallf3ea8cf2010-11-14 08:17:51 +00004845 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004846 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004847 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004848 case Type::STK_Bool:
4849 return CK_IntegralToBoolean;
4850 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004851 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004852 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004853 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004854 case Type::STK_IntegralComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004855 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCall8786da72010-12-14 17:51:41 +00004856 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004857 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004858 case Type::STK_FloatingComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004859 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004860 CK_IntegralToFloating);
4861 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004862 case Type::STK_MemberPointer:
4863 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004864 }
4865 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004866
John McCalldaa8e4e2010-11-15 09:13:47 +00004867 case Type::STK_Floating:
4868 switch (DestTy->getScalarTypeKind()) {
4869 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004870 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004871 case Type::STK_Bool:
4872 return CK_FloatingToBoolean;
4873 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004874 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004875 case Type::STK_FloatingComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004876 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCall8786da72010-12-14 17:51:41 +00004877 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004878 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004879 case Type::STK_IntegralComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004880 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004881 CK_FloatingToIntegral);
4882 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004883 case Type::STK_Pointer:
4884 llvm_unreachable("valid float->pointer cast?");
4885 case Type::STK_MemberPointer:
4886 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004887 }
4888 break;
4889
John McCalldaa8e4e2010-11-15 09:13:47 +00004890 case Type::STK_FloatingComplex:
4891 switch (DestTy->getScalarTypeKind()) {
4892 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004893 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004894 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004895 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004896 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004897 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00004898 if (S.Context.hasSameType(ET, DestTy))
4899 return CK_FloatingComplexToReal;
4900 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4901 return CK_FloatingCast;
4902 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004903 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004904 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004905 case Type::STK_Integral:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004906 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004907 CK_FloatingComplexToReal);
4908 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004909 case Type::STK_Pointer:
4910 llvm_unreachable("valid complex float->pointer cast?");
4911 case Type::STK_MemberPointer:
4912 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004913 }
4914 break;
4915
John McCalldaa8e4e2010-11-15 09:13:47 +00004916 case Type::STK_IntegralComplex:
4917 switch (DestTy->getScalarTypeKind()) {
4918 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004919 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004920 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004921 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004922 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004923 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00004924 if (S.Context.hasSameType(ET, DestTy))
4925 return CK_IntegralComplexToReal;
4926 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4927 return CK_IntegralCast;
4928 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004929 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004930 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004931 case Type::STK_Floating:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004932 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004933 CK_IntegralComplexToReal);
4934 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004935 case Type::STK_Pointer:
4936 llvm_unreachable("valid complex int->pointer cast?");
4937 case Type::STK_MemberPointer:
4938 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004939 }
4940 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00004941 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004942
John McCallf3ea8cf2010-11-14 08:17:51 +00004943 llvm_unreachable("Unhandled scalar cast");
4944 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00004945}
4946
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004947/// CheckCastTypes - Check type constraints for casting between types.
John McCallf89e55a2010-11-18 06:31:45 +00004948bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4949 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4950 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004951 if (getLangOptions().CPlusPlus)
Douglas Gregor40749ee2010-11-03 00:35:38 +00004952 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4953 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00004954 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004955 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004956
John McCallf89e55a2010-11-18 06:31:45 +00004957 // We only support r-value casts in C.
4958 VK = VK_RValue;
4959
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004960 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4961 // type needs to be scalar.
4962 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00004963 // We don't necessarily do lvalue-to-rvalue conversions on this.
4964 IgnoredValueConversions(castExpr);
4965
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004966 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00004967 Kind = CK_ToVoid;
Anders Carlssonebeaf202009-10-16 02:35:04 +00004968 return false;
4969 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004970
John McCallf6a16482010-12-04 03:47:34 +00004971 DefaultFunctionArrayLvalueConversion(castExpr);
4972
Eli Friedman8d438082010-07-17 20:43:49 +00004973 if (RequireCompleteType(TyR.getBegin(), castType,
4974 diag::err_typecheck_cast_to_incomplete))
4975 return true;
4976
Anders Carlssonebeaf202009-10-16 02:35:04 +00004977 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00004978 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004979 (castType->isStructureType() || castType->isUnionType())) {
4980 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004981 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004982 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4983 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004984 Kind = CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00004985 return false;
4986 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004987
Anders Carlssonc3516322009-10-16 02:48:28 +00004988 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004989 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00004990 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004991 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004992 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004993 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004994 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00004995 castExpr->getType()) &&
4996 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004997 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4998 << castExpr->getSourceRange();
4999 break;
5000 }
5001 }
5002 if (Field == FieldEnd)
5003 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
5004 << castExpr->getType() << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005005 Kind = CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00005006 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005007 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005008
Anders Carlssonc3516322009-10-16 02:48:28 +00005009 // Reject any other conversions to non-scalar types.
5010 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
5011 << castType << castExpr->getSourceRange();
5012 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005013
John McCallf3ea8cf2010-11-14 08:17:51 +00005014 // The type we're casting to is known to be a scalar or vector.
5015
5016 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005017 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00005018 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005019 return Diag(castExpr->getLocStart(),
5020 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00005021 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00005022 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005023
5024 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00005025 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005026
Anders Carlssonc3516322009-10-16 02:48:28 +00005027 if (castType->isVectorType())
5028 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
5029 if (castExpr->getType()->isVectorType())
5030 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
5031
John McCallf3ea8cf2010-11-14 08:17:51 +00005032 // The source and target types are both scalars, i.e.
5033 // - arithmetic types (fundamental, enum, and complex)
5034 // - all kinds of pointers
5035 // Note that member pointers were filtered out with C++, above.
5036
Anders Carlsson16a89042009-10-16 05:23:41 +00005037 if (isa<ObjCSelectorExpr>(castExpr))
5038 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005039
John McCallf3ea8cf2010-11-14 08:17:51 +00005040 // If either type is a pointer, the other type has to be either an
5041 // integer or a pointer.
Anders Carlssonc3516322009-10-16 02:48:28 +00005042 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00005043 QualType castExprType = castExpr->getType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005044 if (!castExprType->isIntegralType(Context) &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005045 castExprType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00005046 return Diag(castExpr->getLocStart(),
5047 diag::err_cast_pointer_from_non_pointer_int)
5048 << castExprType << castExpr->getSourceRange();
5049 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005050 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00005051 return Diag(castExpr->getLocStart(),
5052 diag::err_cast_pointer_to_non_pointer_int)
5053 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005054 }
Anders Carlsson82debc72009-10-18 18:12:03 +00005055
John McCallf3ea8cf2010-11-14 08:17:51 +00005056 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCallb7f4ffe2010-08-12 21:44:57 +00005057
John McCallf3ea8cf2010-11-14 08:17:51 +00005058 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00005059 CheckCastAlign(castExpr, castType, TyR);
5060
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005061 return false;
5062}
5063
Anders Carlssonc3516322009-10-16 02:48:28 +00005064bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00005065 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00005066 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005067
Anders Carlssona64db8f2007-11-27 05:51:55 +00005068 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00005069 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00005070 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00005071 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00005072 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005073 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00005074 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005075 } else
5076 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005077 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00005078 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005079
John McCall2de56d12010-08-25 11:45:40 +00005080 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005081 return false;
5082}
5083
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005084bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCall2de56d12010-08-25 11:45:40 +00005085 CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00005086 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005087
Anders Carlsson16a89042009-10-16 05:23:41 +00005088 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005089
Nate Begeman9b10da62009-06-27 22:05:55 +00005090 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5091 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00005092 if (SrcTy->isVectorType()) {
5093 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
5094 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5095 << DestTy << SrcTy << R;
John McCall2de56d12010-08-25 11:45:40 +00005096 Kind = CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00005097 return false;
5098 }
5099
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005100 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00005101 // conversion will take place first from scalar to elt type, and then
5102 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005103 if (SrcTy->isPointerType())
5104 return Diag(R.getBegin(),
5105 diag::err_invalid_conversion_between_vector_and_scalar)
5106 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00005107
5108 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5109 ImpCastExprToType(CastExpr, DestElemTy,
John McCallf3ea8cf2010-11-14 08:17:51 +00005110 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005111
John McCall2de56d12010-08-25 11:45:40 +00005112 Kind = CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00005113 return false;
5114}
5115
John McCall60d7b3a2010-08-24 06:29:42 +00005116ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005117Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005118 SourceLocation RParenLoc, Expr *castExpr) {
5119 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005120 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00005121
John McCall9d125032010-01-15 18:39:57 +00005122 TypeSourceInfo *castTInfo;
5123 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5124 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00005125 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00005126
Nate Begeman2ef13e52009-08-10 23:49:36 +00005127 // If the Expr being casted is a ParenListExpr, handle it specially.
5128 if (isa<ParenListExpr>(castExpr))
John McCall9ae2f072010-08-23 23:25:46 +00005129 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCall42f56b52010-01-18 19:35:47 +00005130 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00005131
John McCall9ae2f072010-08-23 23:25:46 +00005132 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00005133}
5134
John McCall60d7b3a2010-08-24 06:29:42 +00005135ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00005136Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005137 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005138 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00005139 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00005140 CXXCastPath BasePath;
John McCallb042fdf2010-01-15 18:56:44 +00005141 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCallf89e55a2010-11-18 06:31:45 +00005142 Kind, VK, BasePath))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005143 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00005144
John McCallf871d0c2010-08-07 06:22:56 +00005145 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +00005146 Ty->getType().getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +00005147 VK, Kind, castExpr, &BasePath, Ty,
John McCallf871d0c2010-08-07 06:22:56 +00005148 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005149}
5150
Nate Begeman2ef13e52009-08-10 23:49:36 +00005151/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5152/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005153ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005154Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005155 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5156 if (!E)
5157 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00005158
John McCall60d7b3a2010-08-24 06:29:42 +00005159 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00005160
Nate Begeman2ef13e52009-08-10 23:49:36 +00005161 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00005162 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5163 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00005164
John McCall9ae2f072010-08-23 23:25:46 +00005165 if (Result.isInvalid()) return ExprError();
5166
5167 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005168}
5169
John McCall60d7b3a2010-08-24 06:29:42 +00005170ExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00005171Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00005172 SourceLocation RParenLoc, Expr *Op,
John McCall42f56b52010-01-18 19:35:47 +00005173 TypeSourceInfo *TInfo) {
John McCall9ae2f072010-08-23 23:25:46 +00005174 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCall42f56b52010-01-18 19:35:47 +00005175 QualType Ty = TInfo->getType();
John Thompson8bb59a82010-06-30 22:55:51 +00005176 bool isAltiVecLiteral = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005177
John Thompson8bb59a82010-06-30 22:55:51 +00005178 // Check for an altivec literal,
5179 // i.e. all the elements are integer constants.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005180 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5181 if (PE->getNumExprs() == 0) {
5182 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5183 return ExprError();
5184 }
John Thompson8bb59a82010-06-30 22:55:51 +00005185 if (PE->getNumExprs() == 1) {
5186 if (!PE->getExpr(0)->getType()->isVectorType())
5187 isAltiVecLiteral = true;
5188 }
5189 else
5190 isAltiVecLiteral = true;
5191 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00005192
John Thompson8bb59a82010-06-30 22:55:51 +00005193 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
5194 // then handle it as such.
5195 if (isAltiVecLiteral) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005196 llvm::SmallVector<Expr *, 8> initExprs;
5197 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5198 initExprs.push_back(PE->getExpr(i));
5199
5200 // FIXME: This means that pretty-printing the final AST will produce curly
5201 // braces instead of the original commas.
Ted Kremenek709210f2010-04-13 23:39:13 +00005202 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5203 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00005204 initExprs.size(), RParenLoc);
5205 E->setType(Ty);
John McCall9ae2f072010-08-23 23:25:46 +00005206 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005207 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005208 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00005209 // sequence of BinOp comma operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005210 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCall9ae2f072010-08-23 23:25:46 +00005211 if (Result.isInvalid()) return ExprError();
5212 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005213 }
5214}
5215
John McCall60d7b3a2010-08-24 06:29:42 +00005216ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00005217 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005218 MultiExprArg Val,
John McCallb3d87482010-08-24 05:47:05 +00005219 ParsedType TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005220 unsigned nexprs = Val.size();
5221 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005222 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5223 Expr *expr;
5224 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5225 expr = new (Context) ParenExpr(L, R, exprs[0]);
5226 else
5227 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005228 return Owned(expr);
5229}
5230
Sebastian Redl28507842009-02-26 14:39:58 +00005231/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5232/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00005233/// C99 6.5.15
5234QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005235 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00005236 SourceLocation QuestionLoc) {
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005237 // If both LHS and RHS are overloaded functions, try to resolve them.
5238 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
5239 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
5240 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
5241 if (LHSResult.isInvalid())
5242 return QualType();
5243
5244 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
5245 if (RHSResult.isInvalid())
5246 return QualType();
5247
5248 LHS = LHSResult.take();
5249 RHS = RHSResult.take();
5250 }
5251
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005252 // C++ is sufficiently different to merit its own checker.
5253 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00005254 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00005255
5256 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005257 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005258
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005259 UsualUnaryConversions(Cond);
John McCall56ca35d2011-02-17 10:25:35 +00005260 UsualUnaryConversions(LHS);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005261 UsualUnaryConversions(RHS);
5262 QualType CondTy = Cond->getType();
5263 QualType LHSTy = LHS->getType();
5264 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005265
Reid Spencer5f016e22007-07-11 17:01:13 +00005266 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005267 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begeman6155d732010-09-20 22:41:17 +00005268 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5269 // Throw an error if its not either.
5270 if (getLangOptions().OpenCL) {
5271 if (!CondTy->isVectorType()) {
5272 Diag(Cond->getLocStart(),
5273 diag::err_typecheck_cond_expect_scalar_or_vector)
5274 << CondTy;
5275 return QualType();
5276 }
5277 }
5278 else {
5279 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5280 << CondTy;
5281 return QualType();
5282 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005283 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005284
Chris Lattner70d67a92008-01-06 22:42:25 +00005285 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005286 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5287 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00005288
Nate Begeman6155d732010-09-20 22:41:17 +00005289 // OpenCL: If the condition is a vector, and both operands are scalar,
5290 // attempt to implicity convert them to the vector type to act like the
5291 // built in select.
5292 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5293 // Both operands should be of scalar type.
5294 if (!LHSTy->isScalarType()) {
5295 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5296 << CondTy;
5297 return QualType();
5298 }
5299 if (!RHSTy->isScalarType()) {
5300 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5301 << CondTy;
5302 return QualType();
5303 }
5304 // Implicity convert these scalars to the type of the condition.
5305 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5306 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5307 }
5308
Chris Lattner70d67a92008-01-06 22:42:25 +00005309 // If both operands have arithmetic type, do the usual arithmetic conversions
5310 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005311 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5312 UsualArithmeticConversions(LHS, RHS);
5313 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005314 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005315
Chris Lattner70d67a92008-01-06 22:42:25 +00005316 // If both operands are the same structure or union type, the result is that
5317 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005318 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5319 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005320 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005321 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005322 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005323 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005324 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005325 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005326
Chris Lattner70d67a92008-01-06 22:42:25 +00005327 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005328 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005329 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5330 if (!LHSTy->isVoidType())
5331 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5332 << RHS->getSourceRange();
5333 if (!RHSTy->isVoidType())
5334 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5335 << LHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005336 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5337 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00005338 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00005339 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00005340 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5341 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005342 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005343 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005344 // promote the null to a pointer.
John McCalldaa8e4e2010-11-15 09:13:47 +00005345 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005346 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005347 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005348 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005349 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005350 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005351 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005352 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005353
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005354 // All objective-c pointer type analysis is done here.
5355 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5356 QuestionLoc);
5357 if (!compositeType.isNull())
5358 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005359
5360
Steve Naroff7154a772009-07-01 14:36:47 +00005361 // Handle block pointer types.
5362 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5363 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5364 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5365 QualType destType = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005366 ImpCastExprToType(LHS, destType, CK_BitCast);
5367 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005368 return destType;
5369 }
5370 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005371 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00005372 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005373 }
Steve Naroff7154a772009-07-01 14:36:47 +00005374 // We have 2 block pointer types.
5375 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5376 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005377 return LHSTy;
5378 }
Steve Naroff7154a772009-07-01 14:36:47 +00005379 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00005380 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5381 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005382
Steve Naroff7154a772009-07-01 14:36:47 +00005383 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5384 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00005385 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005386 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005387 // In this situation, we assume void* type. No especially good
5388 // reason, but this is what gcc does, and we do have to pick
5389 // to get a consistent AST.
5390 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005391 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5392 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00005393 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005394 }
Steve Naroff7154a772009-07-01 14:36:47 +00005395 // The block pointer types are compatible.
John McCall2de56d12010-08-25 11:45:40 +00005396 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5397 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00005398 return LHSTy;
5399 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005400
Steve Naroff7154a772009-07-01 14:36:47 +00005401 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5402 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5403 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00005404 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5405 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00005406
5407 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5408 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5409 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00005410 QualType destPointee
5411 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005412 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005413 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005414 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005415 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005416 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005417 return destType;
5418 }
5419 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00005420 QualType destPointee
5421 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005422 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005423 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005424 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005425 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005426 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005427 return destType;
5428 }
5429
5430 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5431 // Two identical pointer types are always compatible.
5432 return LHSTy;
5433 }
5434 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5435 rhptee.getUnqualifiedType())) {
5436 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5437 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5438 // In this situation, we assume void* type. No especially good
5439 // reason, but this is what gcc does, and we do have to pick
5440 // to get a consistent AST.
5441 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005442 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5443 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005444 return incompatTy;
5445 }
5446 // The pointer types are compatible.
5447 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5448 // differently qualified versions of compatible types, the result type is
5449 // a pointer to an appropriately qualified version of the *composite*
5450 // type.
5451 // FIXME: Need to calculate the composite type.
5452 // FIXME: Need to add qualifiers
John McCall2de56d12010-08-25 11:45:40 +00005453 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5454 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005455 return LHSTy;
5456 }
Mike Stump1eb44332009-09-09 15:08:12 +00005457
John McCall404cd162010-11-13 01:35:44 +00005458 // GCC compatibility: soften pointer/integer mismatch. Note that
5459 // null pointers have been filtered out by this point.
Steve Naroff7154a772009-07-01 14:36:47 +00005460 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5461 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5462 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005463 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005464 return RHSTy;
5465 }
5466 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5467 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5468 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005469 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005470 return LHSTy;
5471 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005472
Chris Lattner70d67a92008-01-06 22:42:25 +00005473 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005474 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5475 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005476 return QualType();
5477}
5478
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005479/// FindCompositeObjCPointerType - Helper method to find composite type of
5480/// two objective-c pointer types of the two input expressions.
5481QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5482 SourceLocation QuestionLoc) {
5483 QualType LHSTy = LHS->getType();
5484 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005485
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005486 // Handle things like Class and struct objc_class*. Here we case the result
5487 // to the pseudo-builtin, because that will be implicitly cast back to the
5488 // redefinition type if an attempt is made to access its fields.
5489 if (LHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005490 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005491 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005492 return LHSTy;
5493 }
5494 if (RHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005495 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005496 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005497 return RHSTy;
5498 }
5499 // And the same for struct objc_object* / id
5500 if (LHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005501 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005502 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005503 return LHSTy;
5504 }
5505 if (RHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005506 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005507 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005508 return RHSTy;
5509 }
5510 // And the same for struct objc_selector* / SEL
5511 if (Context.isObjCSelType(LHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00005512 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005513 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005514 return LHSTy;
5515 }
5516 if (Context.isObjCSelType(RHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00005517 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005518 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005519 return RHSTy;
5520 }
5521 // Check constraints for Objective-C object pointers types.
5522 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005523
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005524 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5525 // Two identical object pointer types are always compatible.
5526 return LHSTy;
5527 }
5528 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5529 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5530 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005531
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005532 // If both operands are interfaces and either operand can be
5533 // assigned to the other, use that type as the composite
5534 // type. This allows
5535 // xxx ? (A*) a : (B*) b
5536 // where B is a subclass of A.
5537 //
5538 // Additionally, as for assignment, if either type is 'id'
5539 // allow silent coercion. Finally, if the types are
5540 // incompatible then make sure to use 'id' as the composite
5541 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005542
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005543 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5544 // It could return the composite type.
5545 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5546 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5547 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5548 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5549 } else if ((LHSTy->isObjCQualifiedIdType() ||
5550 RHSTy->isObjCQualifiedIdType()) &&
5551 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5552 // Need to handle "id<xx>" explicitly.
5553 // GCC allows qualified id and any Objective-C type to devolve to
5554 // id. Currently localizing to here until clear this should be
5555 // part of ObjCQualifiedIdTypesAreCompatible.
5556 compositeType = Context.getObjCIdType();
5557 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5558 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005559 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005560 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5561 ;
5562 else {
5563 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5564 << LHSTy << RHSTy
5565 << LHS->getSourceRange() << RHS->getSourceRange();
5566 QualType incompatTy = Context.getObjCIdType();
John McCall2de56d12010-08-25 11:45:40 +00005567 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5568 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005569 return incompatTy;
5570 }
5571 // The object pointer types are compatible.
John McCall2de56d12010-08-25 11:45:40 +00005572 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5573 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005574 return compositeType;
5575 }
5576 // Check Objective-C object pointer types and 'void *'
5577 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5578 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5579 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5580 QualType destPointee
5581 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5582 QualType destType = Context.getPointerType(destPointee);
5583 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005584 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005585 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005586 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005587 return destType;
5588 }
5589 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5590 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5591 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5592 QualType destPointee
5593 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5594 QualType destType = Context.getPointerType(destPointee);
5595 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005596 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005597 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005598 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005599 return destType;
5600 }
5601 return QualType();
5602}
5603
Steve Narofff69936d2007-09-16 03:34:24 +00005604/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005605/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005606ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005607 SourceLocation ColonLoc,
5608 Expr *CondExpr, Expr *LHSExpr,
5609 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005610 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5611 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005612 OpaqueValueExpr *opaqueValue = 0;
5613 Expr *commonExpr = 0;
5614 if (LHSExpr == 0) {
5615 commonExpr = CondExpr;
5616
5617 // We usually want to apply unary conversions *before* saving, except
5618 // in the special case of a C++ l-value conditional.
5619 if (!(getLangOptions().CPlusPlus
5620 && !commonExpr->isTypeDependent()
5621 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5622 && commonExpr->isGLValue()
5623 && commonExpr->isOrdinaryOrBitFieldObject()
5624 && RHSExpr->isOrdinaryOrBitFieldObject()
5625 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5626 UsualUnaryConversions(commonExpr);
5627 }
5628
5629 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5630 commonExpr->getType(),
5631 commonExpr->getValueKind(),
5632 commonExpr->getObjectKind());
5633 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005634 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005635
John McCallf89e55a2010-11-18 06:31:45 +00005636 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005637 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian1fb019b2010-09-18 19:38:38 +00005638 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCall56ca35d2011-02-17 10:25:35 +00005639 VK, OK, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00005640 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005641 return ExprError();
5642
John McCall56ca35d2011-02-17 10:25:35 +00005643 if (!commonExpr)
5644 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
5645 LHSExpr, ColonLoc,
5646 RHSExpr, result, VK, OK));
5647
5648 return Owned(new (Context)
5649 BinaryConditionalOperator(commonExpr, opaqueValue, CondExpr, LHSExpr,
5650 RHSExpr, QuestionLoc, ColonLoc, result, VK, OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005651}
5652
John McCalle4be87e2011-01-31 23:13:11 +00005653// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005654// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005655// routine is it effectively iqnores the qualifiers on the top level pointee.
5656// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5657// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005658static Sema::AssignConvertType
5659checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5660 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5661 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005662
Reid Spencer5f016e22007-07-11 17:01:13 +00005663 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005664 const Type *lhptee, *rhptee;
5665 Qualifiers lhq, rhq;
5666 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5667 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005668
John McCalle4be87e2011-01-31 23:13:11 +00005669 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005670
5671 // C99 6.5.16.1p1: This following citation is common to constraints
5672 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5673 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005674 Qualifiers lq;
5675
5676 if (!lhq.compatiblyIncludes(rhq)) {
5677 // Treat address-space mismatches as fatal. TODO: address subspaces
5678 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5679 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5680
5681 // For GCC compatibility, other qualifier mismatches are treated
5682 // as still compatible in C.
5683 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5684 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005685
Mike Stumpeed9cac2009-02-19 03:04:26 +00005686 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5687 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005688 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005689 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005690 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005691 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005692
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005693 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005694 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005695 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005696 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005697
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005698 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005699 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005700 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005701
5702 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005703 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005704 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005705 }
John McCall86c05f32011-02-01 00:10:29 +00005706
Mike Stumpeed9cac2009-02-19 03:04:26 +00005707 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005708 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005709 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5710 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005711 // Check if the pointee types are compatible ignoring the sign.
5712 // We explicitly check for char so that we catch "char" vs
5713 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005714 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005715 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005716 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005717 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005718
Chris Lattner6a2b9262009-10-17 20:33:28 +00005719 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005720 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005721 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005722 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005723
John McCall86c05f32011-02-01 00:10:29 +00005724 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005725 // Types are compatible ignoring the sign. Qualifier incompatibility
5726 // takes priority over sign incompatibility because the sign
5727 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005728 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005729 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005730
John McCalle4be87e2011-01-31 23:13:11 +00005731 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005732 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005733
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005734 // If we are a multi-level pointer, it's possible that our issue is simply
5735 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5736 // the eventual target type is the same and the pointers have the same
5737 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005738 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005739 do {
John McCall86c05f32011-02-01 00:10:29 +00005740 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5741 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005742 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005743
John McCall86c05f32011-02-01 00:10:29 +00005744 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005745 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005746 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005747
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005748 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005749 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005750 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005751 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005752}
5753
John McCalle4be87e2011-01-31 23:13:11 +00005754/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005755/// block pointer types are compatible or whether a block and normal pointer
5756/// are compatible. It is more restrict than comparing two function pointer
5757// types.
John McCalle4be87e2011-01-31 23:13:11 +00005758static Sema::AssignConvertType
5759checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5760 QualType rhsType) {
5761 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5762 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5763
Steve Naroff1c7d0672008-09-04 15:10:53 +00005764 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005765
Steve Naroff1c7d0672008-09-04 15:10:53 +00005766 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00005767 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5768 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005769
John McCalle4be87e2011-01-31 23:13:11 +00005770 // In C++, the types have to match exactly.
5771 if (S.getLangOptions().CPlusPlus)
5772 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005773
John McCalle4be87e2011-01-31 23:13:11 +00005774 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005775
Steve Naroff1c7d0672008-09-04 15:10:53 +00005776 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005777 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5778 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005779
John McCalle4be87e2011-01-31 23:13:11 +00005780 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5781 return Sema::IncompatibleBlockPointer;
5782
Steve Naroff1c7d0672008-09-04 15:10:53 +00005783 return ConvTy;
5784}
5785
John McCalle4be87e2011-01-31 23:13:11 +00005786/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005787/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005788static Sema::AssignConvertType
5789checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5790 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5791 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5792
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005793 if (lhsType->isObjCBuiltinType()) {
5794 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005795 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5796 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005797 return Sema::IncompatiblePointer;
5798 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005799 }
5800 if (rhsType->isObjCBuiltinType()) {
5801 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005802 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5803 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005804 return Sema::IncompatiblePointer;
5805 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005806 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005807 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005808 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005809 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005810 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005811
John McCalle4be87e2011-01-31 23:13:11 +00005812 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5813 return Sema::CompatiblePointerDiscardsQualifiers;
5814
5815 if (S.Context.typesAreCompatible(lhsType, rhsType))
5816 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005817 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005818 return Sema::IncompatibleObjCQualifiedId;
5819 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005820}
5821
John McCall1c23e912010-11-16 02:32:08 +00005822Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005823Sema::CheckAssignmentConstraints(SourceLocation Loc,
5824 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00005825 // Fake up an opaque expression. We don't actually care about what
5826 // cast operations are required, so if CheckAssignmentConstraints
5827 // adds casts to this they'll be wasted, but fortunately that doesn't
5828 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00005829 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John McCall1c23e912010-11-16 02:32:08 +00005830 Expr *rhsPtr = &rhs;
5831 CastKind K = CK_Invalid;
5832
5833 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5834}
5835
Mike Stumpeed9cac2009-02-19 03:04:26 +00005836/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5837/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005838/// pointers. Here are some objectionable examples that GCC considers warnings:
5839///
5840/// int a, *pint;
5841/// short *pshort;
5842/// struct foo *pfoo;
5843///
5844/// pint = pshort; // warning: assignment from incompatible pointer type
5845/// a = pint; // warning: assignment makes integer from pointer without a cast
5846/// pint = a; // warning: assignment makes pointer from integer without a cast
5847/// pint = pfoo; // warning: assignment from incompatible pointer type
5848///
5849/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005850/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005851///
John McCalldaa8e4e2010-11-15 09:13:47 +00005852/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005853Sema::AssignConvertType
John McCall1c23e912010-11-16 02:32:08 +00005854Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00005855 CastKind &Kind) {
John McCall1c23e912010-11-16 02:32:08 +00005856 QualType rhsType = rhs->getType();
5857
Chris Lattnerfc144e22008-01-04 23:18:45 +00005858 // Get canonical types. We're not formatting these types, just comparing
5859 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005860 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5861 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005862
John McCallb6cfa242011-01-31 22:28:28 +00005863 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00005864 if (lhsType == rhsType) {
5865 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005866 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005867 }
5868
Douglas Gregor9d293df2008-10-28 00:22:11 +00005869 // If the left-hand side is a reference type, then we are in a
5870 // (rare!) case where we've allowed the use of references in C,
5871 // e.g., as a parameter type in a built-in function. In this case,
5872 // just make sure that the type referenced is compatible with the
5873 // right-hand side type. The caller is responsible for adjusting
5874 // lhsType so that the resulting expression does not have reference
5875 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005876 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005877 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5878 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005879 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005880 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005881 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005882 }
John McCallb6cfa242011-01-31 22:28:28 +00005883
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005884 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5885 // to the same ExtVector type.
5886 if (lhsType->isExtVectorType()) {
5887 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005888 return Incompatible;
5889 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005890 // CK_VectorSplat does T -> vector T, so first cast to the
5891 // element type.
5892 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5893 if (elType != rhsType) {
5894 Kind = PrepareScalarCast(*this, rhs, elType);
5895 ImpCastExprToType(rhs, elType, Kind);
5896 }
5897 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005898 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005899 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005900 }
Mike Stump1eb44332009-09-09 15:08:12 +00005901
John McCallb6cfa242011-01-31 22:28:28 +00005902 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005903 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00005904 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005905 // Allow assignments of an AltiVec vector type to an equivalent GCC
5906 // vector type and vice versa
5907 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5908 Kind = CK_BitCast;
5909 return Compatible;
5910 }
5911
Douglas Gregor255210e2010-08-06 10:14:59 +00005912 // If we are allowing lax vector conversions, and LHS and RHS are both
5913 // vectors, the total size only needs to be the same. This is a bitcast;
5914 // no bits are changed but the result type is different.
5915 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005916 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005917 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005918 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005919 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005920 }
5921 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005922 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005923
John McCallb6cfa242011-01-31 22:28:28 +00005924 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00005925 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005926 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00005927 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005928 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005929 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005930
John McCallb6cfa242011-01-31 22:28:28 +00005931 // Conversions to normal pointers.
5932 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5933 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00005934 if (isa<PointerType>(rhsType)) {
5935 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00005936 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005937 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005938
John McCallb6cfa242011-01-31 22:28:28 +00005939 // int -> T*
5940 if (rhsType->isIntegerType()) {
5941 Kind = CK_IntegralToPointer; // FIXME: null?
5942 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005943 }
John McCallb6cfa242011-01-31 22:28:28 +00005944
5945 // C pointers are not compatible with ObjC object pointers,
5946 // with two exceptions:
5947 if (isa<ObjCObjectPointerType>(rhsType)) {
5948 // - conversions to void*
5949 if (lhsPointer->getPointeeType()->isVoidType()) {
5950 Kind = CK_AnyPointerToObjCPointerCast;
5951 return Compatible;
5952 }
5953
5954 // - conversions from 'Class' to the redefinition type
5955 if (rhsType->isObjCClassType() &&
5956 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005957 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005958 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005959 }
Steve Naroffb4406862008-09-29 18:10:17 +00005960
John McCallb6cfa242011-01-31 22:28:28 +00005961 Kind = CK_BitCast;
5962 return IncompatiblePointer;
5963 }
5964
5965 // U^ -> void*
5966 if (rhsType->getAs<BlockPointerType>()) {
5967 if (lhsPointer->getPointeeType()->isVoidType()) {
5968 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005969 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005970 }
Steve Naroffb4406862008-09-29 18:10:17 +00005971 }
John McCallb6cfa242011-01-31 22:28:28 +00005972
Steve Naroff1c7d0672008-09-04 15:10:53 +00005973 return Incompatible;
5974 }
5975
John McCallb6cfa242011-01-31 22:28:28 +00005976 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00005977 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005978 // U^ -> T^
5979 if (rhsType->isBlockPointerType()) {
5980 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00005981 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00005982 }
5983
5984 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00005985 if (rhsType->isIntegerType()) {
5986 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005987 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005988 }
5989
John McCallb6cfa242011-01-31 22:28:28 +00005990 // id -> T^
5991 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5992 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005993 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005994 }
Steve Naroffb4406862008-09-29 18:10:17 +00005995
John McCallb6cfa242011-01-31 22:28:28 +00005996 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00005997 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005998 if (RHSPT->getPointeeType()->isVoidType()) {
5999 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006000 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006001 }
John McCalldaa8e4e2010-11-15 09:13:47 +00006002
Chris Lattnerfc144e22008-01-04 23:18:45 +00006003 return Incompatible;
6004 }
6005
John McCallb6cfa242011-01-31 22:28:28 +00006006 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00006007 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006008 // A* -> B*
6009 if (rhsType->isObjCObjectPointerType()) {
6010 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006011 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006012 }
6013
6014 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00006015 if (rhsType->isIntegerType()) {
6016 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00006017 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006018 }
6019
John McCallb6cfa242011-01-31 22:28:28 +00006020 // In general, C pointers are not compatible with ObjC object pointers,
6021 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00006022 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006023 // - conversions from 'void*'
6024 if (rhsType->isVoidPointerType()) {
6025 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006026 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006027 }
6028
6029 // - conversions to 'Class' from its redefinition type
6030 if (lhsType->isObjCClassType() &&
6031 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6032 Kind = CK_BitCast;
6033 return Compatible;
6034 }
6035
6036 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006037 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006038 }
John McCallb6cfa242011-01-31 22:28:28 +00006039
6040 // T^ -> A*
6041 if (rhsType->isBlockPointerType()) {
6042 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00006043 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006044 }
6045
Steve Naroff14108da2009-07-10 23:34:53 +00006046 return Incompatible;
6047 }
John McCallb6cfa242011-01-31 22:28:28 +00006048
6049 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00006050 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006051 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006052 if (lhsType == Context.BoolTy) {
6053 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006054 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006055 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006056
John McCallb6cfa242011-01-31 22:28:28 +00006057 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006058 if (lhsType->isIntegerType()) {
6059 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006060 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006061 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006062
Chris Lattnerfc144e22008-01-04 23:18:45 +00006063 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00006064 }
John McCallb6cfa242011-01-31 22:28:28 +00006065
6066 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00006067 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006068 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006069 if (lhsType == Context.BoolTy) {
6070 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00006071 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006072 }
Steve Naroff14108da2009-07-10 23:34:53 +00006073
John McCallb6cfa242011-01-31 22:28:28 +00006074 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006075 if (lhsType->isIntegerType()) {
6076 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00006077 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006078 }
6079
Steve Naroff14108da2009-07-10 23:34:53 +00006080 return Incompatible;
6081 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006082
John McCallb6cfa242011-01-31 22:28:28 +00006083 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00006084 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006085 if (Context.typesAreCompatible(lhsType, rhsType)) {
6086 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00006087 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006088 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006089 }
John McCallb6cfa242011-01-31 22:28:28 +00006090
Reid Spencer5f016e22007-07-11 17:01:13 +00006091 return Incompatible;
6092}
6093
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006094/// \brief Constructs a transparent union from an expression that is
6095/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00006096static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006097 QualType UnionType, FieldDecl *Field) {
6098 // Build an initializer list that designates the appropriate member
6099 // of the transparent union.
Ted Kremenek709210f2010-04-13 23:39:13 +00006100 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00006101 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006102 SourceLocation());
6103 Initializer->setType(UnionType);
6104 Initializer->setInitializedFieldInUnion(Field);
6105
6106 // Build a compound literal constructing a value of the transparent
6107 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00006108 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall1d7d8d62010-01-19 22:33:45 +00006109 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCallf89e55a2010-11-18 06:31:45 +00006110 VK_RValue, Initializer, false);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006111}
6112
6113Sema::AssignConvertType
6114Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
6115 QualType FromType = rExpr->getType();
6116
Mike Stump1eb44332009-09-09 15:08:12 +00006117 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006118 // transparent_union GCC extension.
6119 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006120 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006121 return Incompatible;
6122
6123 // The field to initialize within the transparent union.
6124 RecordDecl *UD = UT->getDecl();
6125 FieldDecl *InitField = 0;
6126 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006127 for (RecordDecl::field_iterator it = UD->field_begin(),
6128 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006129 it != itend; ++it) {
6130 if (it->getType()->isPointerType()) {
6131 // If the transparent union contains a pointer type, we allow:
6132 // 1) void pointer
6133 // 2) null pointer constant
6134 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00006135 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCall2de56d12010-08-25 11:45:40 +00006136 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006137 InitField = *it;
6138 break;
6139 }
Mike Stump1eb44332009-09-09 15:08:12 +00006140
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006141 if (rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006142 Expr::NPC_ValueDependentIsNull)) {
John McCall404cd162010-11-13 01:35:44 +00006143 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006144 InitField = *it;
6145 break;
6146 }
6147 }
6148
John McCall1c23e912010-11-16 02:32:08 +00006149 Expr *rhs = rExpr;
John McCalldaa8e4e2010-11-15 09:13:47 +00006150 CastKind Kind = CK_Invalid;
John McCall1c23e912010-11-16 02:32:08 +00006151 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006152 == Compatible) {
John McCall1c23e912010-11-16 02:32:08 +00006153 ImpCastExprToType(rhs, it->getType(), Kind);
6154 rExpr = rhs;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006155 InitField = *it;
6156 break;
6157 }
6158 }
6159
6160 if (!InitField)
6161 return Incompatible;
6162
6163 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
6164 return Compatible;
6165}
6166
Chris Lattner5cf216b2008-01-04 18:04:52 +00006167Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00006168Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00006169 if (getLangOptions().CPlusPlus) {
6170 if (!lhsType->isRecordType()) {
6171 // C++ 5.17p3: If the left operand is not of class type, the
6172 // expression is implicitly converted (C++ 4) to the
6173 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00006174 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00006175 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00006176 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00006177 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00006178 }
6179
6180 // FIXME: Currently, we fall through and treat C++ classes like C
6181 // structures.
John McCallf6a16482010-12-04 03:47:34 +00006182 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00006183
Steve Naroff529a4ad2007-11-27 17:58:44 +00006184 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6185 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00006186 if ((lhsType->isPointerType() ||
6187 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00006188 lhsType->isBlockPointerType())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006189 && rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006190 Expr::NPC_ValueDependentIsNull)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006191 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00006192 return Compatible;
6193 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006194
Chris Lattner943140e2007-10-16 02:55:40 +00006195 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00006196 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00006197 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00006198 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00006199 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00006200 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00006201 if (!lhsType->isReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00006202 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00006203
John McCalldaa8e4e2010-11-15 09:13:47 +00006204 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006205 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00006206 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006207
Steve Narofff1120de2007-08-24 22:33:52 +00006208 // C99 6.5.16.1p2: The value of the right operand is converted to the
6209 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006210 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6211 // so that we can use references in built-in functions even in C.
6212 // The getNonReferenceType() call makes sure that the resulting expression
6213 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006214 if (result != Incompatible && rExpr->getType() != lhsType)
John McCalldaa8e4e2010-11-15 09:13:47 +00006215 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006216 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006217}
6218
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006219QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006220 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00006221 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006222 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00006223 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006224}
6225
Chris Lattner7ef655a2010-01-12 21:23:57 +00006226QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00006227 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006228 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00006229 QualType lhsType =
6230 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
6231 QualType rhsType =
6232 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006233
Nate Begemanbe2341d2008-07-14 18:02:46 +00006234 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006235 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00006236 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006237
Nate Begemanbe2341d2008-07-14 18:02:46 +00006238 // Handle the case of a vector & extvector type of the same size and element
6239 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006240 if (getLangOptions().LaxVectorConversions) {
John McCall183700f2009-09-21 23:43:11 +00006241 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth629f9e42010-08-30 07:36:24 +00006242 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006243 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006244 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregor26bcf672010-05-19 03:21:00 +00006245 if (lhsType->isExtVectorType()) {
John McCall2de56d12010-08-25 11:45:40 +00006246 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006247 return lhsType;
6248 }
6249
John McCall2de56d12010-08-25 11:45:40 +00006250 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006251 return rhsType;
Eric Christophere84f9eb2010-08-26 00:42:16 +00006252 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6253 // If we are allowing lax vector conversions, and LHS and RHS are both
6254 // vectors, the total size only needs to be the same. This is a
6255 // bitcast; no bits are changed but the result type is different.
6256 ImpCastExprToType(rex, lhsType, CK_BitCast);
6257 return lhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006258 }
Eric Christophere84f9eb2010-08-26 00:42:16 +00006259 }
Chandler Carruth629f9e42010-08-30 07:36:24 +00006260 }
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006261 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006262
Douglas Gregor255210e2010-08-06 10:14:59 +00006263 // Handle the case of equivalent AltiVec and GCC vector types
6264 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6265 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCall2de56d12010-08-25 11:45:40 +00006266 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00006267 return rhsType;
6268 }
6269
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006270 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6271 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6272 bool swapped = false;
6273 if (rhsType->isExtVectorType()) {
6274 swapped = true;
6275 std::swap(rex, lex);
6276 std::swap(rhsType, lhsType);
6277 }
Mike Stump1eb44332009-09-09 15:08:12 +00006278
Nate Begemandde25982009-06-28 19:12:57 +00006279 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00006280 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006281 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00006282 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006283 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6284 if (order > 0)
6285 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
6286 if (order >= 0) {
6287 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006288 if (swapped) std::swap(rex, lex);
6289 return lhsType;
6290 }
6291 }
6292 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6293 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006294 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6295 if (order > 0)
6296 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
6297 if (order >= 0) {
6298 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006299 if (swapped) std::swap(rex, lex);
6300 return lhsType;
6301 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006302 }
6303 }
Mike Stump1eb44332009-09-09 15:08:12 +00006304
Nate Begemandde25982009-06-28 19:12:57 +00006305 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006306 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00006307 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006308 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006309 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006310}
6311
Chris Lattner7ef655a2010-01-12 21:23:57 +00006312QualType Sema::CheckMultiplyDivideOperands(
6313 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00006314 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006315 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006316
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006317 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006318
Chris Lattner7ef655a2010-01-12 21:23:57 +00006319 if (!lex->getType()->isArithmeticType() ||
6320 !rex->getType()->isArithmeticType())
6321 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006322
Chris Lattner7ef655a2010-01-12 21:23:57 +00006323 // Check for division by zero.
6324 if (isDiv &&
6325 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006326 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattnercb329c52010-01-12 21:30:55 +00006327 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006328
Chris Lattner7ef655a2010-01-12 21:23:57 +00006329 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006330}
6331
Chris Lattner7ef655a2010-01-12 21:23:57 +00006332QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00006333 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00006334 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006335 if (lex->getType()->hasIntegerRepresentation() &&
6336 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar523aa602009-01-05 22:55:36 +00006337 return CheckVectorOperands(Loc, lex, rex);
6338 return InvalidOperands(Loc, lex, rex);
6339 }
Steve Naroff90045e82007-07-13 23:32:42 +00006340
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006341 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006342
Chris Lattner7ef655a2010-01-12 21:23:57 +00006343 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6344 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006345
Chris Lattner7ef655a2010-01-12 21:23:57 +00006346 // Check for remainder by zero.
6347 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattnercb329c52010-01-12 21:30:55 +00006348 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
6349 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006350
Chris Lattner7ef655a2010-01-12 21:23:57 +00006351 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006352}
6353
Chris Lattner7ef655a2010-01-12 21:23:57 +00006354QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00006355 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006356 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6357 QualType compType = CheckVectorOperands(Loc, lex, rex);
6358 if (CompLHSTy) *CompLHSTy = compType;
6359 return compType;
6360 }
Steve Naroff49b45262007-07-13 16:58:59 +00006361
Eli Friedmanab3a8522009-03-28 01:22:36 +00006362 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006363
Reid Spencer5f016e22007-07-11 17:01:13 +00006364 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00006365 if (lex->getType()->isArithmeticType() &&
6366 rex->getType()->isArithmeticType()) {
6367 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006368 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006369 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006370
Eli Friedmand72d16e2008-05-18 18:08:51 +00006371 // Put any potential pointer into PExp
6372 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006373 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006374 std::swap(PExp, IExp);
6375
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006376 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006377
Eli Friedmand72d16e2008-05-18 18:08:51 +00006378 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00006379 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00006380
Chris Lattnerb5f15622009-04-24 23:50:08 +00006381 // Check for arithmetic on pointers to incomplete types.
6382 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006383 if (getLangOptions().CPlusPlus) {
6384 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006385 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006386 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006387 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006388
6389 // GNU extension: arithmetic on pointer to void
6390 Diag(Loc, diag::ext_gnu_void_ptr)
6391 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00006392 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006393 if (getLangOptions().CPlusPlus) {
6394 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6395 << lex->getType() << lex->getSourceRange();
6396 return QualType();
6397 }
6398
6399 // GNU extension: arithmetic on pointer to function
6400 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6401 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00006402 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00006403 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00006404 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00006405 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00006406 PExp->getType()->isObjCObjectPointerType()) &&
6407 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00006408 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6409 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006410 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00006411 return QualType();
6412 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00006413 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006414 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006415 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6416 << PointeeTy << PExp->getSourceRange();
6417 return QualType();
6418 }
Mike Stump1eb44332009-09-09 15:08:12 +00006419
Eli Friedmanab3a8522009-03-28 01:22:36 +00006420 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00006421 QualType LHSTy = Context.isPromotableBitField(lex);
6422 if (LHSTy.isNull()) {
6423 LHSTy = lex->getType();
6424 if (LHSTy->isPromotableIntegerType())
6425 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00006426 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00006427 *CompLHSTy = LHSTy;
6428 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00006429 return PExp->getType();
6430 }
6431 }
6432
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006433 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006434}
6435
Chris Lattnereca7be62008-04-07 05:30:13 +00006436// C99 6.5.6
6437QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006438 SourceLocation Loc, QualType* CompLHSTy) {
6439 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6440 QualType compType = CheckVectorOperands(Loc, lex, rex);
6441 if (CompLHSTy) *CompLHSTy = compType;
6442 return compType;
6443 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006444
Eli Friedmanab3a8522009-03-28 01:22:36 +00006445 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006446
Chris Lattner6e4ab612007-12-09 21:53:25 +00006447 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006448
Chris Lattner6e4ab612007-12-09 21:53:25 +00006449 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00006450 if (lex->getType()->isArithmeticType()
6451 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006452 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006453 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006454 }
Mike Stump1eb44332009-09-09 15:08:12 +00006455
Chris Lattner6e4ab612007-12-09 21:53:25 +00006456 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006457 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00006458 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006459
Douglas Gregore7450f52009-03-24 19:52:54 +00006460 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00006461
Douglas Gregore7450f52009-03-24 19:52:54 +00006462 bool ComplainAboutVoid = false;
6463 Expr *ComplainAboutFunc = 0;
6464 if (lpointee->isVoidType()) {
6465 if (getLangOptions().CPlusPlus) {
6466 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6467 << lex->getSourceRange() << rex->getSourceRange();
6468 return QualType();
6469 }
6470
6471 // GNU C extension: arithmetic on pointer to void
6472 ComplainAboutVoid = true;
6473 } else if (lpointee->isFunctionType()) {
6474 if (getLangOptions().CPlusPlus) {
6475 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00006476 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006477 return QualType();
6478 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006479
6480 // GNU C extension: arithmetic on pointer to function
6481 ComplainAboutFunc = lex;
6482 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006483 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00006484 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00006485 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006486 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00006487 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006488
Chris Lattnerb5f15622009-04-24 23:50:08 +00006489 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006490 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006491 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6492 << lpointee << lex->getSourceRange();
6493 return QualType();
6494 }
Mike Stump1eb44332009-09-09 15:08:12 +00006495
Chris Lattner6e4ab612007-12-09 21:53:25 +00006496 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00006497 if (rex->getType()->isIntegerType()) {
6498 if (ComplainAboutVoid)
6499 Diag(Loc, diag::ext_gnu_void_ptr)
6500 << lex->getSourceRange() << rex->getSourceRange();
6501 if (ComplainAboutFunc)
6502 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00006503 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00006504 << ComplainAboutFunc->getSourceRange();
6505
Eli Friedmanab3a8522009-03-28 01:22:36 +00006506 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006507 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006508 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006509
Chris Lattner6e4ab612007-12-09 21:53:25 +00006510 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006511 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006512 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006513
Douglas Gregore7450f52009-03-24 19:52:54 +00006514 // RHS must be a completely-type object type.
6515 // Handle the GNU void* extension.
6516 if (rpointee->isVoidType()) {
6517 if (getLangOptions().CPlusPlus) {
6518 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6519 << lex->getSourceRange() << rex->getSourceRange();
6520 return QualType();
6521 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006522
Douglas Gregore7450f52009-03-24 19:52:54 +00006523 ComplainAboutVoid = true;
6524 } else if (rpointee->isFunctionType()) {
6525 if (getLangOptions().CPlusPlus) {
6526 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00006527 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006528 return QualType();
6529 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006530
6531 // GNU extension: arithmetic on pointer to function
6532 if (!ComplainAboutFunc)
6533 ComplainAboutFunc = rex;
6534 } else if (!rpointee->isDependentType() &&
6535 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00006536 PDiag(diag::err_typecheck_sub_ptr_object)
6537 << rex->getSourceRange()
6538 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00006539 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006540
Eli Friedman88d936b2009-05-16 13:54:38 +00006541 if (getLangOptions().CPlusPlus) {
6542 // Pointee types must be the same: C++ [expr.add]
6543 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6544 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6545 << lex->getType() << rex->getType()
6546 << lex->getSourceRange() << rex->getSourceRange();
6547 return QualType();
6548 }
6549 } else {
6550 // Pointee types must be compatible C99 6.5.6p3
6551 if (!Context.typesAreCompatible(
6552 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6553 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6554 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6555 << lex->getType() << rex->getType()
6556 << lex->getSourceRange() << rex->getSourceRange();
6557 return QualType();
6558 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006559 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006560
Douglas Gregore7450f52009-03-24 19:52:54 +00006561 if (ComplainAboutVoid)
6562 Diag(Loc, diag::ext_gnu_void_ptr)
6563 << lex->getSourceRange() << rex->getSourceRange();
6564 if (ComplainAboutFunc)
6565 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00006566 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00006567 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006568
6569 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006570 return Context.getPointerDiffType();
6571 }
6572 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006573
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006574 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006575}
6576
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006577static bool isScopedEnumerationType(QualType T) {
6578 if (const EnumType *ET = dyn_cast<EnumType>(T))
6579 return ET->getDecl()->isScoped();
6580 return false;
6581}
6582
Chris Lattnereca7be62008-04-07 05:30:13 +00006583// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006584QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00006585 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00006586 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregorf6094622010-07-23 15:58:24 +00006587 if (!lex->getType()->hasIntegerRepresentation() ||
6588 !rex->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006589 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006590
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006591 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6592 // hasIntegerRepresentation() above instead of this.
6593 if (isScopedEnumerationType(lex->getType()) ||
6594 isScopedEnumerationType(rex->getType())) {
6595 return InvalidOperands(Loc, lex, rex);
6596 }
6597
Nate Begeman2207d792009-10-25 02:26:48 +00006598 // Vector shifts promote their scalar inputs to vector type.
6599 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6600 return CheckVectorOperands(Loc, lex, rex);
6601
Chris Lattnerca5eede2007-12-12 05:47:28 +00006602 // Shifts don't perform usual arithmetic conversions, they just do integer
6603 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006604
John McCall1bc80af2010-12-16 19:28:59 +00006605 // For the LHS, do usual unary conversions, but then reset them away
6606 // if this is a compound assignment.
6607 Expr *old_lex = lex;
6608 UsualUnaryConversions(lex);
6609 QualType LHSTy = lex->getType();
6610 if (isCompAssign) lex = old_lex;
6611
6612 // The RHS is simpler.
Chris Lattnerca5eede2007-12-12 05:47:28 +00006613 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006614
Ryan Flynnd0439682009-08-07 16:20:20 +00006615 // Sanity-check shift operands
6616 llvm::APSInt Right;
6617 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00006618 if (!rex->isValueDependent() &&
6619 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00006620 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00006621 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6622 else {
6623 llvm::APInt LeftBits(Right.getBitWidth(),
6624 Context.getTypeSize(lex->getType()));
6625 if (Right.uge(LeftBits))
6626 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6627 }
6628 }
6629
Chris Lattnerca5eede2007-12-12 05:47:28 +00006630 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00006631 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006632}
6633
Chandler Carruth99919472010-07-10 12:30:03 +00006634static bool IsWithinTemplateSpecialization(Decl *D) {
6635 if (DeclContext *DC = D->getDeclContext()) {
6636 if (isa<ClassTemplateSpecializationDecl>(DC))
6637 return true;
6638 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6639 return FD->isFunctionTemplateSpecialization();
6640 }
6641 return false;
6642}
6643
Douglas Gregor0c6db942009-05-04 06:07:12 +00006644// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006645QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00006646 unsigned OpaqueOpc, bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00006647 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006648
Chris Lattner02dd4b12009-12-05 05:40:13 +00006649 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00006650 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006651 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006652
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006653 QualType lType = lex->getType();
6654 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006655
Chandler Carruth543cb652011-02-17 08:37:06 +00006656 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6657 Expr *RHSStripped = rex->IgnoreParenImpCasts();
6658 QualType LHSStrippedType = LHSStripped->getType();
6659 QualType RHSStrippedType = RHSStripped->getType();
6660
6661 // Two different enums will raise a warning when compared.
6662 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6663 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6664 if (LHSEnumType->getDecl()->getIdentifier() &&
6665 RHSEnumType->getDecl()->getIdentifier() &&
6666 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6667 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6668 << LHSStrippedType << RHSStrippedType
6669 << lex->getSourceRange() << rex->getSourceRange();
6670 }
6671 }
6672 }
6673
Douglas Gregor8eee1192010-06-22 22:12:46 +00006674 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006675 !(lType->isBlockPointerType() && isRelational) &&
6676 !lex->getLocStart().isMacroID() &&
6677 !rex->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006678 // For non-floating point types, check for self-comparisons of the form
6679 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6680 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006681 //
6682 // NOTE: Don't warn about comparison expressions resulting from macro
6683 // expansion. Also don't warn about comparisons which are only self
6684 // comparisons within a template specialization. The warnings should catch
6685 // obvious cases in the definition of the template anyways. The idea is to
6686 // warn when the typed comparison operator will always evaluate to the same
6687 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006688 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006689 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006690 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006691 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006692 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6693 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006694 << (Opc == BO_EQ
6695 || Opc == BO_LE
6696 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00006697 } else if (lType->isArrayType() && rType->isArrayType() &&
6698 !DRL->getDecl()->getType()->isReferenceType() &&
6699 !DRR->getDecl()->getType()->isReferenceType()) {
6700 // what is it always going to eval to?
6701 char always_evals_to;
6702 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006703 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006704 always_evals_to = 0; // false
6705 break;
John McCall2de56d12010-08-25 11:45:40 +00006706 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006707 always_evals_to = 1; // true
6708 break;
6709 default:
6710 // best we can say is 'a constant'
6711 always_evals_to = 2; // e.g. array1 <= array2
6712 break;
6713 }
6714 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6715 << 1 // array
6716 << always_evals_to);
6717 }
6718 }
Chandler Carruth99919472010-07-10 12:30:03 +00006719 }
Mike Stump1eb44332009-09-09 15:08:12 +00006720
Chris Lattner55660a72009-03-08 19:39:53 +00006721 if (isa<CastExpr>(LHSStripped))
6722 LHSStripped = LHSStripped->IgnoreParenCasts();
6723 if (isa<CastExpr>(RHSStripped))
6724 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006725
Chris Lattner55660a72009-03-08 19:39:53 +00006726 // Warn about comparisons against a string constant (unless the other
6727 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006728 Expr *literalString = 0;
6729 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006730 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006731 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006732 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00006733 literalString = lex;
6734 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006735 } else if ((isa<StringLiteral>(RHSStripped) ||
6736 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006737 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006738 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00006739 literalString = rex;
6740 literalStringStripped = RHSStripped;
6741 }
6742
6743 if (literalString) {
6744 std::string resultComparison;
6745 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006746 case BO_LT: resultComparison = ") < 0"; break;
6747 case BO_GT: resultComparison = ") > 0"; break;
6748 case BO_LE: resultComparison = ") <= 0"; break;
6749 case BO_GE: resultComparison = ") >= 0"; break;
6750 case BO_EQ: resultComparison = ") == 0"; break;
6751 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00006752 default: assert(false && "Invalid comparison operator");
6753 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006754
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006755 DiagRuntimeBehavior(Loc,
6756 PDiag(diag::warn_stringcompare)
6757 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006758 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006759 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006760 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006761
Douglas Gregord64fdd02010-06-08 19:50:34 +00006762 // C99 6.5.8p3 / C99 6.5.9p4
6763 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6764 UsualArithmeticConversions(lex, rex);
6765 else {
6766 UsualUnaryConversions(lex);
6767 UsualUnaryConversions(rex);
6768 }
6769
6770 lType = lex->getType();
6771 rType = rex->getType();
6772
Douglas Gregor447b69e2008-11-19 03:25:36 +00006773 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00006774 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00006775
Chris Lattnera5937dd2007-08-26 01:18:55 +00006776 if (isRelational) {
6777 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006778 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006779 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006780 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006781 if (lType->hasFloatingRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006782 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006783
Chris Lattnera5937dd2007-08-26 01:18:55 +00006784 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006785 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006786 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006787
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006788 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006789 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006790 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006791 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006792
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006793 // All of the following pointer-related warnings are GCC extensions, except
6794 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00006795 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006796 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006797 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00006798 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006799 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006800
Douglas Gregor0c6db942009-05-04 06:07:12 +00006801 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006802 if (LCanPointeeTy == RCanPointeeTy)
6803 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006804 if (!isRelational &&
6805 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6806 // Valid unless comparison between non-null pointer and function pointer
6807 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006808 // In a SFINAE context, we treat this as a hard error to maintain
6809 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006810 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6811 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006812 Diag(Loc,
6813 isSFINAEContext()?
6814 diag::err_typecheck_comparison_of_fptr_to_void
6815 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006816 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006817
6818 if (isSFINAEContext())
6819 return QualType();
6820
John McCall2de56d12010-08-25 11:45:40 +00006821 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006822 return ResultTy;
6823 }
6824 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006825
Douglas Gregor0c6db942009-05-04 06:07:12 +00006826 // C++ [expr.rel]p2:
6827 // [...] Pointer conversions (4.10) and qualification
6828 // conversions (4.4) are performed on pointer operands (or on
6829 // a pointer operand and a null pointer constant) to bring
6830 // them to their composite pointer type. [...]
6831 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00006832 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00006833 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006834 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006835 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006836 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006837 if (T.isNull()) {
6838 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6839 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6840 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006841 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006842 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006843 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006844 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006845 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00006846 }
6847
John McCall2de56d12010-08-25 11:45:40 +00006848 ImpCastExprToType(lex, T, CK_BitCast);
6849 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006850 return ResultTy;
6851 }
Eli Friedman3075e762009-08-23 00:27:47 +00006852 // C99 6.5.9p2 and C99 6.5.8p2
6853 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6854 RCanPointeeTy.getUnqualifiedType())) {
6855 // Valid unless a relational comparison of function pointers
6856 if (isRelational && LCanPointeeTy->isFunctionType()) {
6857 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6858 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6859 }
6860 } else if (!isRelational &&
6861 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6862 // Valid unless comparison between non-null pointer and function pointer
6863 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6864 && !LHSIsNull && !RHSIsNull) {
6865 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6866 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6867 }
6868 } else {
6869 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006870 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00006871 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006872 }
Eli Friedman3075e762009-08-23 00:27:47 +00006873 if (LCanPointeeTy != RCanPointeeTy)
John McCall2de56d12010-08-25 11:45:40 +00006874 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006875 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00006876 }
Mike Stump1eb44332009-09-09 15:08:12 +00006877
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006878 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006879 // Comparison of nullptr_t with itself.
6880 if (lType->isNullPtrType() && rType->isNullPtrType())
6881 return ResultTy;
6882
Mike Stump1eb44332009-09-09 15:08:12 +00006883 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00006884 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00006885 if (RHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006886 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00006887 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregor443c2122010-08-07 13:36:37 +00006888 ImpCastExprToType(rex, lType,
6889 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006890 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006891 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006892 return ResultTy;
6893 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006894 if (LHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006895 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00006896 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregor443c2122010-08-07 13:36:37 +00006897 ImpCastExprToType(lex, rType,
6898 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006899 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006900 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006901 return ResultTy;
6902 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006903
6904 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00006905 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00006906 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6907 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006908 // In addition, pointers to members can be compared, or a pointer to
6909 // member and a null pointer constant. Pointer to member conversions
6910 // (4.11) and qualification conversions (4.4) are performed to bring
6911 // them to a common type. If one operand is a null pointer constant,
6912 // the common type is the type of the other operand. Otherwise, the
6913 // common type is a pointer to member type similar (4.4) to the type
6914 // of one of the operands, with a cv-qualification signature (4.4)
6915 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00006916 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006917 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006918 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006919 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00006920 if (T.isNull()) {
6921 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006922 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00006923 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006924 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006925 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006926 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006927 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006928 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00006929 }
Mike Stump1eb44332009-09-09 15:08:12 +00006930
John McCall2de56d12010-08-25 11:45:40 +00006931 ImpCastExprToType(lex, T, CK_BitCast);
6932 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00006933 return ResultTy;
6934 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006935 }
Mike Stump1eb44332009-09-09 15:08:12 +00006936
Steve Naroff1c7d0672008-09-04 15:10:53 +00006937 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00006938 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006939 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6940 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006941
Steve Naroff1c7d0672008-09-04 15:10:53 +00006942 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00006943 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006944 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00006945 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00006946 }
John McCall2de56d12010-08-25 11:45:40 +00006947 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006948 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006949 }
Steve Naroff59f53942008-09-28 01:11:11 +00006950 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00006951 if (!isRelational
6952 && ((lType->isBlockPointerType() && rType->isPointerType())
6953 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00006954 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006955 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006956 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00006957 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006958 ->getPointeeType()->isVoidType())))
6959 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6960 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00006961 }
John McCall2de56d12010-08-25 11:45:40 +00006962 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006963 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00006964 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00006965
Steve Naroff14108da2009-07-10 23:34:53 +00006966 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00006967 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006968 const PointerType *LPT = lType->getAs<PointerType>();
6969 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006970 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00006971 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006972 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00006973 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006974
Steve Naroffa8069f12008-11-17 19:49:16 +00006975 if (!LPtrToVoid && !RPtrToVoid &&
6976 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006977 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00006978 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00006979 }
John McCall2de56d12010-08-25 11:45:40 +00006980 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006981 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00006982 }
Steve Naroff14108da2009-07-10 23:34:53 +00006983 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006984 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00006985 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6986 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00006987 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006988 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00006989 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00006990 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006991 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6992 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006993 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006994 bool isError = false;
6995 if ((LHSIsNull && lType->isIntegerType()) ||
6996 (RHSIsNull && rType->isIntegerType())) {
6997 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006998 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006999 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007000 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007001 else if (getLangOptions().CPlusPlus) {
7002 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7003 isError = true;
7004 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007005 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007006
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007007 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007008 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00007009 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007010 if (isError)
7011 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007012 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007013
7014 if (lType->isIntegerType())
John McCall404cd162010-11-13 01:35:44 +00007015 ImpCastExprToType(lex, rType,
7016 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007017 else
John McCall404cd162010-11-13 01:35:44 +00007018 ImpCastExprToType(rex, lType,
7019 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007020 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007021 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007022
Steve Naroff39218df2008-09-04 16:56:14 +00007023 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00007024 if (!isRelational && RHSIsNull
7025 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCall404cd162010-11-13 01:35:44 +00007026 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007027 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007028 }
Mike Stumpaf199f32009-05-07 18:43:07 +00007029 if (!isRelational && LHSIsNull
7030 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCall404cd162010-11-13 01:35:44 +00007031 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007032 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007033 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007034 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007035}
7036
Nate Begemanbe2341d2008-07-14 18:02:46 +00007037/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007038/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007039/// like a scalar comparison, a vector comparison produces a vector of integer
7040/// types.
7041QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007042 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007043 bool isRelational) {
7044 // Check to make sure we're operating on vectors of the same type and width,
7045 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007046 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007047 if (vType.isNull())
7048 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007049
Anton Yartsevaa4fe052010-11-18 03:19:30 +00007050 // If AltiVec, the comparison results in a numeric type, i.e.
7051 // bool for C++, int for C
7052 if (getLangOptions().AltiVec)
7053 return (getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy);
7054
Nate Begemanbe2341d2008-07-14 18:02:46 +00007055 QualType lType = lex->getType();
7056 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007057
Nate Begemanbe2341d2008-07-14 18:02:46 +00007058 // For non-floating point types, check for self-comparisons of the form
7059 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7060 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007061 if (!lType->hasFloatingRepresentation()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007062 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
7063 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
7064 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregord64fdd02010-06-08 19:50:34 +00007065 DiagRuntimeBehavior(Loc,
7066 PDiag(diag::warn_comparison_always)
7067 << 0 // self-
7068 << 2 // "a constant"
7069 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007070 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007071
Nate Begemanbe2341d2008-07-14 18:02:46 +00007072 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007073 if (!isRelational && lType->hasFloatingRepresentation()) {
7074 assert (rType->hasFloatingRepresentation());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007075 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007076 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007077
Nate Begemanbe2341d2008-07-14 18:02:46 +00007078 // Return the type for the comparison, which is the same as vector type for
7079 // integer vectors, or an integer type of identical size and number of
7080 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00007081 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00007082 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007083
John McCall183700f2009-09-21 23:43:11 +00007084 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00007085 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00007086 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007087 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00007088 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00007089 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7090
Mike Stumpeed9cac2009-02-19 03:04:26 +00007091 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00007092 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00007093 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7094}
7095
Reid Spencer5f016e22007-07-11 17:01:13 +00007096inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00007097 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregorf6094622010-07-23 15:58:24 +00007098 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
7099 if (lex->getType()->hasIntegerRepresentation() &&
7100 rex->getType()->hasIntegerRepresentation())
7101 return CheckVectorOperands(Loc, lex, rex);
7102
7103 return InvalidOperands(Loc, lex, rex);
7104 }
Steve Naroff90045e82007-07-13 23:32:42 +00007105
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007106 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007107
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007108 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
7109 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007110 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007111 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007112}
7113
7114inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner90a8f272010-07-13 19:41:32 +00007115 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
7116
7117 // Diagnose cases where the user write a logical and/or but probably meant a
7118 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7119 // is a constant.
7120 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman787b0942010-07-27 19:14:53 +00007121 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattner23ef3e42010-07-15 00:26:43 +00007122 // Don't warn in macros.
Chris Lattnerb7690b42010-07-24 01:10:11 +00007123 !Loc.isMacroID()) {
7124 // If the RHS can be constant folded, and if it constant folds to something
7125 // that isn't 0 or 1 (which indicate a potential logical operation that
7126 // happened to fold to true/false) then warn.
7127 Expr::EvalResult Result;
7128 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
7129 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7130 Diag(Loc, diag::warn_logical_instead_of_bitwise)
7131 << rex->getSourceRange()
John McCall2de56d12010-08-25 11:45:40 +00007132 << (Opc == BO_LAnd ? "&&" : "||")
7133 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattnerb7690b42010-07-24 01:10:11 +00007134 }
7135 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007136
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007137 if (!Context.getLangOptions().CPlusPlus) {
7138 UsualUnaryConversions(lex);
7139 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007140
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007141 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
7142 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007143
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007144 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007145 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007146
John McCall75f7c0f2010-06-04 00:29:51 +00007147 // The following is safe because we only use this method for
7148 // non-overloadable operands.
7149
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007150 // C++ [expr.log.and]p1
7151 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007152 // The operands are both contextually converted to type bool.
7153 if (PerformContextuallyConvertToBool(lex) ||
7154 PerformContextuallyConvertToBool(rex))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007155 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007156
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007157 // C++ [expr.log.and]p2
7158 // C++ [expr.log.or]p2
7159 // The result is a bool.
7160 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007161}
7162
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007163/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7164/// is a read-only property; return true if so. A readonly property expression
7165/// depends on various declarations and thus must be treated specially.
7166///
Mike Stump1eb44332009-09-09 15:08:12 +00007167static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007168 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7169 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00007170 if (PropExpr->isImplicitProperty()) return false;
7171
7172 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7173 QualType BaseType = PropExpr->isSuperReceiver() ?
7174 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007175 PropExpr->getBase()->getType();
7176
John McCall12f78a62010-12-02 01:19:52 +00007177 if (const ObjCObjectPointerType *OPT =
7178 BaseType->getAsObjCInterfacePointerType())
7179 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7180 if (S.isPropertyReadonly(PDecl, IFace))
7181 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007182 }
7183 return false;
7184}
7185
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007186/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7187/// emit an error and return true. If so, return false.
7188static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007189 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007190 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007191 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007192 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7193 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007194 if (IsLV == Expr::MLV_Valid)
7195 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007196
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007197 unsigned Diag = 0;
7198 bool NeedType = false;
7199 switch (IsLV) { // C99 6.5.16p2
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007200 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007201 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007202 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7203 NeedType = true;
7204 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007205 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007206 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7207 NeedType = true;
7208 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007209 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007210 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7211 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007212 case Expr::MLV_Valid:
7213 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007214 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007215 case Expr::MLV_MemberFunction:
7216 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007217 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7218 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007219 case Expr::MLV_IncompleteType:
7220 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007221 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007222 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00007223 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00007224 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007225 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7226 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00007227 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007228 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7229 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007230 case Expr::MLV_ReadonlyProperty:
7231 Diag = diag::error_readonly_property_assignment;
7232 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007233 case Expr::MLV_NoSetterProperty:
7234 Diag = diag::error_nosetter_property_assignment;
7235 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007236 case Expr::MLV_SubObjCPropertySetting:
7237 Diag = diag::error_no_subobject_property_setting;
7238 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007239 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007240
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007241 SourceRange Assign;
7242 if (Loc != OrigLoc)
7243 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007244 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007245 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007246 else
Mike Stump1eb44332009-09-09 15:08:12 +00007247 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007248 return true;
7249}
7250
7251
7252
7253// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007254QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
7255 SourceLocation Loc,
7256 QualType CompoundType) {
7257 // Verify that LHS is a modifiable lvalue, and emit error if not.
7258 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007259 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007260
7261 QualType LHSType = LHS->getType();
7262 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007263 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007264 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007265 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007266 // Simple assignment "x = y".
John McCallf6a16482010-12-04 03:47:34 +00007267 if (LHS->getObjectKind() == OK_ObjCProperty)
7268 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007269 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007270 // Special case of NSObject attributes on c-style pointer types.
7271 if (ConvTy == IncompatiblePointer &&
7272 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007273 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007274 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007275 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007276 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007277
John McCallf89e55a2010-11-18 06:31:45 +00007278 if (ConvTy == Compatible &&
7279 getLangOptions().ObjCNonFragileABI &&
7280 LHSType->isObjCObjectType())
7281 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7282 << LHSType;
7283
Chris Lattner2c156472008-08-21 18:04:13 +00007284 // If the RHS is a unary plus or minus, check to see if they = and + are
7285 // right next to each other. If so, the user may have typo'd "x =+ 4"
7286 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007287 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00007288 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7289 RHSCheck = ICE->getSubExpr();
7290 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007291 if ((UO->getOpcode() == UO_Plus ||
7292 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007293 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007294 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00007295 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7296 // And there is a space or other character before the subexpr of the
7297 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00007298 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7299 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007300 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007301 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007302 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007303 }
Chris Lattner2c156472008-08-21 18:04:13 +00007304 }
7305 } else {
7306 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007307 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007308 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007309
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007310 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00007311 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007312 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007313
Chris Lattner8b5dec32010-07-07 06:14:23 +00007314
7315 // Check to see if the destination operand is a dereferenced null pointer. If
7316 // so, and if not volatile-qualified, this is undefined behavior that the
7317 // optimizer will delete, so warn about it. People sometimes try to use this
7318 // to get a deterministic trap and are surprised by clang's behavior. This
7319 // only handles the pattern "*null = whatever", which is a very syntactic
7320 // check.
7321 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCall2de56d12010-08-25 11:45:40 +00007322 if (UO->getOpcode() == UO_Deref &&
Chris Lattner8b5dec32010-07-07 06:14:23 +00007323 UO->getSubExpr()->IgnoreParenCasts()->
7324 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7325 !UO->getType().isVolatileQualified()) {
7326 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
7327 << UO->getSubExpr()->getSourceRange();
7328 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
7329 }
7330
Ted Kremeneka0125d82011-02-16 01:57:07 +00007331 // Check for trivial buffer overflows.
7332 if (const ArraySubscriptExpr *ae
7333 = dyn_cast<ArraySubscriptExpr>(LHS->IgnoreParenCasts()))
7334 CheckArrayAccess(ae);
7335
Reid Spencer5f016e22007-07-11 17:01:13 +00007336 // C99 6.5.16p3: The type of an assignment expression is the type of the
7337 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007338 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007339 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7340 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007341 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007342 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00007343 return (getLangOptions().CPlusPlus
7344 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007345}
7346
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007347// C99 6.5.17
John McCallf6a16482010-12-04 03:47:34 +00007348static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall09431682010-11-18 19:01:18 +00007349 SourceLocation Loc) {
7350 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00007351
John McCall09431682010-11-18 19:01:18 +00007352 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007353 if (LHSResult.isInvalid())
7354 return QualType();
7355
John McCall09431682010-11-18 19:01:18 +00007356 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007357 if (RHSResult.isInvalid())
7358 return QualType();
7359 RHS = RHSResult.take();
7360
John McCallcf2e5062010-10-12 07:14:40 +00007361 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7362 // operands, but not unary promotions.
7363 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007364
John McCallf6a16482010-12-04 03:47:34 +00007365 // So we treat the LHS as a ignored value, and in C++ we allow the
7366 // containing site to determine what should be done with the RHS.
7367 S.IgnoredValueConversions(LHS);
7368
7369 if (!S.getLangOptions().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007370 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCallcf2e5062010-10-12 07:14:40 +00007371 if (!RHS->getType()->isVoidType())
John McCall09431682010-11-18 19:01:18 +00007372 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007373 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007374
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007375 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007376}
7377
Steve Naroff49b45262007-07-13 16:58:59 +00007378/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7379/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007380static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7381 ExprValueKind &VK,
7382 SourceLocation OpLoc,
7383 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007384 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007385 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007386
Chris Lattner3528d352008-11-21 07:05:48 +00007387 QualType ResType = Op->getType();
7388 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007389
John McCall09431682010-11-18 19:01:18 +00007390 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007391 // Decrement of bool is not allowed.
7392 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00007393 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007394 return QualType();
7395 }
7396 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007397 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007398 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007399 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007400 } else if (ResType->isAnyPointerType()) {
7401 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00007402
Chris Lattner3528d352008-11-21 07:05:48 +00007403 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00007404 if (PointeeTy->isVoidType()) {
John McCall09431682010-11-18 19:01:18 +00007405 if (S.getLangOptions().CPlusPlus) {
7406 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00007407 << Op->getSourceRange();
7408 return QualType();
7409 }
7410
7411 // Pointer to void is a GNU extension in C.
John McCall09431682010-11-18 19:01:18 +00007412 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00007413 } else if (PointeeTy->isFunctionType()) {
John McCall09431682010-11-18 19:01:18 +00007414 if (S.getLangOptions().CPlusPlus) {
7415 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00007416 << Op->getType() << Op->getSourceRange();
7417 return QualType();
7418 }
7419
John McCall09431682010-11-18 19:01:18 +00007420 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00007421 << ResType << Op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007422 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7423 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00007424 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00007425 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007426 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007427 // Diagnose bad cases where we step over interface counts.
John McCall09431682010-11-18 19:01:18 +00007428 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7429 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007430 << PointeeTy << Op->getSourceRange();
7431 return QualType();
7432 }
Eli Friedman5b088a12010-01-03 00:20:48 +00007433 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007434 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007435 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007436 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007437 } else if (ResType->isPlaceholderType()) {
John McCall09431682010-11-18 19:01:18 +00007438 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007439 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007440 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7441 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00007442 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7443 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007444 } else {
John McCall09431682010-11-18 19:01:18 +00007445 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00007446 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007447 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007448 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007449 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007450 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007451 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007452 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007453 // In C++, a prefix increment is the same type as the operand. Otherwise
7454 // (in C or with postfix), the increment is the unqualified type of the
7455 // operand.
John McCall09431682010-11-18 19:01:18 +00007456 if (isPrefix && S.getLangOptions().CPlusPlus) {
7457 VK = VK_LValue;
7458 return ResType;
7459 } else {
7460 VK = VK_RValue;
7461 return ResType.getUnqualifiedType();
7462 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007463}
7464
John McCallf6a16482010-12-04 03:47:34 +00007465void Sema::ConvertPropertyForRValue(Expr *&E) {
7466 assert(E->getValueKind() == VK_LValue &&
7467 E->getObjectKind() == OK_ObjCProperty);
7468 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7469
7470 ExprValueKind VK = VK_RValue;
7471 if (PRE->isImplicitProperty()) {
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007472 if (const ObjCMethodDecl *GetterMethod =
7473 PRE->getImplicitPropertyGetter()) {
7474 QualType Result = GetterMethod->getResultType();
7475 VK = Expr::getValueKindForType(Result);
7476 }
7477 else {
7478 Diag(PRE->getLocation(), diag::err_getter_not_found)
7479 << PRE->getBase()->getType();
7480 }
John McCallf6a16482010-12-04 03:47:34 +00007481 }
7482
7483 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7484 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00007485
7486 ExprResult Result = MaybeBindToTemporary(E);
7487 if (!Result.isInvalid())
7488 E = Result.take();
John McCallf6a16482010-12-04 03:47:34 +00007489}
7490
7491void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7492 assert(LHS->getValueKind() == VK_LValue &&
7493 LHS->getObjectKind() == OK_ObjCProperty);
7494 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7495
7496 if (PRE->isImplicitProperty()) {
7497 // If using property-dot syntax notation for assignment, and there is a
7498 // setter, RHS expression is being passed to the setter argument. So,
7499 // type conversion (and comparison) is RHS to setter's argument type.
7500 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7501 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7502 LHSTy = (*P)->getType();
7503
7504 // Otherwise, if the getter returns an l-value, just call that.
7505 } else {
7506 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7507 ExprValueKind VK = Expr::getValueKindForType(Result);
7508 if (VK == VK_LValue) {
7509 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7510 CK_GetObjCProperty, LHS, 0, VK);
7511 return;
John McCall12f78a62010-12-02 01:19:52 +00007512 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007513 }
John McCallf6a16482010-12-04 03:47:34 +00007514 }
7515
7516 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007517 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007518 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007519 Expr *Arg = RHS;
7520 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7521 Owned(Arg));
7522 if (!ArgE.isInvalid())
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007523 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007524 }
7525}
7526
7527
Anders Carlsson369dee42008-02-01 07:15:58 +00007528/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007529/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007530/// where the declaration is needed for type checking. We only need to
7531/// handle cases when the expression references a function designator
7532/// or is an lvalue. Here are some examples:
7533/// - &(x) => x
7534/// - &*****f => f for f a function designator.
7535/// - &s.xx => s
7536/// - &s.zz[1].yy -> s, if zz is an array
7537/// - *(x + 1) -> x, if x is an array
7538/// - &"123"[2] -> 0
7539/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007540static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007541 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007542 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007543 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007544 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007545 // If this is an arrow operator, the address is an offset from
7546 // the base's value, so the object the base refers to is
7547 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007548 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007549 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007550 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007551 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007552 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007553 // FIXME: This code shouldn't be necessary! We should catch the implicit
7554 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007555 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7556 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7557 if (ICE->getSubExpr()->getType()->isArrayType())
7558 return getPrimaryDecl(ICE->getSubExpr());
7559 }
7560 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007561 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007562 case Stmt::UnaryOperatorClass: {
7563 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007564
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007565 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007566 case UO_Real:
7567 case UO_Imag:
7568 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007569 return getPrimaryDecl(UO->getSubExpr());
7570 default:
7571 return 0;
7572 }
7573 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007574 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007575 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007576 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007577 // If the result of an implicit cast is an l-value, we care about
7578 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007579 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007580 default:
7581 return 0;
7582 }
7583}
7584
7585/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007586/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007587/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007588/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007589/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007590/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007591/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00007592static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7593 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00007594 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007595 return S.Context.DependentTy;
7596 if (OrigOp->getType() == S.Context.OverloadTy)
7597 return S.Context.OverloadTy;
John McCall9c72c602010-08-27 09:08:28 +00007598
John McCall09431682010-11-18 19:01:18 +00007599 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007600 if (PR.isInvalid()) return QualType();
7601 OrigOp = PR.take();
7602
John McCall9c72c602010-08-27 09:08:28 +00007603 // Make sure to ignore parentheses in subsequent checks
7604 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007605
John McCall09431682010-11-18 19:01:18 +00007606 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007607 // Implement C99-only parts of addressof rules.
7608 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007609 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007610 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7611 // (assuming the deref expression is valid).
7612 return uOp->getSubExpr()->getType();
7613 }
7614 // Technically, there should be a check for array subscript
7615 // expressions here, but the result of one is always an lvalue anyway.
7616 }
John McCall5808ce42011-02-03 08:15:49 +00007617 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007618 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007619
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007620 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007621 bool sfinae = S.isSFINAEContext();
7622 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7623 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007624 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007625 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007626 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007627 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007628 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007629 } else if (lval == Expr::LV_MemberFunction) {
7630 // If it's an instance method, make a member pointer.
7631 // The expression must have exactly the form &A::foo.
7632
7633 // If the underlying expression isn't a decl ref, give up.
7634 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007635 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007636 << OrigOp->getSourceRange();
7637 return QualType();
7638 }
7639 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7640 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7641
7642 // The id-expression was parenthesized.
7643 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00007644 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007645 << OrigOp->getSourceRange();
7646
7647 // The method was named without a qualifier.
7648 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007649 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007650 << op->getSourceRange();
7651 }
7652
John McCall09431682010-11-18 19:01:18 +00007653 return S.Context.getMemberPointerType(op->getType(),
7654 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007655 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007656 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007657 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007658 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00007659 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00007660 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00007661 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007662 return QualType();
7663 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007664 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007665 // The operand cannot be a bit-field
John McCall09431682010-11-18 19:01:18 +00007666 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman23d58ce2009-04-20 08:23:18 +00007667 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00007668 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007669 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007670 // The operand cannot be an element of a vector
John McCall09431682010-11-18 19:01:18 +00007671 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00007672 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007673 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007674 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007675 // cannot take address of a property expression.
John McCall09431682010-11-18 19:01:18 +00007676 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007677 << "property expression" << op->getSourceRange();
7678 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007679 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007680 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007681 // with the register storage-class specifier.
7682 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007683 // in C++ it is not error to take address of a register
7684 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007685 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007686 !S.getLangOptions().CPlusPlus) {
7687 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007688 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007689 return QualType();
7690 }
John McCallba135432009-11-21 08:51:07 +00007691 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007692 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007693 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007694 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007695 // Could be a pointer to member, though, if there is an explicit
7696 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007697 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007698 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007699 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007700 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007701 S.Diag(OpLoc,
7702 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007703 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007704 return QualType();
7705 }
Mike Stump1eb44332009-09-09 15:08:12 +00007706
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007707 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7708 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007709 return S.Context.getMemberPointerType(op->getType(),
7710 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007711 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007712 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00007713 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00007714 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007715 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007716
Eli Friedman441cf102009-05-16 23:27:50 +00007717 if (lval == Expr::LV_IncompleteVoidType) {
7718 // Taking the address of a void variable is technically illegal, but we
7719 // allow it in cases which are otherwise valid.
7720 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007721 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007722 }
7723
Reid Spencer5f016e22007-07-11 17:01:13 +00007724 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007725 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007726 return S.Context.getObjCObjectPointerType(op->getType());
7727 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007728}
7729
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007730/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007731static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7732 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007733 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007734 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007735
John McCall09431682010-11-18 19:01:18 +00007736 S.UsualUnaryConversions(Op);
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007737 QualType OpTy = Op->getType();
7738 QualType Result;
7739
7740 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7741 // is an incomplete type or void. It would be possible to warn about
7742 // dereferencing a void pointer, but it's completely well-defined, and such a
7743 // warning is unlikely to catch any mistakes.
7744 if (const PointerType *PT = OpTy->getAs<PointerType>())
7745 Result = PT->getPointeeType();
7746 else if (const ObjCObjectPointerType *OPT =
7747 OpTy->getAs<ObjCObjectPointerType>())
7748 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007749 else {
John McCall09431682010-11-18 19:01:18 +00007750 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007751 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007752 if (PR.take() != Op)
7753 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007754 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007755
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007756 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007757 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007758 << OpTy << Op->getSourceRange();
7759 return QualType();
7760 }
John McCall09431682010-11-18 19:01:18 +00007761
7762 // Dereferences are usually l-values...
7763 VK = VK_LValue;
7764
7765 // ...except that certain expressions are never l-values in C.
7766 if (!S.getLangOptions().CPlusPlus &&
7767 IsCForbiddenLValueType(S.Context, Result))
7768 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007769
7770 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007771}
7772
John McCall2de56d12010-08-25 11:45:40 +00007773static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007774 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007775 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007776 switch (Kind) {
7777 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007778 case tok::periodstar: Opc = BO_PtrMemD; break;
7779 case tok::arrowstar: Opc = BO_PtrMemI; break;
7780 case tok::star: Opc = BO_Mul; break;
7781 case tok::slash: Opc = BO_Div; break;
7782 case tok::percent: Opc = BO_Rem; break;
7783 case tok::plus: Opc = BO_Add; break;
7784 case tok::minus: Opc = BO_Sub; break;
7785 case tok::lessless: Opc = BO_Shl; break;
7786 case tok::greatergreater: Opc = BO_Shr; break;
7787 case tok::lessequal: Opc = BO_LE; break;
7788 case tok::less: Opc = BO_LT; break;
7789 case tok::greaterequal: Opc = BO_GE; break;
7790 case tok::greater: Opc = BO_GT; break;
7791 case tok::exclaimequal: Opc = BO_NE; break;
7792 case tok::equalequal: Opc = BO_EQ; break;
7793 case tok::amp: Opc = BO_And; break;
7794 case tok::caret: Opc = BO_Xor; break;
7795 case tok::pipe: Opc = BO_Or; break;
7796 case tok::ampamp: Opc = BO_LAnd; break;
7797 case tok::pipepipe: Opc = BO_LOr; break;
7798 case tok::equal: Opc = BO_Assign; break;
7799 case tok::starequal: Opc = BO_MulAssign; break;
7800 case tok::slashequal: Opc = BO_DivAssign; break;
7801 case tok::percentequal: Opc = BO_RemAssign; break;
7802 case tok::plusequal: Opc = BO_AddAssign; break;
7803 case tok::minusequal: Opc = BO_SubAssign; break;
7804 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7805 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7806 case tok::ampequal: Opc = BO_AndAssign; break;
7807 case tok::caretequal: Opc = BO_XorAssign; break;
7808 case tok::pipeequal: Opc = BO_OrAssign; break;
7809 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007810 }
7811 return Opc;
7812}
7813
John McCall2de56d12010-08-25 11:45:40 +00007814static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007815 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007816 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007817 switch (Kind) {
7818 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007819 case tok::plusplus: Opc = UO_PreInc; break;
7820 case tok::minusminus: Opc = UO_PreDec; break;
7821 case tok::amp: Opc = UO_AddrOf; break;
7822 case tok::star: Opc = UO_Deref; break;
7823 case tok::plus: Opc = UO_Plus; break;
7824 case tok::minus: Opc = UO_Minus; break;
7825 case tok::tilde: Opc = UO_Not; break;
7826 case tok::exclaim: Opc = UO_LNot; break;
7827 case tok::kw___real: Opc = UO_Real; break;
7828 case tok::kw___imag: Opc = UO_Imag; break;
7829 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007830 }
7831 return Opc;
7832}
7833
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007834/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7835/// This warning is only emitted for builtin assignment operations. It is also
7836/// suppressed in the event of macro expansions.
7837static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7838 SourceLocation OpLoc) {
7839 if (!S.ActiveTemplateInstantiations.empty())
7840 return;
7841 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7842 return;
7843 lhs = lhs->IgnoreParenImpCasts();
7844 rhs = rhs->IgnoreParenImpCasts();
7845 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7846 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7847 if (!LeftDeclRef || !RightDeclRef ||
7848 LeftDeclRef->getLocation().isMacroID() ||
7849 RightDeclRef->getLocation().isMacroID())
7850 return;
7851 const ValueDecl *LeftDecl =
7852 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7853 const ValueDecl *RightDecl =
7854 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7855 if (LeftDecl != RightDecl)
7856 return;
7857 if (LeftDecl->getType().isVolatileQualified())
7858 return;
7859 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7860 if (RefTy->getPointeeType().isVolatileQualified())
7861 return;
7862
7863 S.Diag(OpLoc, diag::warn_self_assignment)
7864 << LeftDeclRef->getType()
7865 << lhs->getSourceRange() << rhs->getSourceRange();
7866}
7867
Douglas Gregoreaebc752008-11-06 23:29:22 +00007868/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7869/// operator @p Opc at location @c TokLoc. This routine only supports
7870/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00007871ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007872 BinaryOperatorKind Opc,
John McCall2de56d12010-08-25 11:45:40 +00007873 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00007874 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00007875 // The following two variables are used for compound assignment operators
7876 QualType CompLHSTy; // Type of LHS after promotions for computation
7877 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00007878 ExprValueKind VK = VK_RValue;
7879 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00007880
7881 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007882 case BO_Assign:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007883 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00007884 if (getLangOptions().CPlusPlus &&
7885 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall09431682010-11-18 19:01:18 +00007886 VK = lhs->getValueKind();
7887 OK = lhs->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007888 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007889 if (!ResultTy.isNull())
7890 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007891 break;
John McCall2de56d12010-08-25 11:45:40 +00007892 case BO_PtrMemD:
7893 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00007894 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007895 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00007896 break;
John McCall2de56d12010-08-25 11:45:40 +00007897 case BO_Mul:
7898 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007899 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00007900 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007901 break;
John McCall2de56d12010-08-25 11:45:40 +00007902 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007903 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7904 break;
John McCall2de56d12010-08-25 11:45:40 +00007905 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007906 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7907 break;
John McCall2de56d12010-08-25 11:45:40 +00007908 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007909 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7910 break;
John McCall2de56d12010-08-25 11:45:40 +00007911 case BO_Shl:
7912 case BO_Shr:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007913 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
7914 break;
John McCall2de56d12010-08-25 11:45:40 +00007915 case BO_LE:
7916 case BO_LT:
7917 case BO_GE:
7918 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00007919 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007920 break;
John McCall2de56d12010-08-25 11:45:40 +00007921 case BO_EQ:
7922 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00007923 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007924 break;
John McCall2de56d12010-08-25 11:45:40 +00007925 case BO_And:
7926 case BO_Xor:
7927 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007928 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7929 break;
John McCall2de56d12010-08-25 11:45:40 +00007930 case BO_LAnd:
7931 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00007932 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007933 break;
John McCall2de56d12010-08-25 11:45:40 +00007934 case BO_MulAssign:
7935 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007936 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00007937 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007938 CompLHSTy = CompResultTy;
7939 if (!CompResultTy.isNull())
7940 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007941 break;
John McCall2de56d12010-08-25 11:45:40 +00007942 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007943 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7944 CompLHSTy = CompResultTy;
7945 if (!CompResultTy.isNull())
7946 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007947 break;
John McCall2de56d12010-08-25 11:45:40 +00007948 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007949 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7950 if (!CompResultTy.isNull())
7951 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007952 break;
John McCall2de56d12010-08-25 11:45:40 +00007953 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007954 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7955 if (!CompResultTy.isNull())
7956 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007957 break;
John McCall2de56d12010-08-25 11:45:40 +00007958 case BO_ShlAssign:
7959 case BO_ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007960 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
7961 CompLHSTy = CompResultTy;
7962 if (!CompResultTy.isNull())
7963 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007964 break;
John McCall2de56d12010-08-25 11:45:40 +00007965 case BO_AndAssign:
7966 case BO_XorAssign:
7967 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007968 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7969 CompLHSTy = CompResultTy;
7970 if (!CompResultTy.isNull())
7971 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007972 break;
John McCall2de56d12010-08-25 11:45:40 +00007973 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00007974 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCallf89e55a2010-11-18 06:31:45 +00007975 if (getLangOptions().CPlusPlus) {
7976 VK = rhs->getValueKind();
7977 OK = rhs->getObjectKind();
7978 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00007979 break;
7980 }
7981 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007982 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00007983 if (CompResultTy.isNull())
John McCallf89e55a2010-11-18 06:31:45 +00007984 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
7985 VK, OK, OpLoc));
7986
John McCallf6a16482010-12-04 03:47:34 +00007987 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00007988 VK = VK_LValue;
7989 OK = lhs->getObjectKind();
7990 }
7991 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
7992 VK, OK, CompLHSTy,
7993 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00007994}
7995
Sebastian Redlaee3c932009-10-27 12:10:02 +00007996/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
7997/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007998static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7999 const PartialDiagnostic &PD,
Douglas Gregor55b38842010-04-14 16:09:52 +00008000 const PartialDiagnostic &FirstNote,
8001 SourceRange FirstParenRange,
8002 const PartialDiagnostic &SecondNote,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008003 SourceRange SecondParenRange) {
Douglas Gregor55b38842010-04-14 16:09:52 +00008004 Self.Diag(Loc, PD);
8005
8006 if (!FirstNote.getDiagID())
8007 return;
8008
8009 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8010 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8011 // We can't display the parentheses, so just return.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008012 return;
8013 }
8014
Douglas Gregor55b38842010-04-14 16:09:52 +00008015 Self.Diag(Loc, FirstNote)
8016 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregor849b2432010-03-31 17:46:05 +00008017 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008018
Douglas Gregor55b38842010-04-14 16:09:52 +00008019 if (!SecondNote.getDiagID())
Douglas Gregor827feec2010-01-08 00:20:23 +00008020 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008021
Douglas Gregor827feec2010-01-08 00:20:23 +00008022 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8023 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8024 // We can't display the parentheses, so just dig the
8025 // warning/error and return.
Douglas Gregor55b38842010-04-14 16:09:52 +00008026 Self.Diag(Loc, SecondNote);
Douglas Gregor827feec2010-01-08 00:20:23 +00008027 return;
8028 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008029
Douglas Gregor55b38842010-04-14 16:09:52 +00008030 Self.Diag(Loc, SecondNote)
Douglas Gregor849b2432010-03-31 17:46:05 +00008031 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8032 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008033}
8034
Sebastian Redlaee3c932009-10-27 12:10:02 +00008035/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8036/// operators are mixed in a way that suggests that the programmer forgot that
8037/// comparison operators have higher precedence. The most typical example of
8038/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008039static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008040 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00008041 typedef BinaryOperator BinOp;
8042 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8043 rhsopc = static_cast<BinOp::Opcode>(-1);
8044 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008045 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00008046 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008047 rhsopc = BO->getOpcode();
8048
8049 // Subs are not binary operators.
8050 if (lhsopc == -1 && rhsopc == -1)
8051 return;
8052
8053 // Bitwise operations are sometimes used as eager logical ops.
8054 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00008055 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8056 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008057 return;
8058
Sebastian Redlaee3c932009-10-27 12:10:02 +00008059 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008060 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008061 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00008062 << SourceRange(lhs->getLocStart(), OpLoc)
8063 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008064 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00008065 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00008066 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
8067 Self.PDiag(diag::note_precedence_bitwise_silence)
8068 << BinOp::getOpcodeStr(lhsopc),
8069 lhs->getSourceRange());
Sebastian Redlaee3c932009-10-27 12:10:02 +00008070 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008071 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008072 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00008073 << SourceRange(OpLoc, rhs->getLocEnd())
8074 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008075 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00008076 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00008077 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
8078 Self.PDiag(diag::note_precedence_bitwise_silence)
8079 << BinOp::getOpcodeStr(rhsopc),
8080 rhs->getSourceRange());
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008081}
8082
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008083/// \brief It accepts a '&&' expr that is inside a '||' one.
8084/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8085/// in parentheses.
8086static void
8087EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8088 Expr *E) {
8089 assert(isa<BinaryOperator>(E) &&
8090 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
8091 SuggestParentheses(Self, OpLoc,
8092 Self.PDiag(diag::warn_logical_and_in_logical_or)
8093 << E->getSourceRange(),
8094 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8095 E->getSourceRange(),
8096 Self.PDiag(0), SourceRange());
8097}
8098
8099/// \brief Returns true if the given expression can be evaluated as a constant
8100/// 'true'.
8101static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8102 bool Res;
8103 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8104}
8105
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008106/// \brief Returns true if the given expression can be evaluated as a constant
8107/// 'false'.
8108static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8109 bool Res;
8110 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8111}
8112
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008113/// \brief Look for '&&' in the left hand of a '||' expr.
8114static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008115 Expr *OrLHS, Expr *OrRHS) {
8116 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008117 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008118 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8119 if (EvaluatesAsFalse(S, OrRHS))
8120 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008121 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8122 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8123 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8124 } else if (Bop->getOpcode() == BO_LOr) {
8125 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8126 // If it's "a || b && 1 || c" we didn't warn earlier for
8127 // "a || b && 1", but warn now.
8128 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8129 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8130 }
8131 }
8132 }
8133}
8134
8135/// \brief Look for '&&' in the right hand of a '||' expr.
8136static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008137 Expr *OrLHS, Expr *OrRHS) {
8138 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008139 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008140 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8141 if (EvaluatesAsFalse(S, OrLHS))
8142 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008143 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8144 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8145 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008146 }
8147 }
8148}
8149
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008150/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008151/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008152static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008153 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008154 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008155 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008156 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8157
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008158 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8159 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008160 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008161 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8162 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008163 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008164}
8165
Reid Spencer5f016e22007-07-11 17:01:13 +00008166// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008167ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008168 tok::TokenKind Kind,
8169 Expr *lhs, Expr *rhs) {
8170 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00008171 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8172 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008173
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008174 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8175 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8176
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008177 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8178}
8179
John McCall60d7b3a2010-08-24 06:29:42 +00008180ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008181 BinaryOperatorKind Opc,
8182 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00008183 if (getLangOptions().CPlusPlus) {
8184 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008185
John McCall01b2e4e2010-12-06 05:26:58 +00008186 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8187 UseBuiltinOperator = false;
8188 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8189 UseBuiltinOperator = true;
8190 } else {
8191 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8192 !rhs->getType()->isOverloadableType();
8193 }
8194
8195 if (!UseBuiltinOperator) {
8196 // Find all of the overloaded operators visible from this
8197 // point. We perform both an operator-name lookup from the local
8198 // scope and an argument-dependent lookup based on the types of
8199 // the arguments.
8200 UnresolvedSet<16> Functions;
8201 OverloadedOperatorKind OverOp
8202 = BinaryOperator::getOverloadedOperator(Opc);
8203 if (S && OverOp != OO_None)
8204 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8205 Functions);
8206
8207 // Build the (potentially-overloaded, potentially-dependent)
8208 // binary operation.
8209 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8210 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008211 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008212
Douglas Gregoreaebc752008-11-06 23:29:22 +00008213 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008214 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00008215}
8216
John McCall60d7b3a2010-08-24 06:29:42 +00008217ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008218 UnaryOperatorKind Opc,
John McCall2cd11fe2010-10-12 02:09:17 +00008219 Expr *Input) {
John McCallf89e55a2010-11-18 06:31:45 +00008220 ExprValueKind VK = VK_RValue;
8221 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008222 QualType resultType;
8223 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008224 case UO_PreInc:
8225 case UO_PreDec:
8226 case UO_PostInc:
8227 case UO_PostDec:
John McCall09431682010-11-18 19:01:18 +00008228 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008229 Opc == UO_PreInc ||
8230 Opc == UO_PostInc,
8231 Opc == UO_PreInc ||
8232 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008233 break;
John McCall2de56d12010-08-25 11:45:40 +00008234 case UO_AddrOf:
John McCall09431682010-11-18 19:01:18 +00008235 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008236 break;
John McCall2de56d12010-08-25 11:45:40 +00008237 case UO_Deref:
Douglas Gregora873dfc2010-02-03 00:27:59 +00008238 DefaultFunctionArrayLvalueConversion(Input);
John McCall09431682010-11-18 19:01:18 +00008239 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008240 break;
John McCall2de56d12010-08-25 11:45:40 +00008241 case UO_Plus:
8242 case UO_Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00008243 UsualUnaryConversions(Input);
8244 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008245 if (resultType->isDependentType())
8246 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008247 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8248 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008249 break;
8250 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8251 resultType->isEnumeralType())
8252 break;
8253 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008254 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008255 resultType->isPointerType())
8256 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008257 else if (resultType->isPlaceholderType()) {
8258 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8259 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008260 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008261 }
Douglas Gregor74253732008-11-19 15:42:04 +00008262
Sebastian Redl0eb23302009-01-19 00:08:26 +00008263 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8264 << resultType << Input->getSourceRange());
John McCall2de56d12010-08-25 11:45:40 +00008265 case UO_Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00008266 UsualUnaryConversions(Input);
8267 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008268 if (resultType->isDependentType())
8269 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008270 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8271 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8272 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008273 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00008274 << resultType << Input->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008275 else if (resultType->hasIntegerRepresentation())
8276 break;
8277 else if (resultType->isPlaceholderType()) {
8278 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8279 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008280 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008281 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008282 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8283 << resultType << Input->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008284 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008285 break;
John McCall2de56d12010-08-25 11:45:40 +00008286 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008287 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregora873dfc2010-02-03 00:27:59 +00008288 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00008289 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008290 if (resultType->isDependentType())
8291 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008292 if (resultType->isScalarType()) { // C99 6.5.3.3p1
8293 // ok, fallthrough
8294 } else if (resultType->isPlaceholderType()) {
8295 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8296 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008297 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008298 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008299 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8300 << resultType << Input->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008301 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008302
Reid Spencer5f016e22007-07-11 17:01:13 +00008303 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008304 // In C++, it's bool. C++ 5.3.1p8
8305 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00008306 break;
John McCall2de56d12010-08-25 11:45:40 +00008307 case UO_Real:
8308 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008309 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008310 // _Real and _Imag map ordinary l-values into ordinary l-values.
8311 if (Input->getValueKind() != VK_RValue &&
8312 Input->getObjectKind() == OK_Ordinary)
8313 VK = Input->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00008314 break;
John McCall2de56d12010-08-25 11:45:40 +00008315 case UO_Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00008316 resultType = Input->getType();
John McCallf89e55a2010-11-18 06:31:45 +00008317 VK = Input->getValueKind();
8318 OK = Input->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008319 break;
8320 }
8321 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008322 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008323
John McCallf89e55a2010-11-18 06:31:45 +00008324 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
8325 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008326}
8327
John McCall60d7b3a2010-08-24 06:29:42 +00008328ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008329 UnaryOperatorKind Opc,
8330 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00008331 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00008332 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008333 // Find all of the overloaded operators visible from this
8334 // point. We perform both an operator-name lookup from the local
8335 // scope and an argument-dependent lookup based on the types of
8336 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008337 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008338 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008339 if (S && OverOp != OO_None)
8340 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8341 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008342
John McCall9ae2f072010-08-23 23:25:46 +00008343 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008344 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008345
John McCall9ae2f072010-08-23 23:25:46 +00008346 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008347}
8348
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008349// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008350ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008351 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008352 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008353}
8354
Steve Naroff1b273c42007-09-16 14:56:35 +00008355/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008356ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
8357 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00008358 // Look up the record for this label identifier.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008359 LabelDecl *&TheDecl = getCurFunction()->LabelMap[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00008360
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00008361 // If we haven't seen this label yet, create a forward reference. It
8362 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008363 if (TheDecl == 0)
8364 TheDecl = LabelDecl::Create(Context, CurContext, LabLoc, LabelII);
Chris Lattner57ad3782011-02-17 20:34:02 +00008365 return ActOnAddrLabel(OpLoc, LabLoc, TheDecl);
8366}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008367
Chris Lattner57ad3782011-02-17 20:34:02 +00008368ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
8369 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008370 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008371 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008372 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008373 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008374}
8375
John McCall60d7b3a2010-08-24 06:29:42 +00008376ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008377Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008378 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008379 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8380 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8381
Douglas Gregordd8f5692010-03-10 04:54:39 +00008382 bool isFileScope
8383 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008384 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008385 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008386
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008387 // FIXME: there are a variety of strange constraints to enforce here, for
8388 // example, it is not possible to goto into a stmt expression apparently.
8389 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008390
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008391 // If there are sub stmts in the compound stmt, take the type of the last one
8392 // as the type of the stmtexpr.
8393 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008394 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008395 if (!Compound->body_empty()) {
8396 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008397 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008398 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008399 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8400 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008401 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008402 }
8403 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008404 // Do function/array conversion on the last expression, but not
8405 // lvalue-to-rvalue. However, initialize an unqualified type.
8406 DefaultFunctionArrayConversion(LastExpr);
8407 Ty = LastExpr->getType().getUnqualifiedType();
8408
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008409 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8410 ExprResult Res = PerformCopyInitialization(
8411 InitializedEntity::InitializeResult(LPLoc,
8412 Ty,
8413 false),
8414 SourceLocation(),
8415 Owned(LastExpr));
8416 if (Res.isInvalid())
8417 return ExprError();
8418 if ((LastExpr = Res.takeAs<Expr>())) {
8419 if (!LastLabelStmt)
8420 Compound->setLastStmt(LastExpr);
8421 else
8422 LastLabelStmt->setSubStmt(LastExpr);
8423 StmtExprMayBindToTemp = true;
8424 }
8425 }
8426 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008427 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008428
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008429 // FIXME: Check that expression type is complete/non-abstract; statement
8430 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008431 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8432 if (StmtExprMayBindToTemp)
8433 return MaybeBindToTemporary(ResStmtExpr);
8434 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008435}
Steve Naroffd34e9152007-08-01 22:05:33 +00008436
John McCall60d7b3a2010-08-24 06:29:42 +00008437ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008438 TypeSourceInfo *TInfo,
8439 OffsetOfComponent *CompPtr,
8440 unsigned NumComponents,
8441 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008442 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008443 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008444 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008445
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008446 // We must have at least one component that refers to the type, and the first
8447 // one is known to be a field designator. Verify that the ArgTy represents
8448 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008449 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008450 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8451 << ArgTy << TypeRange);
8452
8453 // Type must be complete per C99 7.17p3 because a declaring a variable
8454 // with an incomplete type would be ill-formed.
8455 if (!Dependent
8456 && RequireCompleteType(BuiltinLoc, ArgTy,
8457 PDiag(diag::err_offsetof_incomplete_type)
8458 << TypeRange))
8459 return ExprError();
8460
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008461 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8462 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008463 // FIXME: This diagnostic isn't actually visible because the location is in
8464 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008465 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008466 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8467 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008468
8469 bool DidWarnAboutNonPOD = false;
8470 QualType CurrentType = ArgTy;
8471 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8472 llvm::SmallVector<OffsetOfNode, 4> Comps;
8473 llvm::SmallVector<Expr*, 4> Exprs;
8474 for (unsigned i = 0; i != NumComponents; ++i) {
8475 const OffsetOfComponent &OC = CompPtr[i];
8476 if (OC.isBrackets) {
8477 // Offset of an array sub-field. TODO: Should we allow vector elements?
8478 if (!CurrentType->isDependentType()) {
8479 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8480 if(!AT)
8481 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8482 << CurrentType);
8483 CurrentType = AT->getElementType();
8484 } else
8485 CurrentType = Context.DependentTy;
8486
8487 // The expression must be an integral expression.
8488 // FIXME: An integral constant expression?
8489 Expr *Idx = static_cast<Expr*>(OC.U.E);
8490 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8491 !Idx->getType()->isIntegerType())
8492 return ExprError(Diag(Idx->getLocStart(),
8493 diag::err_typecheck_subscript_not_integer)
8494 << Idx->getSourceRange());
8495
8496 // Record this array index.
8497 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8498 Exprs.push_back(Idx);
8499 continue;
8500 }
8501
8502 // Offset of a field.
8503 if (CurrentType->isDependentType()) {
8504 // We have the offset of a field, but we can't look into the dependent
8505 // type. Just record the identifier of the field.
8506 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8507 CurrentType = Context.DependentTy;
8508 continue;
8509 }
8510
8511 // We need to have a complete type to look into.
8512 if (RequireCompleteType(OC.LocStart, CurrentType,
8513 diag::err_offsetof_incomplete_type))
8514 return ExprError();
8515
8516 // Look for the designated field.
8517 const RecordType *RC = CurrentType->getAs<RecordType>();
8518 if (!RC)
8519 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8520 << CurrentType);
8521 RecordDecl *RD = RC->getDecl();
8522
8523 // C++ [lib.support.types]p5:
8524 // The macro offsetof accepts a restricted set of type arguments in this
8525 // International Standard. type shall be a POD structure or a POD union
8526 // (clause 9).
8527 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8528 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8529 DiagRuntimeBehavior(BuiltinLoc,
8530 PDiag(diag::warn_offsetof_non_pod_type)
8531 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8532 << CurrentType))
8533 DidWarnAboutNonPOD = true;
8534 }
8535
8536 // Look for the field.
8537 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8538 LookupQualifiedName(R, RD);
8539 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008540 IndirectFieldDecl *IndirectMemberDecl = 0;
8541 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008542 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008543 MemberDecl = IndirectMemberDecl->getAnonField();
8544 }
8545
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008546 if (!MemberDecl)
8547 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8548 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8549 OC.LocEnd));
8550
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008551 // C99 7.17p3:
8552 // (If the specified member is a bit-field, the behavior is undefined.)
8553 //
8554 // We diagnose this as an error.
8555 if (MemberDecl->getBitWidth()) {
8556 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8557 << MemberDecl->getDeclName()
8558 << SourceRange(BuiltinLoc, RParenLoc);
8559 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8560 return ExprError();
8561 }
Eli Friedman19410a72010-08-05 10:11:36 +00008562
8563 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008564 if (IndirectMemberDecl)
8565 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008566
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008567 // If the member was found in a base class, introduce OffsetOfNodes for
8568 // the base class indirections.
8569 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8570 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008571 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008572 CXXBasePath &Path = Paths.front();
8573 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8574 B != BEnd; ++B)
8575 Comps.push_back(OffsetOfNode(B->Base));
8576 }
Eli Friedman19410a72010-08-05 10:11:36 +00008577
Francois Pichet87c2e122010-11-21 06:08:52 +00008578 if (IndirectMemberDecl) {
8579 for (IndirectFieldDecl::chain_iterator FI =
8580 IndirectMemberDecl->chain_begin(),
8581 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8582 assert(isa<FieldDecl>(*FI));
8583 Comps.push_back(OffsetOfNode(OC.LocStart,
8584 cast<FieldDecl>(*FI), OC.LocEnd));
8585 }
8586 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008587 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008588
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008589 CurrentType = MemberDecl->getType().getNonReferenceType();
8590 }
8591
8592 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8593 TInfo, Comps.data(), Comps.size(),
8594 Exprs.data(), Exprs.size(), RParenLoc));
8595}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008596
John McCall60d7b3a2010-08-24 06:29:42 +00008597ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008598 SourceLocation BuiltinLoc,
8599 SourceLocation TypeLoc,
8600 ParsedType argty,
8601 OffsetOfComponent *CompPtr,
8602 unsigned NumComponents,
8603 SourceLocation RPLoc) {
8604
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008605 TypeSourceInfo *ArgTInfo;
8606 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8607 if (ArgTy.isNull())
8608 return ExprError();
8609
Eli Friedman5a15dc12010-08-05 10:15:45 +00008610 if (!ArgTInfo)
8611 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8612
8613 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8614 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008615}
8616
8617
John McCall60d7b3a2010-08-24 06:29:42 +00008618ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008619 Expr *CondExpr,
8620 Expr *LHSExpr, Expr *RHSExpr,
8621 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008622 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8623
John McCallf89e55a2010-11-18 06:31:45 +00008624 ExprValueKind VK = VK_RValue;
8625 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008626 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008627 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008628 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008629 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008630 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008631 } else {
8632 // The conditional expression is required to be a constant expression.
8633 llvm::APSInt condEval(32);
8634 SourceLocation ExpLoc;
8635 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008636 return ExprError(Diag(ExpLoc,
8637 diag::err_typecheck_choose_expr_requires_constant)
8638 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008639
Sebastian Redl28507842009-02-26 14:39:58 +00008640 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008641 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8642
8643 resType = ActiveExpr->getType();
8644 ValueDependent = ActiveExpr->isValueDependent();
8645 VK = ActiveExpr->getValueKind();
8646 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008647 }
8648
Sebastian Redlf53597f2009-03-15 17:47:39 +00008649 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008650 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008651 resType->isDependentType(),
8652 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008653}
8654
Steve Naroff4eb206b2008-09-03 18:15:37 +00008655//===----------------------------------------------------------------------===//
8656// Clang Extensions.
8657//===----------------------------------------------------------------------===//
8658
8659/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00008660void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008661 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8662 PushBlockScope(BlockScope, Block);
8663 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008664 if (BlockScope)
8665 PushDeclContext(BlockScope, Block);
8666 else
8667 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00008668}
8669
Mike Stump98eb8a72009-02-04 22:31:32 +00008670void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008671 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008672 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008673 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008674
John McCallbf1a0282010-06-04 23:28:52 +00008675 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008676 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008677
John McCall711c52b2011-01-05 12:14:39 +00008678 // GetTypeForDeclarator always produces a function type for a block
8679 // literal signature. Furthermore, it is always a FunctionProtoType
8680 // unless the function was written with a typedef.
8681 assert(T->isFunctionType() &&
8682 "GetTypeForDeclarator made a non-function block signature");
8683
8684 // Look for an explicit signature in that function type.
8685 FunctionProtoTypeLoc ExplicitSignature;
8686
8687 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8688 if (isa<FunctionProtoTypeLoc>(tmp)) {
8689 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8690
8691 // Check whether that explicit signature was synthesized by
8692 // GetTypeForDeclarator. If so, don't save that as part of the
8693 // written signature.
8694 if (ExplicitSignature.getLParenLoc() ==
8695 ExplicitSignature.getRParenLoc()) {
8696 // This would be much cheaper if we stored TypeLocs instead of
8697 // TypeSourceInfos.
8698 TypeLoc Result = ExplicitSignature.getResultLoc();
8699 unsigned Size = Result.getFullDataSize();
8700 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8701 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8702
8703 ExplicitSignature = FunctionProtoTypeLoc();
8704 }
John McCall82dc0092010-06-04 11:21:44 +00008705 }
Mike Stump1eb44332009-09-09 15:08:12 +00008706
John McCall711c52b2011-01-05 12:14:39 +00008707 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8708 CurBlock->FunctionType = T;
8709
8710 const FunctionType *Fn = T->getAs<FunctionType>();
8711 QualType RetTy = Fn->getResultType();
8712 bool isVariadic =
8713 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8714
John McCallc71a4912010-06-04 19:02:56 +00008715 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008716
John McCall82dc0092010-06-04 11:21:44 +00008717 // Don't allow returning a objc interface by value.
8718 if (RetTy->isObjCObjectType()) {
8719 Diag(ParamInfo.getSourceRange().getBegin(),
8720 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8721 return;
8722 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008723
John McCall82dc0092010-06-04 11:21:44 +00008724 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008725 // return type. TODO: what should we do with declarators like:
8726 // ^ * { ... }
8727 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00008728 if (RetTy != Context.DependentTy)
8729 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008730
John McCall82dc0092010-06-04 11:21:44 +00008731 // Push block parameters from the declarator if we had them.
John McCallc71a4912010-06-04 19:02:56 +00008732 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008733 if (ExplicitSignature) {
8734 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8735 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008736 if (Param->getIdentifier() == 0 &&
8737 !Param->isImplicit() &&
8738 !Param->isInvalidDecl() &&
8739 !getLangOptions().CPlusPlus)
8740 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008741 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008742 }
John McCall82dc0092010-06-04 11:21:44 +00008743
8744 // Fake up parameter variables if we have a typedef, like
8745 // ^ fntype { ... }
8746 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8747 for (FunctionProtoType::arg_type_iterator
8748 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8749 ParmVarDecl *Param =
8750 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8751 ParamInfo.getSourceRange().getBegin(),
8752 *I);
John McCallc71a4912010-06-04 19:02:56 +00008753 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008754 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008755 }
John McCall82dc0092010-06-04 11:21:44 +00008756
John McCallc71a4912010-06-04 19:02:56 +00008757 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008758 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00008759 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00008760 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8761 CurBlock->TheDecl->param_end(),
8762 /*CheckParameterNames=*/false);
8763 }
8764
John McCall82dc0092010-06-04 11:21:44 +00008765 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008766 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008767
John McCallc71a4912010-06-04 19:02:56 +00008768 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008769 Diag(ParamInfo.getAttributes()->getLoc(),
8770 diag::warn_attribute_sentinel_not_variadic) << 1;
8771 // FIXME: remove the attribute.
8772 }
8773
8774 // Put the parameter variables in scope. We can bail out immediately
8775 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008776 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008777 return;
8778
Steve Naroff090276f2008-10-10 01:28:17 +00008779 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008780 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8781 (*AI)->setOwningFunction(CurBlock->TheDecl);
8782
Steve Naroff090276f2008-10-10 01:28:17 +00008783 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008784 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008785 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008786
Steve Naroff090276f2008-10-10 01:28:17 +00008787 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008788 }
John McCall7a9813c2010-01-22 00:28:27 +00008789 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008790}
8791
8792/// ActOnBlockError - If there is an error parsing a block, this callback
8793/// is invoked to pop the information about the block from the action impl.
8794void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00008795 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008796 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008797 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008798}
8799
8800/// ActOnBlockStmtExpr - This is called when the body of a block statement
8801/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008802ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
John McCall9ae2f072010-08-23 23:25:46 +00008803 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008804 // If blocks are disabled, emit an error.
8805 if (!LangOpts.Blocks)
8806 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008807
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008808 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008809
Steve Naroff090276f2008-10-10 01:28:17 +00008810 PopDeclContext();
8811
Steve Naroff4eb206b2008-09-03 18:15:37 +00008812 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008813 if (!BSI->ReturnType.isNull())
8814 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008815
Mike Stump56925862009-07-28 22:04:01 +00008816 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008817 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008818
John McCall469a1eb2011-02-02 13:00:07 +00008819 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00008820 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8821 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00008822
John McCallc71a4912010-06-04 19:02:56 +00008823 // If the user wrote a function type in some form, try to use that.
8824 if (!BSI->FunctionType.isNull()) {
8825 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8826
8827 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8828 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8829
8830 // Turn protoless block types into nullary block types.
8831 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00008832 FunctionProtoType::ExtProtoInfo EPI;
8833 EPI.ExtInfo = Ext;
8834 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008835
8836 // Otherwise, if we don't need to change anything about the function type,
8837 // preserve its sugar structure.
8838 } else if (FTy->getResultType() == RetTy &&
8839 (!NoReturn || FTy->getNoReturnAttr())) {
8840 BlockTy = BSI->FunctionType;
8841
8842 // Otherwise, make the minimal modifications to the function type.
8843 } else {
8844 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00008845 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8846 EPI.TypeQuals = 0; // FIXME: silently?
8847 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00008848 BlockTy = Context.getFunctionType(RetTy,
8849 FPT->arg_type_begin(),
8850 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00008851 EPI);
John McCallc71a4912010-06-04 19:02:56 +00008852 }
8853
8854 // If we don't have a function type, just build one from nothing.
8855 } else {
John McCalle23cf432010-12-14 08:05:40 +00008856 FunctionProtoType::ExtProtoInfo EPI;
8857 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
8858 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008859 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008860
John McCallc71a4912010-06-04 19:02:56 +00008861 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8862 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00008863 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008864
Chris Lattner17a78302009-04-19 05:28:12 +00008865 // If needed, diagnose invalid gotos and switches in the block.
John McCall781472f2010-08-25 08:40:02 +00008866 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00008867 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00008868
John McCall9ae2f072010-08-23 23:25:46 +00008869 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Mike Stumpa3899eb2010-01-19 23:08:01 +00008870
Mike Stumpa3899eb2010-01-19 23:08:01 +00008871 // Check goto/label use.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008872 if (BSI->checkLabelUse(0, *this)) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008873 PopFunctionOrBlockScope();
Mike Stumpa3899eb2010-01-19 23:08:01 +00008874 return ExprError();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008875 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008876
John McCall469a1eb2011-02-02 13:00:07 +00008877 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCalle0054f62010-08-25 05:56:39 +00008878
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00008879 // Issue any analysis-based warnings.
Ted Kremenekd064fdc2010-03-23 00:13:23 +00008880 const sema::AnalysisBasedWarnings::Policy &WP =
8881 AnalysisWarnings.getDefaultPolicy();
John McCalle0054f62010-08-25 05:56:39 +00008882 AnalysisWarnings.IssueWarnings(WP, Result);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00008883
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008884 PopFunctionOrBlockScope();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008885 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00008886}
8887
John McCall60d7b3a2010-08-24 06:29:42 +00008888ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00008889 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008890 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008891 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008892 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00008893 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008894}
8895
John McCall60d7b3a2010-08-24 06:29:42 +00008896ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00008897 Expr *E, TypeSourceInfo *TInfo,
8898 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008899 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00008900
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008901 // Get the va_list type
8902 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008903 if (VaListType->isArrayType()) {
8904 // Deal with implicit array decay; for example, on x86-64,
8905 // va_list is an array, but it's supposed to decay to
8906 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008907 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00008908 // Make sure the input expression also decays appropriately.
8909 UsualUnaryConversions(E);
8910 } else {
8911 // Otherwise, the va_list argument must be an l-value because
8912 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00008913 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00008914 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00008915 return ExprError();
8916 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008917
Douglas Gregordd027302009-05-19 23:10:31 +00008918 if (!E->isTypeDependent() &&
8919 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00008920 return ExprError(Diag(E->getLocStart(),
8921 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008922 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00008923 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008924
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008925 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008926 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008927
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008928 QualType T = TInfo->getType().getNonLValueExprType(Context);
8929 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008930}
8931
John McCall60d7b3a2010-08-24 06:29:42 +00008932ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008933 // The type of __null will be int or long, depending on the size of
8934 // pointers on the target.
8935 QualType Ty;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008936 unsigned pw = Context.Target.getPointerWidth(0);
8937 if (pw == Context.Target.getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008938 Ty = Context.IntTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008939 else if (pw == Context.Target.getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008940 Ty = Context.LongTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008941 else if (pw == Context.Target.getLongLongWidth())
8942 Ty = Context.LongLongTy;
8943 else {
8944 assert(!"I don't know size of pointer!");
8945 Ty = Context.IntTy;
8946 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008947
Sebastian Redlf53597f2009-03-15 17:47:39 +00008948 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008949}
8950
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008951static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00008952 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008953 if (!SemaRef.getLangOptions().ObjC1)
8954 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008955
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008956 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8957 if (!PT)
8958 return;
8959
8960 // Check if the destination is of type 'id'.
8961 if (!PT->isObjCIdType()) {
8962 // Check if the destination is the 'NSString' interface.
8963 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8964 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8965 return;
8966 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008967
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008968 // Strip off any parens and casts.
8969 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8970 if (!SL || SL->isWide())
8971 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008972
Douglas Gregor849b2432010-03-31 17:46:05 +00008973 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008974}
8975
Chris Lattner5cf216b2008-01-04 18:04:52 +00008976bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8977 SourceLocation Loc,
8978 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00008979 Expr *SrcExpr, AssignmentAction Action,
8980 bool *Complained) {
8981 if (Complained)
8982 *Complained = false;
8983
Chris Lattner5cf216b2008-01-04 18:04:52 +00008984 // Decode the result (notice that AST's are still created for extensions).
8985 bool isInvalid = false;
8986 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00008987 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008988
Chris Lattner5cf216b2008-01-04 18:04:52 +00008989 switch (ConvTy) {
8990 default: assert(0 && "Unknown conversion type");
8991 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008992 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00008993 DiagKind = diag::ext_typecheck_convert_pointer_int;
8994 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008995 case IntToPointer:
8996 DiagKind = diag::ext_typecheck_convert_int_pointer;
8997 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008998 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00008999 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009000 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9001 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009002 case IncompatiblePointerSign:
9003 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9004 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009005 case FunctionVoidPointer:
9006 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9007 break;
John McCall86c05f32011-02-01 00:10:29 +00009008 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009009 // Perform array-to-pointer decay if necessary.
9010 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9011
John McCall86c05f32011-02-01 00:10:29 +00009012 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9013 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9014 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9015 DiagKind = diag::err_typecheck_incompatible_address_space;
9016 break;
9017 }
9018
9019 llvm_unreachable("unknown error case for discarding qualifiers!");
9020 // fallthrough
9021 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009022 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009023 // If the qualifiers lost were because we were applying the
9024 // (deprecated) C++ conversion from a string literal to a char*
9025 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9026 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009027 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009028 // bit of refactoring (so that the second argument is an
9029 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009030 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009031 // C++ semantics.
9032 if (getLangOptions().CPlusPlus &&
9033 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9034 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009035 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9036 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009037 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009038 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009039 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009040 case IntToBlockPointer:
9041 DiagKind = diag::err_int_to_block_pointer;
9042 break;
9043 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009044 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009045 break;
Steve Naroff39579072008-10-14 22:18:38 +00009046 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009047 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009048 // it can give a more specific diagnostic.
9049 DiagKind = diag::warn_incompatible_qualified_id;
9050 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009051 case IncompatibleVectors:
9052 DiagKind = diag::warn_incompatible_vectors;
9053 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009054 case Incompatible:
9055 DiagKind = diag::err_typecheck_convert_incompatible;
9056 isInvalid = true;
9057 break;
9058 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009059
Douglas Gregord4eea832010-04-09 00:35:39 +00009060 QualType FirstType, SecondType;
9061 switch (Action) {
9062 case AA_Assigning:
9063 case AA_Initializing:
9064 // The destination type comes first.
9065 FirstType = DstType;
9066 SecondType = SrcType;
9067 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009068
Douglas Gregord4eea832010-04-09 00:35:39 +00009069 case AA_Returning:
9070 case AA_Passing:
9071 case AA_Converting:
9072 case AA_Sending:
9073 case AA_Casting:
9074 // The source type comes first.
9075 FirstType = SrcType;
9076 SecondType = DstType;
9077 break;
9078 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009079
Douglas Gregord4eea832010-04-09 00:35:39 +00009080 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009081 << SrcExpr->getSourceRange() << Hint;
Douglas Gregora41a8c52010-04-22 00:20:18 +00009082 if (Complained)
9083 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009084 return isInvalid;
9085}
Anders Carlssone21555e2008-11-30 19:50:32 +00009086
Chris Lattner3bf68932009-04-25 21:59:05 +00009087bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009088 llvm::APSInt ICEResult;
9089 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9090 if (Result)
9091 *Result = ICEResult;
9092 return false;
9093 }
9094
Anders Carlssone21555e2008-11-30 19:50:32 +00009095 Expr::EvalResult EvalResult;
9096
Mike Stumpeed9cac2009-02-19 03:04:26 +00009097 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009098 EvalResult.HasSideEffects) {
9099 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9100
9101 if (EvalResult.Diag) {
9102 // We only show the note if it's not the usual "invalid subexpression"
9103 // or if it's actually in a subexpression.
9104 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9105 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9106 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9107 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009108
Anders Carlssone21555e2008-11-30 19:50:32 +00009109 return true;
9110 }
9111
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009112 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9113 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009114
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009115 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009116 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9117 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009118 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009119
Anders Carlssone21555e2008-11-30 19:50:32 +00009120 if (Result)
9121 *Result = EvalResult.Val.getInt();
9122 return false;
9123}
Douglas Gregore0762c92009-06-19 23:52:42 +00009124
Douglas Gregor2afce722009-11-26 00:44:06 +00009125void
Mike Stump1eb44332009-09-09 15:08:12 +00009126Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009127 ExprEvalContexts.push_back(
9128 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00009129}
9130
Mike Stump1eb44332009-09-09 15:08:12 +00009131void
Douglas Gregor2afce722009-11-26 00:44:06 +00009132Sema::PopExpressionEvaluationContext() {
9133 // Pop the current expression evaluation context off the stack.
9134 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9135 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009136
Douglas Gregor06d33692009-12-12 07:57:52 +00009137 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9138 if (Rec.PotentiallyReferenced) {
9139 // Mark any remaining declarations in the current position of the stack
9140 // as "referenced". If they were not meant to be referenced, semantic
9141 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009142 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009143 I = Rec.PotentiallyReferenced->begin(),
9144 IEnd = Rec.PotentiallyReferenced->end();
9145 I != IEnd; ++I)
9146 MarkDeclarationReferenced(I->first, I->second);
9147 }
9148
9149 if (Rec.PotentiallyDiagnosed) {
9150 // Emit any pending diagnostics.
9151 for (PotentiallyEmittedDiagnostics::iterator
9152 I = Rec.PotentiallyDiagnosed->begin(),
9153 IEnd = Rec.PotentiallyDiagnosed->end();
9154 I != IEnd; ++I)
9155 Diag(I->first, I->second);
9156 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009157 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009158
9159 // When are coming out of an unevaluated context, clear out any
9160 // temporaries that we may have created as part of the evaluation of
9161 // the expression in that context: they aren't relevant because they
9162 // will never be constructed.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009163 if (Rec.Context == Unevaluated &&
Douglas Gregor2afce722009-11-26 00:44:06 +00009164 ExprTemporaries.size() > Rec.NumTemporaries)
9165 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9166 ExprTemporaries.end());
9167
9168 // Destroy the popped expression evaluation record.
9169 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009170}
Douglas Gregore0762c92009-06-19 23:52:42 +00009171
9172/// \brief Note that the given declaration was referenced in the source code.
9173///
9174/// This routine should be invoke whenever a given declaration is referenced
9175/// in the source code, and where that reference occurred. If this declaration
9176/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9177/// C99 6.9p3), then the declaration will be marked as used.
9178///
9179/// \param Loc the location where the declaration was referenced.
9180///
9181/// \param D the declaration that has been referenced by the source code.
9182void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9183 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009184
Douglas Gregorc070cc62010-06-17 23:14:26 +00009185 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009186 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009187
Douglas Gregorb5352cf2009-10-08 21:35:42 +00009188 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9189 // template or not. The reason for this is that unevaluated expressions
9190 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9191 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009192 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009193 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009194 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009195 return;
9196 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009197
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009198 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9199 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009200
Douglas Gregore0762c92009-06-19 23:52:42 +00009201 // Do not mark anything as "used" within a dependent context; wait for
9202 // an instantiation.
9203 if (CurContext->isDependentContext())
9204 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009205
Douglas Gregor2afce722009-11-26 00:44:06 +00009206 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009207 case Unevaluated:
9208 // We are in an expression that is not potentially evaluated; do nothing.
9209 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009210
Douglas Gregorac7610d2009-06-22 20:57:11 +00009211 case PotentiallyEvaluated:
9212 // We are in a potentially-evaluated expression, so this declaration is
9213 // "used"; handle this below.
9214 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009215
Douglas Gregorac7610d2009-06-22 20:57:11 +00009216 case PotentiallyPotentiallyEvaluated:
9217 // We are in an expression that may be potentially evaluated; queue this
9218 // declaration reference until we know whether the expression is
9219 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009220 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009221 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009222
9223 case PotentiallyEvaluatedIfUsed:
9224 // Referenced declarations will only be used if the construct in the
9225 // containing expression is used.
9226 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009227 }
Mike Stump1eb44332009-09-09 15:08:12 +00009228
Douglas Gregore0762c92009-06-19 23:52:42 +00009229 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009230 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009231 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00009232 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00009233 if (Constructor->getParent()->hasTrivialConstructor())
9234 return;
9235 if (!Constructor->isUsed(false))
9236 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00009237 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00009238 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009239 if (!Constructor->isUsed(false))
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009240 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9241 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009242
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009243 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009244 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009245 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009246 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009247 if (Destructor->isVirtual())
9248 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009249 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9250 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9251 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009252 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +00009253 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009254 } else if (MethodDecl->isVirtual())
9255 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009256 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009257 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00009258 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009259 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009260 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009261 bool AlreadyInstantiated = false;
9262 if (FunctionTemplateSpecializationInfo *SpecInfo
9263 = Function->getTemplateSpecializationInfo()) {
9264 if (SpecInfo->getPointOfInstantiation().isInvalid())
9265 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009266 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009267 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009268 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009269 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009270 = Function->getMemberSpecializationInfo()) {
9271 if (MSInfo->getPointOfInstantiation().isInvalid())
9272 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009273 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009274 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009275 AlreadyInstantiated = true;
9276 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009277
Douglas Gregor60406be2010-01-16 22:29:39 +00009278 if (!AlreadyInstantiated) {
9279 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9280 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9281 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9282 Loc));
9283 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009284 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009285 }
Gabor Greif40181c42010-08-28 00:16:06 +00009286 } else // Walk redefinitions, as some of them may be instantiable.
9287 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9288 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009289 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009290 MarkDeclarationReferenced(Loc, *i);
9291 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009292
Douglas Gregore0762c92009-06-19 23:52:42 +00009293 // FIXME: keep track of references to static functions
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009294
9295 // Recursive functions should be marked when used from another function.
9296 if (CurContext != Function)
9297 Function->setUsed(true);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009298
Douglas Gregore0762c92009-06-19 23:52:42 +00009299 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009300 }
Mike Stump1eb44332009-09-09 15:08:12 +00009301
Douglas Gregore0762c92009-06-19 23:52:42 +00009302 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009303 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009304 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009305 Var->getInstantiatedFromStaticDataMember()) {
9306 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9307 assert(MSInfo && "Missing member specialization information?");
9308 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9309 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9310 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009311 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009312 }
9313 }
Mike Stump1eb44332009-09-09 15:08:12 +00009314
Douglas Gregore0762c92009-06-19 23:52:42 +00009315 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00009316
Douglas Gregore0762c92009-06-19 23:52:42 +00009317 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00009318 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00009319 }
Douglas Gregore0762c92009-06-19 23:52:42 +00009320}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009321
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009322namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009323 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009324 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009325 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009326 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9327 Sema &S;
9328 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009329
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009330 public:
9331 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009332
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009333 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009334
9335 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9336 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009337 };
9338}
9339
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009340bool MarkReferencedDecls::TraverseTemplateArgument(
9341 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009342 if (Arg.getKind() == TemplateArgument::Declaration) {
9343 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9344 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009345
9346 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009347}
9348
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009349bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009350 if (ClassTemplateSpecializationDecl *Spec
9351 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9352 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00009353 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009354 }
9355
Chandler Carruthe3e210c2010-06-10 10:31:57 +00009356 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009357}
9358
9359void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9360 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009361 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009362}
9363
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009364namespace {
9365 /// \brief Helper class that marks all of the declarations referenced by
9366 /// potentially-evaluated subexpressions as "referenced".
9367 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9368 Sema &S;
9369
9370 public:
9371 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9372
9373 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9374
9375 void VisitDeclRefExpr(DeclRefExpr *E) {
9376 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9377 }
9378
9379 void VisitMemberExpr(MemberExpr *E) {
9380 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009381 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009382 }
9383
9384 void VisitCXXNewExpr(CXXNewExpr *E) {
9385 if (E->getConstructor())
9386 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9387 if (E->getOperatorNew())
9388 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9389 if (E->getOperatorDelete())
9390 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009391 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009392 }
9393
9394 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9395 if (E->getOperatorDelete())
9396 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009397 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9398 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9399 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9400 S.MarkDeclarationReferenced(E->getLocStart(),
9401 S.LookupDestructor(Record));
9402 }
9403
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009404 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009405 }
9406
9407 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9408 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009409 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009410 }
9411
9412 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9413 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9414 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009415
9416 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9417 Visit(E->getExpr());
9418 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009419 };
9420}
9421
9422/// \brief Mark any declarations that appear within this expression or any
9423/// potentially-evaluated subexpressions as "referenced".
9424void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9425 EvaluatedExprMarker(*this).Visit(E);
9426}
9427
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009428/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9429/// of the program being compiled.
9430///
9431/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009432/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009433/// possibility that the code will actually be executable. Code in sizeof()
9434/// expressions, code used only during overload resolution, etc., are not
9435/// potentially evaluated. This routine will suppress such diagnostics or,
9436/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009437/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009438/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009439///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009440/// This routine should be used for all diagnostics that describe the run-time
9441/// behavior of a program, such as passing a non-POD value through an ellipsis.
9442/// Failure to do so will likely result in spurious diagnostics or failures
9443/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009444bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009445 const PartialDiagnostic &PD) {
9446 switch (ExprEvalContexts.back().Context ) {
9447 case Unevaluated:
9448 // The argument will never be evaluated, so don't complain.
9449 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009450
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009451 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009452 case PotentiallyEvaluatedIfUsed:
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009453 Diag(Loc, PD);
9454 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009455
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009456 case PotentiallyPotentiallyEvaluated:
9457 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9458 break;
9459 }
9460
9461 return false;
9462}
9463
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009464bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9465 CallExpr *CE, FunctionDecl *FD) {
9466 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9467 return false;
9468
9469 PartialDiagnostic Note =
9470 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9471 << FD->getDeclName() : PDiag();
9472 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009473
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009474 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009475 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009476 PDiag(diag::err_call_function_incomplete_return)
9477 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009478 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009479 << CE->getSourceRange(),
9480 std::make_pair(NoteLoc, Note)))
9481 return true;
9482
9483 return false;
9484}
9485
Douglas Gregor92c3a042011-01-19 16:50:08 +00009486// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +00009487// will prevent this condition from triggering, which is what we want.
9488void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9489 SourceLocation Loc;
9490
John McCalla52ef082009-11-11 02:41:58 +00009491 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +00009492 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +00009493
John McCall5a881bb2009-10-12 21:59:07 +00009494 if (isa<BinaryOperator>(E)) {
9495 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +00009496 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +00009497 return;
9498
Douglas Gregor92c3a042011-01-19 16:50:08 +00009499 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9500
John McCallc8d8ac52009-11-12 00:06:05 +00009501 // Greylist some idioms by putting them into a warning subcategory.
9502 if (ObjCMessageExpr *ME
9503 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9504 Selector Sel = ME->getSelector();
9505
John McCallc8d8ac52009-11-12 00:06:05 +00009506 // self = [<foo> init...]
9507 if (isSelfExpr(Op->getLHS())
9508 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
9509 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9510
9511 // <foo> = [<bar> nextObject]
9512 else if (Sel.isUnarySelector() &&
9513 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
9514 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9515 }
John McCalla52ef082009-11-11 02:41:58 +00009516
John McCall5a881bb2009-10-12 21:59:07 +00009517 Loc = Op->getOperatorLoc();
9518 } else if (isa<CXXOperatorCallExpr>(E)) {
9519 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +00009520 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +00009521 return;
9522
Douglas Gregor92c3a042011-01-19 16:50:08 +00009523 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +00009524 Loc = Op->getOperatorLoc();
9525 } else {
9526 // Not an assignment.
9527 return;
9528 }
9529
John McCall5a881bb2009-10-12 21:59:07 +00009530 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00009531 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009532
Douglas Gregor55b38842010-04-14 16:09:52 +00009533 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +00009534
9535 if (IsOrAssign)
9536 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9537 << FixItHint::CreateReplacement(Loc, "!=");
9538 else
9539 Diag(Loc, diag::note_condition_assign_to_comparison)
9540 << FixItHint::CreateReplacement(Loc, "==");
9541
Douglas Gregor55b38842010-04-14 16:09:52 +00009542 Diag(Loc, diag::note_condition_assign_silence)
9543 << FixItHint::CreateInsertion(Open, "(")
9544 << FixItHint::CreateInsertion(Close, ")");
John McCall5a881bb2009-10-12 21:59:07 +00009545}
9546
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009547/// \brief Redundant parentheses over an equality comparison can indicate
9548/// that the user intended an assignment used as condition.
9549void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009550 // Don't warn if the parens came from a macro.
9551 SourceLocation parenLoc = parenE->getLocStart();
9552 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9553 return;
9554
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009555 Expr *E = parenE->IgnoreParens();
9556
9557 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +00009558 if (opE->getOpcode() == BO_EQ &&
9559 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9560 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009561 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +00009562
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009563 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9564 Diag(Loc, diag::note_equality_comparison_to_assign)
9565 << FixItHint::CreateReplacement(Loc, "=");
9566 Diag(Loc, diag::note_equality_comparison_silence)
9567 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9568 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009569 }
9570}
9571
John McCall5a881bb2009-10-12 21:59:07 +00009572bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9573 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009574 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9575 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +00009576
9577 if (!E->isTypeDependent()) {
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009578 if (E->isBoundMemberFunction(Context))
9579 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9580 << E->getSourceRange();
9581
John McCallf6a16482010-12-04 03:47:34 +00009582 if (getLangOptions().CPlusPlus)
9583 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9584
9585 DefaultFunctionArrayLvalueConversion(E);
John McCallabc56c72010-12-04 06:09:13 +00009586
9587 QualType T = E->getType();
John McCallf6a16482010-12-04 03:47:34 +00009588 if (!T->isScalarType()) // C99 6.8.4.1p1
9589 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9590 << T << E->getSourceRange();
John McCall5a881bb2009-10-12 21:59:07 +00009591 }
9592
9593 return false;
9594}
Douglas Gregor586596f2010-05-06 17:25:47 +00009595
John McCall60d7b3a2010-08-24 06:29:42 +00009596ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9597 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +00009598 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +00009599 return ExprError();
9600
Douglas Gregorff331c12010-07-25 18:17:45 +00009601 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregor586596f2010-05-06 17:25:47 +00009602 return ExprError();
Douglas Gregor586596f2010-05-06 17:25:47 +00009603
9604 return Owned(Sub);
9605}
John McCall2a984ca2010-10-12 00:20:44 +00009606
9607/// Check for operands with placeholder types and complain if found.
9608/// Returns true if there was an error and no recovery was possible.
9609ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9610 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9611 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9612
9613 // If this is overload, check for a single overload.
9614 if (BT->getKind() == BuiltinType::Overload) {
9615 if (FunctionDecl *Specialization
9616 = ResolveSingleFunctionTemplateSpecialization(E)) {
9617 // The access doesn't really matter in this case.
9618 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9619 Specialization->getAccess());
9620 E = FixOverloadedFunctionReference(E, Found, Specialization);
9621 if (!E) return ExprError();
9622 return Owned(E);
9623 }
9624
John McCall2cd11fe2010-10-12 02:09:17 +00009625 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
John McCall2a984ca2010-10-12 00:20:44 +00009626 return ExprError();
9627 }
9628
9629 // Otherwise it's a use of undeduced auto.
9630 assert(BT->getKind() == BuiltinType::UndeducedAuto);
9631
9632 DeclRefExpr *DRE = cast<DeclRefExpr>(E->IgnoreParens());
9633 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
9634 << DRE->getDecl() << E->getSourceRange();
9635 return ExprError();
9636}