blob: 2abbcf0acdce394f82a2323cc0237e91dc5aae1f [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Douglas Gregord1702062010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000023#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000024#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000026#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000027#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000029#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000031#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000033#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Designator.h"
35#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000036#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000037#include "clang/Sema/ParsedTemplate.h"
John McCallde6836a2010-08-24 07:21:54 +000038#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000039using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000040using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000041
David Chisnall9f57c292009-08-17 16:35:33 +000042
Douglas Gregor171c45a2009-02-18 21:56:37 +000043/// \brief Determine whether the use of this declaration is valid, and
44/// emit any corresponding diagnostics.
45///
46/// This routine diagnoses various problems with referencing
47/// declarations that can occur when using a declaration. For example,
48/// it might warn if a deprecated or unavailable declaration is being
49/// used, or produce an error (and return true) if a C++0x deleted
50/// function is being used.
51///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000052/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattnerb7df3c62009-10-25 22:31:57 +000053/// decls.
54///
Douglas Gregor171c45a2009-02-18 21:56:37 +000055/// \returns true if there was an error (this declaration cannot be
56/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000057///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000058bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Peter Collingbourneed12ffb2011-01-02 19:53:12 +000059 bool UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000060 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
61 // If there were any diagnostics suppressed by template argument deduction,
62 // emit them now.
63 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
64 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
65 if (Pos != SuppressedDiagnostics.end()) {
66 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
67 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
68 Diag(Suppressed[I].first, Suppressed[I].second);
69
70 // Clear out the list of suppressed diagnostics, so that we don't emit
71 // them again for this specialization. However, we don't remove this
72 // entry from the table, because we want to avoid ever emitting these
73 // diagnostics again.
74 Suppressed.clear();
75 }
76 }
77
Richard Smith30482bc2011-02-20 03:19:35 +000078 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +000079 if (ParsingInitForAutoVars.count(D)) {
80 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
81 << D->getDeclName();
82 return true;
Richard Smith30482bc2011-02-20 03:19:35 +000083 }
84
Chris Lattner4bf74fd2009-02-15 22:43:40 +000085 // See if the decl is deprecated.
Benjamin Kramerbfac7dc2010-10-09 15:49:00 +000086 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>())
Peter Collingbourneed12ffb2011-01-02 19:53:12 +000087 EmitDeprecationWarning(D, DA->getMessage(), Loc, UnknownObjCClass);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000088
Chris Lattnera27dd592009-10-25 17:21:40 +000089 // See if the decl is unavailable
Fariborz Jahanianc74073c2010-10-06 23:12:32 +000090 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) {
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000091 if (UA->getMessage().empty()) {
Peter Collingbourneed12ffb2011-01-02 19:53:12 +000092 if (!UnknownObjCClass)
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000093 Diag(Loc, diag::err_unavailable) << D->getDeclName();
94 else
95 Diag(Loc, diag::warn_unavailable_fwdclass_message)
96 << D->getDeclName();
97 }
98 else
Fariborz Jahanianc74073c2010-10-06 23:12:32 +000099 Diag(Loc, diag::err_unavailable_message)
Benjamin Kramerbfac7dc2010-10-09 15:49:00 +0000100 << D->getDeclName() << UA->getMessage();
Chris Lattnera27dd592009-10-25 17:21:40 +0000101 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
102 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000103
Douglas Gregor171c45a2009-02-18 21:56:37 +0000104 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000105 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000106 if (FD->isDeleted()) {
107 Diag(Loc, diag::err_deleted_function_use);
108 Diag(D->getLocation(), diag::note_unavailable_here) << true;
109 return true;
110 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000111 }
Douglas Gregor171c45a2009-02-18 21:56:37 +0000112
Anders Carlsson73067a02010-10-22 23:37:08 +0000113 // Warn if this is used but marked unused.
114 if (D->hasAttr<UnusedAttr>())
115 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
116
Douglas Gregor171c45a2009-02-18 21:56:37 +0000117 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000118}
119
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000120/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000121/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000122/// attribute. It warns if call does not have the sentinel argument.
123///
124void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000125 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000126 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000127 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000128 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000129
130 // FIXME: In C++0x, if any of the arguments are parameter pack
131 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000132 int sentinelPos = attr->getSentinel();
133 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000134
Mike Stump87c57ac2009-05-16 07:39:55 +0000135 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
136 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000137 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000138 bool warnNotEnoughArgs = false;
139 int isMethod = 0;
140 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
141 // skip over named parameters.
142 ObjCMethodDecl::param_iterator P, E = MD->param_end();
143 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
144 if (nullPos)
145 --nullPos;
146 else
147 ++i;
148 }
149 warnNotEnoughArgs = (P != E || i >= NumArgs);
150 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000151 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000152 // skip over named parameters.
153 ObjCMethodDecl::param_iterator P, E = FD->param_end();
154 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
155 if (nullPos)
156 --nullPos;
157 else
158 ++i;
159 }
160 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000161 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000162 // block or function pointer call.
163 QualType Ty = V->getType();
164 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000165 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000166 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
167 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000168 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
169 unsigned NumArgsInProto = Proto->getNumArgs();
170 unsigned k;
171 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
172 if (nullPos)
173 --nullPos;
174 else
175 ++i;
176 }
177 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
178 }
179 if (Ty->isBlockPointerType())
180 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000181 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000182 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000183 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000184 return;
185
186 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000187 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000188 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000189 return;
190 }
191 int sentinel = i;
192 while (sentinelPos > 0 && i < NumArgs-1) {
193 --sentinelPos;
194 ++i;
195 }
196 if (sentinelPos > 0) {
197 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000198 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000199 return;
200 }
201 while (i < NumArgs-1) {
202 ++i;
203 ++sentinel;
204 }
205 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000206 if (!sentinelExpr) return;
207 if (sentinelExpr->isTypeDependent()) return;
208 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000209
210 // nullptr_t is always treated as null.
211 if (sentinelExpr->getType()->isNullPtrType()) return;
212
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000213 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000214 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
215 Expr::NPC_ValueDependentIsNull))
216 return;
217
218 // Unfortunately, __null has type 'int'.
219 if (isa<GNUNullExpr>(sentinelExpr)) return;
220
221 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
222 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000223}
224
Douglas Gregor87f95b02009-02-26 21:00:50 +0000225SourceRange Sema::getExprRange(ExprTy *E) const {
226 Expr *Ex = (Expr *)E;
227 return Ex? Ex->getSourceRange() : SourceRange();
228}
229
Chris Lattner513165e2008-07-25 21:10:04 +0000230//===----------------------------------------------------------------------===//
231// Standard Promotions and Conversions
232//===----------------------------------------------------------------------===//
233
Chris Lattner513165e2008-07-25 21:10:04 +0000234/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
235void Sema::DefaultFunctionArrayConversion(Expr *&E) {
236 QualType Ty = E->getType();
237 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
238
Chris Lattner513165e2008-07-25 21:10:04 +0000239 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000240 ImpCastExprToType(E, Context.getPointerType(Ty),
John McCalle3027922010-08-25 11:45:40 +0000241 CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000242 else if (Ty->isArrayType()) {
243 // In C90 mode, arrays only promote to pointers if the array expression is
244 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
245 // type 'array of type' is converted to an expression that has type 'pointer
246 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
247 // that has type 'array of type' ...". The relevant change is "an lvalue"
248 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000249 //
250 // C++ 4.2p1:
251 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
252 // T" can be converted to an rvalue of type "pointer to T".
253 //
John McCall086a4642010-11-24 05:12:34 +0000254 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000255 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
John McCalle3027922010-08-25 11:45:40 +0000256 CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000257 }
Chris Lattner513165e2008-07-25 21:10:04 +0000258}
259
John McCall27584242010-12-06 20:48:59 +0000260void Sema::DefaultLvalueConversion(Expr *&E) {
John McCallf3735e02010-12-01 04:43:34 +0000261 // C++ [conv.lval]p1:
262 // A glvalue of a non-function, non-array type T can be
263 // converted to a prvalue.
John McCall27584242010-12-06 20:48:59 +0000264 if (!E->isGLValue()) return;
John McCall34376a62010-12-04 03:47:34 +0000265
John McCall27584242010-12-06 20:48:59 +0000266 QualType T = E->getType();
267 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000268
John McCall27584242010-12-06 20:48:59 +0000269 // Create a load out of an ObjCProperty l-value, if necessary.
270 if (E->getObjectKind() == OK_ObjCProperty) {
271 ConvertPropertyForRValue(E);
272 if (!E->isGLValue())
John McCall34376a62010-12-04 03:47:34 +0000273 return;
Douglas Gregorb92a1562010-02-03 00:27:59 +0000274 }
John McCall27584242010-12-06 20:48:59 +0000275
276 // We don't want to throw lvalue-to-rvalue casts on top of
277 // expressions of certain types in C++.
278 if (getLangOptions().CPlusPlus &&
279 (E->getType() == Context.OverloadTy ||
280 T->isDependentType() ||
281 T->isRecordType()))
282 return;
283
284 // The C standard is actually really unclear on this point, and
285 // DR106 tells us what the result should be but not why. It's
286 // generally best to say that void types just doesn't undergo
287 // lvalue-to-rvalue at all. Note that expressions of unqualified
288 // 'void' type are never l-values, but qualified void can be.
289 if (T->isVoidType())
290 return;
291
292 // C++ [conv.lval]p1:
293 // [...] If T is a non-class type, the type of the prvalue is the
294 // cv-unqualified version of T. Otherwise, the type of the
295 // rvalue is T.
296 //
297 // C99 6.3.2.1p2:
298 // If the lvalue has qualified type, the value has the unqualified
299 // version of the type of the lvalue; otherwise, the value has the
300 // type of the lvalue.
301 if (T.hasQualifiers())
302 T = T.getUnqualifiedType();
303
Ted Kremenek64699be2011-02-16 01:57:07 +0000304 if (const ArraySubscriptExpr *ae = dyn_cast<ArraySubscriptExpr>(E))
305 CheckArrayAccess(ae);
306
John McCall27584242010-12-06 20:48:59 +0000307 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
308 E, 0, VK_RValue);
309}
310
311void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
312 DefaultFunctionArrayConversion(E);
313 DefaultLvalueConversion(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000314}
315
316
Chris Lattner513165e2008-07-25 21:10:04 +0000317/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000318/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000319/// sometimes surpressed. For example, the array->pointer conversion doesn't
320/// apply if the array is an argument to the sizeof or address (&) operators.
321/// In these instances, this routine should *not* be called.
John McCallf3735e02010-12-01 04:43:34 +0000322Expr *Sema::UsualUnaryConversions(Expr *&E) {
323 // First, convert to an r-value.
324 DefaultFunctionArrayLvalueConversion(E);
325
326 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000327 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000328
329 // Try to perform integral promotions if the object has a theoretically
330 // promotable type.
331 if (Ty->isIntegralOrUnscopedEnumerationType()) {
332 // C99 6.3.1.1p2:
333 //
334 // The following may be used in an expression wherever an int or
335 // unsigned int may be used:
336 // - an object or expression with an integer type whose integer
337 // conversion rank is less than or equal to the rank of int
338 // and unsigned int.
339 // - A bit-field of type _Bool, int, signed int, or unsigned int.
340 //
341 // If an int can represent all values of the original type, the
342 // value is converted to an int; otherwise, it is converted to an
343 // unsigned int. These are called the integer promotions. All
344 // other types are unchanged by the integer promotions.
345
346 QualType PTy = Context.isPromotableBitField(E);
347 if (!PTy.isNull()) {
348 ImpCastExprToType(E, PTy, CK_IntegralCast);
349 return E;
350 }
351 if (Ty->isPromotableIntegerType()) {
352 QualType PT = Context.getPromotedIntegerType(Ty);
353 ImpCastExprToType(E, PT, CK_IntegralCast);
354 return E;
355 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000356 }
357
John McCallf3735e02010-12-01 04:43:34 +0000358 return E;
Chris Lattner513165e2008-07-25 21:10:04 +0000359}
360
Chris Lattner2ce500f2008-07-25 22:25:12 +0000361/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000362/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000363/// double. All other argument types are converted by UsualUnaryConversions().
364void Sema::DefaultArgumentPromotion(Expr *&Expr) {
365 QualType Ty = Expr->getType();
366 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000367
John McCall9bc26772010-12-06 18:36:11 +0000368 UsualUnaryConversions(Expr);
369
Chris Lattner2ce500f2008-07-25 22:25:12 +0000370 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000371 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John McCall9bc26772010-12-06 18:36:11 +0000372 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000373}
374
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000375/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
376/// will warn if the resulting type is not a POD type, and rejects ObjC
377/// interfaces passed by value. This returns true if the argument type is
378/// completely illegal.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000379bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
380 FunctionDecl *FDecl) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000381 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000382
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000383 // __builtin_va_start takes the second argument as a "varargs" argument, but
384 // it doesn't actually do anything with it. It doesn't need to be non-pod
385 // etc.
386 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
387 return false;
388
John McCall8b07ec22010-05-15 11:32:37 +0000389 if (Expr->getType()->isObjCObjectType() &&
Ted Kremenek3427fac2011-02-23 01:52:04 +0000390 DiagRuntimeBehavior(Expr->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000391 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
392 << Expr->getType() << CT))
393 return true;
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000394
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000395 if (!Expr->getType()->isPODType() &&
Ted Kremenek3427fac2011-02-23 01:52:04 +0000396 DiagRuntimeBehavior(Expr->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000397 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
398 << Expr->getType() << CT))
399 return true;
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000400
401 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000402}
403
Chris Lattner513165e2008-07-25 21:10:04 +0000404/// UsualArithmeticConversions - Performs various conversions that are common to
405/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000406/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000407/// responsible for emitting appropriate error diagnostics.
408/// FIXME: verify the conversion rules for "complex int" are consistent with
409/// GCC.
410QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
411 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000412 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000413 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000414
415 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000416
Mike Stump11289f42009-09-09 15:08:12 +0000417 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000418 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000419 QualType lhs =
420 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000421 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000422 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000423
424 // If both types are identical, no conversion is needed.
425 if (lhs == rhs)
426 return lhs;
427
428 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
429 // The caller can deal with this (e.g. pointer + int).
430 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
431 return lhs;
432
John McCalld005ac92010-11-13 08:17:45 +0000433 // Apply unary and bitfield promotions to the LHS's type.
434 QualType lhs_unpromoted = lhs;
435 if (lhs->isPromotableIntegerType())
436 lhs = Context.getPromotedIntegerType(lhs);
Eli Friedman629ffb92009-08-20 04:21:42 +0000437 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000438 if (!LHSBitfieldPromoteTy.isNull())
439 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000440 if (lhs != lhs_unpromoted && !isCompAssign)
441 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000442
John McCalld005ac92010-11-13 08:17:45 +0000443 // If both types are identical, no conversion is needed.
444 if (lhs == rhs)
445 return lhs;
446
447 // At this point, we have two different arithmetic types.
448
449 // Handle complex types first (C99 6.3.1.8p1).
450 bool LHSComplexFloat = lhs->isComplexType();
451 bool RHSComplexFloat = rhs->isComplexType();
452 if (LHSComplexFloat || RHSComplexFloat) {
453 // if we have an integer operand, the result is the complex type.
454
John McCallc5e62b42010-11-13 09:02:35 +0000455 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
456 if (rhs->isIntegerType()) {
457 QualType fp = cast<ComplexType>(lhs)->getElementType();
458 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
459 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
460 } else {
461 assert(rhs->isComplexIntegerType());
John McCalld7646252010-11-14 08:17:51 +0000462 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000463 }
John McCalld005ac92010-11-13 08:17:45 +0000464 return lhs;
465 }
466
John McCallc5e62b42010-11-13 09:02:35 +0000467 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
468 if (!isCompAssign) {
469 // int -> float -> _Complex float
470 if (lhs->isIntegerType()) {
471 QualType fp = cast<ComplexType>(rhs)->getElementType();
472 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
473 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
474 } else {
475 assert(lhs->isComplexIntegerType());
John McCalld7646252010-11-14 08:17:51 +0000476 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000477 }
478 }
John McCalld005ac92010-11-13 08:17:45 +0000479 return rhs;
480 }
481
482 // This handles complex/complex, complex/float, or float/complex.
483 // When both operands are complex, the shorter operand is converted to the
484 // type of the longer, and that is the type of the result. This corresponds
485 // to what is done when combining two real floating-point operands.
486 // The fun begins when size promotion occur across type domains.
487 // From H&S 6.3.4: When one operand is complex and the other is a real
488 // floating-point type, the less precise type is converted, within it's
489 // real or complex domain, to the precision of the other type. For example,
490 // when combining a "long double" with a "double _Complex", the
491 // "double _Complex" is promoted to "long double _Complex".
492 int order = Context.getFloatingTypeOrder(lhs, rhs);
493
494 // If both are complex, just cast to the more precise type.
495 if (LHSComplexFloat && RHSComplexFloat) {
496 if (order > 0) {
497 // _Complex float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000498 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000499 return lhs;
500
501 } else if (order < 0) {
502 // _Complex float -> _Complex double
503 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000504 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000505 return rhs;
506 }
507 return lhs;
508 }
509
510 // If just the LHS is complex, the RHS needs to be converted,
511 // and the LHS might need to be promoted.
512 if (LHSComplexFloat) {
513 if (order > 0) { // LHS is wider
514 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000515 QualType fp = cast<ComplexType>(lhs)->getElementType();
516 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
517 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000518 return lhs;
519 }
520
521 // RHS is at least as wide. Find its corresponding complex type.
522 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
523
524 // double -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000525 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000526
527 // _Complex float -> _Complex double
528 if (!isCompAssign && order < 0)
John McCallc5e62b42010-11-13 09:02:35 +0000529 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000530
531 return result;
532 }
533
534 // Just the RHS is complex, so the LHS needs to be converted
535 // and the RHS might need to be promoted.
536 assert(RHSComplexFloat);
537
538 if (order < 0) { // RHS is wider
539 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000540 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000541 QualType fp = cast<ComplexType>(rhs)->getElementType();
542 ImpCastExprToType(lhsExpr, fp, CK_FloatingCast);
John McCallc5e62b42010-11-13 09:02:35 +0000543 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
544 }
John McCalld005ac92010-11-13 08:17:45 +0000545 return rhs;
546 }
547
548 // LHS is at least as wide. Find its corresponding complex type.
549 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
550
551 // double -> _Complex double
552 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000553 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000554
555 // _Complex float -> _Complex double
556 if (order > 0)
John McCallc5e62b42010-11-13 09:02:35 +0000557 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000558
559 return result;
560 }
561
562 // Now handle "real" floating types (i.e. float, double, long double).
563 bool LHSFloat = lhs->isRealFloatingType();
564 bool RHSFloat = rhs->isRealFloatingType();
565 if (LHSFloat || RHSFloat) {
566 // If we have two real floating types, convert the smaller operand
567 // to the bigger result.
568 if (LHSFloat && RHSFloat) {
569 int order = Context.getFloatingTypeOrder(lhs, rhs);
570 if (order > 0) {
571 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
572 return lhs;
573 }
574
575 assert(order < 0 && "illegal float comparison");
576 if (!isCompAssign)
577 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
578 return rhs;
579 }
580
581 // If we have an integer operand, the result is the real floating type.
582 if (LHSFloat) {
583 if (rhs->isIntegerType()) {
584 // Convert rhs to the lhs floating point type.
585 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
586 return lhs;
587 }
588
589 // Convert both sides to the appropriate complex float.
590 assert(rhs->isComplexIntegerType());
591 QualType result = Context.getComplexType(lhs);
592
593 // _Complex int -> _Complex float
John McCalld7646252010-11-14 08:17:51 +0000594 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000595
596 // float -> _Complex float
597 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000598 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000599
600 return result;
601 }
602
603 assert(RHSFloat);
604 if (lhs->isIntegerType()) {
605 // Convert lhs to the rhs floating point type.
606 if (!isCompAssign)
607 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
608 return rhs;
609 }
610
611 // Convert both sides to the appropriate complex float.
612 assert(lhs->isComplexIntegerType());
613 QualType result = Context.getComplexType(rhs);
614
615 // _Complex int -> _Complex float
616 if (!isCompAssign)
John McCalld7646252010-11-14 08:17:51 +0000617 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000618
619 // float -> _Complex float
John McCallc5e62b42010-11-13 09:02:35 +0000620 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000621
622 return result;
623 }
624
625 // Handle GCC complex int extension.
626 // FIXME: if the operands are (int, _Complex long), we currently
627 // don't promote the complex. Also, signedness?
628 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
629 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
630 if (lhsComplexInt && rhsComplexInt) {
631 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
632 rhsComplexInt->getElementType());
633 assert(order && "inequal types with equal element ordering");
634 if (order > 0) {
635 // _Complex int -> _Complex long
John McCallc5e62b42010-11-13 09:02:35 +0000636 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000637 return lhs;
638 }
639
640 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000641 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000642 return rhs;
643 } else if (lhsComplexInt) {
644 // int -> _Complex int
John McCallc5e62b42010-11-13 09:02:35 +0000645 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000646 return lhs;
647 } else if (rhsComplexInt) {
648 // int -> _Complex int
649 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000650 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000651 return rhs;
652 }
653
654 // Finally, we have two differing integer types.
655 // The rules for this case are in C99 6.3.1.8
656 int compare = Context.getIntegerTypeOrder(lhs, rhs);
657 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
658 rhsSigned = rhs->hasSignedIntegerRepresentation();
659 if (lhsSigned == rhsSigned) {
660 // Same signedness; use the higher-ranked type
661 if (compare >= 0) {
662 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
663 return lhs;
664 } else if (!isCompAssign)
665 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
666 return rhs;
667 } else if (compare != (lhsSigned ? 1 : -1)) {
668 // The unsigned type has greater than or equal rank to the
669 // signed type, so use the unsigned type
670 if (rhsSigned) {
671 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
672 return lhs;
673 } else if (!isCompAssign)
674 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
675 return rhs;
676 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
677 // The two types are different widths; if we are here, that
678 // means the signed type is larger than the unsigned type, so
679 // use the signed type.
680 if (lhsSigned) {
681 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
682 return lhs;
683 } else if (!isCompAssign)
684 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
685 return rhs;
686 } else {
687 // The signed type is higher-ranked than the unsigned type,
688 // but isn't actually any bigger (like unsigned int and long
689 // on most 32-bit systems). Use the unsigned type corresponding
690 // to the signed type.
691 QualType result =
692 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
693 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
694 if (!isCompAssign)
695 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
696 return result;
697 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000698}
699
Chris Lattner513165e2008-07-25 21:10:04 +0000700//===----------------------------------------------------------------------===//
701// Semantic Analysis for various Expression Types
702//===----------------------------------------------------------------------===//
703
704
Steve Naroff83895f72007-09-16 03:34:24 +0000705/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000706/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
707/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
708/// multiple tokens. However, the common case is that StringToks points to one
709/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000710///
John McCalldadc5752010-08-24 06:29:42 +0000711ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000712Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000713 assert(NumStringToks && "Must have at least one string!");
714
Chris Lattner8a24e582009-01-16 18:51:42 +0000715 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000716 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000717 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000718
Chris Lattner23b7eb62007-06-15 23:05:46 +0000719 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000720 for (unsigned i = 0; i != NumStringToks; ++i)
721 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000722
Chris Lattner36fc8792008-02-11 00:02:17 +0000723 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000724 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000725 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000726
727 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000728 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000729 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000730
Chris Lattner36fc8792008-02-11 00:02:17 +0000731 // Get an array type for the string, according to C99 6.4.5. This includes
732 // the nul terminator character as well as the string length for pascal
733 // strings.
734 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000735 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000736 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000737
Chris Lattner5b183d82006-11-10 05:03:26 +0000738 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000739 return Owned(StringLiteral::Create(Context, Literal.GetString(),
740 Literal.GetStringLength(),
741 Literal.AnyWide, StrTy,
742 &StringTokLocs[0],
743 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000744}
745
John McCallc63de662011-02-02 13:00:07 +0000746enum CaptureResult {
747 /// No capture is required.
748 CR_NoCapture,
749
750 /// A capture is required.
751 CR_Capture,
752
John McCall351762c2011-02-07 10:33:21 +0000753 /// A by-ref capture is required.
754 CR_CaptureByRef,
755
John McCallc63de662011-02-02 13:00:07 +0000756 /// An error occurred when trying to capture the given variable.
757 CR_Error
758};
759
760/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +0000761///
John McCallc63de662011-02-02 13:00:07 +0000762/// \param var - the variable referenced
763/// \param DC - the context which we couldn't capture through
764static CaptureResult
John McCall351762c2011-02-07 10:33:21 +0000765diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000766 VarDecl *var, DeclContext *DC) {
767 switch (S.ExprEvalContexts.back().Context) {
768 case Sema::Unevaluated:
769 // The argument will never be evaluated, so don't complain.
770 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +0000771
John McCallc63de662011-02-02 13:00:07 +0000772 case Sema::PotentiallyEvaluated:
773 case Sema::PotentiallyEvaluatedIfUsed:
774 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +0000775
John McCallc63de662011-02-02 13:00:07 +0000776 case Sema::PotentiallyPotentiallyEvaluated:
777 // FIXME: delay these!
778 break;
Chris Lattner497d7b02009-04-21 22:26:47 +0000779 }
Mike Stump11289f42009-09-09 15:08:12 +0000780
John McCallc63de662011-02-02 13:00:07 +0000781 // Don't diagnose about capture if we're not actually in code right
782 // now; in general, there are more appropriate places that will
783 // diagnose this.
784 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
785
786 // This particular madness can happen in ill-formed default
787 // arguments; claim it's okay and let downstream code handle it.
788 if (isa<ParmVarDecl>(var) &&
789 S.CurContext == var->getDeclContext()->getParent())
790 return CR_NoCapture;
791
792 DeclarationName functionName;
793 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
794 functionName = fn->getDeclName();
795 // FIXME: variable from enclosing block that we couldn't capture from!
796
797 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
798 << var->getIdentifier() << functionName;
799 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
800 << var->getIdentifier();
801
802 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +0000803}
804
John McCall351762c2011-02-07 10:33:21 +0000805/// There is a well-formed capture at a particular scope level;
806/// propagate it through all the nested blocks.
807static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
808 const BlockDecl::Capture &capture) {
809 VarDecl *var = capture.getVariable();
810
811 // Update all the inner blocks with the capture information.
812 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
813 i != e; ++i) {
814 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
815 innerBlock->Captures.push_back(
816 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
817 /*nested*/ true, capture.getCopyExpr()));
818 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
819 }
820
821 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
822}
823
824/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +0000825/// given value in the current context requires a variable capture.
826///
827/// This also keeps the captures set in the BlockScopeInfo records
828/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +0000829static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000830 ValueDecl *value) {
831 // Only variables ever require capture.
832 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +0000833 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +0000834
835 // Fast path: variables from the current context never require capture.
836 DeclContext *DC = S.CurContext;
837 if (var->getDeclContext() == DC) return CR_NoCapture;
838
839 // Only variables with local storage require capture.
840 // FIXME: What about 'const' variables in C++?
841 if (!var->hasLocalStorage()) return CR_NoCapture;
842
843 // Otherwise, we need to capture.
844
845 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +0000846 do {
847 // Only blocks (and eventually C++0x closures) can capture; other
848 // scopes don't work.
849 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +0000850 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +0000851
852 BlockScopeInfo *blockScope =
853 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
854 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
855
John McCall351762c2011-02-07 10:33:21 +0000856 // Check whether we've already captured it in this block. If so,
857 // we're done.
858 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
859 return propagateCapture(S, functionScopesIndex,
860 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +0000861
862 functionScopesIndex--;
863 DC = cast<BlockDecl>(DC)->getDeclContext();
864 } while (var->getDeclContext() != DC);
865
John McCall351762c2011-02-07 10:33:21 +0000866 // Okay, we descended all the way to the block that defines the variable.
867 // Actually try to capture it.
868 QualType type = var->getType();
869
870 // Prohibit variably-modified types.
871 if (type->isVariablyModifiedType()) {
872 S.Diag(loc, diag::err_ref_vm_type);
873 S.Diag(var->getLocation(), diag::note_declared_at);
874 return CR_Error;
875 }
876
877 // Prohibit arrays, even in __block variables, but not references to
878 // them.
879 if (type->isArrayType()) {
880 S.Diag(loc, diag::err_ref_array_type);
881 S.Diag(var->getLocation(), diag::note_declared_at);
882 return CR_Error;
883 }
884
885 S.MarkDeclarationReferenced(loc, var);
886
887 // The BlocksAttr indicates the variable is bound by-reference.
888 bool byRef = var->hasAttr<BlocksAttr>();
889
890 // Build a copy expression.
891 Expr *copyExpr = 0;
892 if (!byRef && S.getLangOptions().CPlusPlus &&
893 !type->isDependentType() && type->isStructureOrClassType()) {
894 // According to the blocks spec, the capture of a variable from
895 // the stack requires a const copy constructor. This is not true
896 // of the copy/move done to move a __block variable to the heap.
897 type.addConst();
898
899 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
900 ExprResult result =
901 S.PerformCopyInitialization(
902 InitializedEntity::InitializeBlock(var->getLocation(),
903 type, false),
904 loc, S.Owned(declRef));
905
906 // Build a full-expression copy expression if initialization
907 // succeeded and used a non-trivial constructor. Recover from
908 // errors by pretending that the copy isn't necessary.
909 if (!result.isInvalid() &&
910 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
911 result = S.MaybeCreateExprWithCleanups(result);
912 copyExpr = result.take();
913 }
914 }
915
916 // We're currently at the declarer; go back to the closure.
917 functionScopesIndex++;
918 BlockScopeInfo *blockScope =
919 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
920
921 // Build a valid capture in this scope.
922 blockScope->Captures.push_back(
923 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
924 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
925
926 // Propagate that to inner captures if necessary.
927 return propagateCapture(S, functionScopesIndex,
928 blockScope->Captures.back());
929}
930
931static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
932 const DeclarationNameInfo &NameInfo,
933 bool byRef) {
934 assert(isa<VarDecl>(vd) && "capturing non-variable");
935
936 VarDecl *var = cast<VarDecl>(vd);
937 assert(var->hasLocalStorage() && "capturing non-local");
938 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
939
940 QualType exprType = var->getType().getNonReferenceType();
941
942 BlockDeclRefExpr *BDRE;
943 if (!byRef) {
944 // The variable will be bound by copy; make it const within the
945 // closure, but record that this was done in the expression.
946 bool constAdded = !exprType.isConstQualified();
947 exprType.addConst();
948
949 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
950 NameInfo.getLoc(), false,
951 constAdded);
952 } else {
953 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
954 NameInfo.getLoc(), true);
955 }
956
957 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +0000958}
Chris Lattner2a9d9892008-10-20 05:16:36 +0000959
John McCalldadc5752010-08-24 06:29:42 +0000960ExprResult
John McCall7decc9e2010-11-18 06:31:45 +0000961Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +0000962 SourceLocation Loc,
963 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000964 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +0000965 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000966}
967
John McCallf4cd4f92011-02-09 01:13:10 +0000968/// BuildDeclRefExpr - Build an expression that references a
969/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +0000970ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +0000971Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000972 const DeclarationNameInfo &NameInfo,
973 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000974 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +0000975
John McCall086a4642010-11-24 05:12:34 +0000976 Expr *E = DeclRefExpr::Create(Context,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000977 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
John McCall086a4642010-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 Gregorc7acfdf2009-01-06 05:10:23 +0000986}
987
John McCallfeb624a2010-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 McCalldadc5752010-08-24 06:29:42 +0000994ExprResult
John McCallf3a88602011-02-03 08:15:49 +0000995Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
996 SourceLocation loc,
997 IndirectFieldDecl *indirectField,
998 Expr *baseObjectExpr,
999 SourceLocation opLoc) {
1000 // First, build the expression that refers to the base object.
1001
1002 bool baseObjectIsPointer = false;
1003 Qualifiers baseQuals;
1004
1005 // Case 1: the base of the indirect field is not a field.
1006 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregore10f36d2011-02-18 02:44:58 +00001007 CXXScopeSpec EmptySS;
John McCallf3a88602011-02-03 08:15:49 +00001008 if (baseVariable) {
1009 assert(baseVariable->getType()->isRecordType());
1010
1011 // In principle we could have a member access expression that
1012 // accesses an anonymous struct/union that's a static member of
1013 // the base object's class. However, under the current standard,
1014 // static data members cannot be anonymous structs or unions.
1015 // Supporting this is as easy as building a MemberExpr here.
1016 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1017
1018 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1019
1020 ExprResult result =
Douglas Gregore10f36d2011-02-18 02:44:58 +00001021 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCallf3a88602011-02-03 08:15:49 +00001022 if (result.isInvalid()) return ExprError();
1023
1024 baseObjectExpr = result.take();
1025 baseObjectIsPointer = false;
1026 baseQuals = baseObjectExpr->getType().getQualifiers();
1027
1028 // Case 2: the base of the indirect field is a field and the user
1029 // wrote a member expression.
1030 } else if (baseObjectExpr) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001031 // The caller provided the base object expression. Determine
1032 // whether its a pointer and whether it adds any qualifiers to the
1033 // anonymous struct/union fields we're looking into.
John McCallf3a88602011-02-03 08:15:49 +00001034 QualType objectType = baseObjectExpr->getType();
1035
1036 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1037 baseObjectIsPointer = true;
1038 objectType = ptr->getPointeeType();
1039 } else {
1040 baseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001041 }
John McCallf3a88602011-02-03 08:15:49 +00001042 baseQuals = objectType.getQualifiers();
1043
1044 // Case 3: the base of the indirect field is a field and we should
1045 // build an implicit member access.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001046 } else {
1047 // We've found a member of an anonymous struct/union that is
1048 // inside a non-anonymous struct/union, so in a well-formed
1049 // program our base object expression is "this".
John McCallf3a88602011-02-03 08:15:49 +00001050 CXXMethodDecl *method = tryCaptureCXXThis();
1051 if (!method) {
1052 Diag(loc, diag::err_invalid_member_use_in_static_method)
1053 << indirectField->getDeclName();
1054 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001055 }
1056
John McCallf3a88602011-02-03 08:15:49 +00001057 // Our base object expression is "this".
1058 baseObjectExpr =
1059 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1060 /*isImplicit=*/ true);
1061 baseObjectIsPointer = true;
1062 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001063 }
1064
1065 // Build the implicit member references to the field of the
1066 // anonymous struct/union.
John McCallf3a88602011-02-03 08:15:49 +00001067 Expr *result = baseObjectExpr;
1068 IndirectFieldDecl::chain_iterator
1069 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +00001070
John McCallf3a88602011-02-03 08:15:49 +00001071 // Build the first member access in the chain with full information.
1072 if (!baseVariable) {
1073 FieldDecl *field = cast<FieldDecl>(*FI);
John McCallfeb624a2010-11-23 20:48:44 +00001074
John McCallf3a88602011-02-03 08:15:49 +00001075 // FIXME: use the real found-decl info!
1076 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +00001077
John McCallf3a88602011-02-03 08:15:49 +00001078 // Make a nameInfo that properly uses the anonymous name.
1079 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall8ccfcb52009-09-24 19:53:00 +00001080
John McCallf3a88602011-02-03 08:15:49 +00001081 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001082 EmptySS, field, foundDecl,
John McCallf3a88602011-02-03 08:15:49 +00001083 memberNameInfo).take();
1084 baseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +00001085
John McCallf3a88602011-02-03 08:15:49 +00001086 // FIXME: check qualified member access
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001087 }
1088
John McCallf3a88602011-02-03 08:15:49 +00001089 // In all cases, we should now skip the first declaration in the chain.
1090 ++FI;
1091
Douglas Gregore10f36d2011-02-18 02:44:58 +00001092 while (FI != FEnd) {
1093 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCallf3a88602011-02-03 08:15:49 +00001094
1095 // FIXME: these are somewhat meaningless
1096 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1097 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCallf3a88602011-02-03 08:15:49 +00001098
1099 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001100 (FI == FEnd? SS : EmptySS), field,
1101 foundDecl, memberNameInfo)
John McCallf3a88602011-02-03 08:15:49 +00001102 .take();
1103 }
1104
1105 return Owned(result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001106}
1107
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001108/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001109/// possibly a list of template arguments.
1110///
1111/// If this produces template arguments, it is permitted to call
1112/// DecomposeTemplateName.
1113///
1114/// This actually loses a lot of source location information for
1115/// non-standard name kinds; we should consider preserving that in
1116/// some way.
1117static void DecomposeUnqualifiedId(Sema &SemaRef,
1118 const UnqualifiedId &Id,
1119 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001120 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00001121 const TemplateArgumentListInfo *&TemplateArgs) {
1122 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1123 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1124 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1125
1126 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1127 Id.TemplateId->getTemplateArgs(),
1128 Id.TemplateId->NumArgs);
1129 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1130 TemplateArgsPtr.release();
1131
John McCall3e56fd42010-08-23 07:28:44 +00001132 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001133 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1134 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001135 TemplateArgs = &Buffer;
1136 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001137 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001138 TemplateArgs = 0;
1139 }
1140}
1141
John McCall2d74de92009-12-01 22:10:20 +00001142/// Determines if the given class is provably not derived from all of
1143/// the prospective base classes.
1144static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1145 CXXRecordDecl *Record,
1146 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001147 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001148 return false;
1149
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001150 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001151 if (!RD) return false;
1152 Record = cast<CXXRecordDecl>(RD);
1153
John McCall2d74de92009-12-01 22:10:20 +00001154 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1155 E = Record->bases_end(); I != E; ++I) {
1156 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1157 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1158 if (!BaseRT) return false;
1159
1160 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001161 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1162 return false;
1163 }
1164
1165 return true;
1166}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001167
John McCall2d74de92009-12-01 22:10:20 +00001168enum IMAKind {
1169 /// The reference is definitely not an instance member access.
1170 IMA_Static,
1171
1172 /// The reference may be an implicit instance member access.
1173 IMA_Mixed,
1174
1175 /// The reference may be to an instance member, but it is invalid if
1176 /// so, because the context is not an instance method.
1177 IMA_Mixed_StaticContext,
1178
1179 /// The reference may be to an instance member, but it is invalid if
1180 /// so, because the context is from an unrelated class.
1181 IMA_Mixed_Unrelated,
1182
1183 /// The reference is definitely an implicit instance member access.
1184 IMA_Instance,
1185
1186 /// The reference may be to an unresolved using declaration.
1187 IMA_Unresolved,
1188
1189 /// The reference may be to an unresolved using declaration and the
1190 /// context is not an instance method.
1191 IMA_Unresolved_StaticContext,
1192
John McCall2d74de92009-12-01 22:10:20 +00001193 /// All possible referrents are instance members and the current
1194 /// context is not an instance method.
1195 IMA_Error_StaticContext,
1196
1197 /// All possible referrents are instance members of an unrelated
1198 /// class.
1199 IMA_Error_Unrelated
1200};
1201
1202/// The given lookup names class member(s) and is not being used for
1203/// an address-of-member expression. Classify the type of access
1204/// according to whether it's possible that this reference names an
1205/// instance member. This is best-effort; it is okay to
1206/// conservatively answer "yes", in which case some errors will simply
1207/// not be caught until template-instantiation.
1208static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1209 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001210 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001211
John McCall87fe5d52010-05-20 01:18:31 +00001212 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001213 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001214 (!isa<CXXMethodDecl>(DC) ||
1215 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001216
1217 if (R.isUnresolvableResult())
1218 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1219
1220 // Collect all the declaring classes of instance members we find.
1221 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001222 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001223 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1224 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001225 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001226
John McCalla8ae2222010-04-06 21:38:20 +00001227 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001228 if (dyn_cast<FieldDecl>(D))
1229 hasField = true;
1230
John McCall2d74de92009-12-01 22:10:20 +00001231 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001232 Classes.insert(R->getCanonicalDecl());
1233 }
1234 else
1235 hasNonInstance = true;
1236 }
1237
1238 // If we didn't find any instance members, it can't be an implicit
1239 // member reference.
1240 if (Classes.empty())
1241 return IMA_Static;
1242
1243 // If the current context is not an instance method, it can't be
1244 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001245 if (isStaticContext) {
1246 if (hasNonInstance)
1247 return IMA_Mixed_StaticContext;
1248
1249 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1250 // C++0x [expr.prim.general]p10:
1251 // An id-expression that denotes a non-static data member or non-static
1252 // member function of a class can only be used:
1253 // (...)
1254 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1255 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1256 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1257 if (isUnevaluatedExpression)
1258 return IMA_Mixed_StaticContext;
1259 }
1260
1261 return IMA_Error_StaticContext;
1262 }
John McCall2d74de92009-12-01 22:10:20 +00001263
1264 // If we can prove that the current context is unrelated to all the
1265 // declaring classes, it can't be an implicit member reference (in
1266 // which case it's an error if any of those members are selected).
1267 if (IsProvablyNotDerivedFrom(SemaRef,
John McCall87fe5d52010-05-20 01:18:31 +00001268 cast<CXXMethodDecl>(DC)->getParent(),
John McCall2d74de92009-12-01 22:10:20 +00001269 Classes))
1270 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1271
1272 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1273}
1274
1275/// Diagnose a reference to a field with no object available.
1276static void DiagnoseInstanceReference(Sema &SemaRef,
1277 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00001278 NamedDecl *rep,
1279 const DeclarationNameInfo &nameInfo) {
1280 SourceLocation Loc = nameInfo.getLoc();
John McCall2d74de92009-12-01 22:10:20 +00001281 SourceRange Range(Loc);
1282 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1283
John McCallf3a88602011-02-03 08:15:49 +00001284 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCall2d74de92009-12-01 22:10:20 +00001285 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1286 if (MD->isStatic()) {
1287 // "invalid use of member 'x' in static member function"
1288 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallf3a88602011-02-03 08:15:49 +00001289 << Range << nameInfo.getName();
John McCall2d74de92009-12-01 22:10:20 +00001290 return;
1291 }
1292 }
1293
1294 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallf3a88602011-02-03 08:15:49 +00001295 << nameInfo.getName() << Range;
John McCall2d74de92009-12-01 22:10:20 +00001296 return;
1297 }
1298
1299 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001300}
1301
John McCalld681c392009-12-16 08:11:27 +00001302/// Diagnose an empty lookup.
1303///
1304/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001305bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1306 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001307 DeclarationName Name = R.getLookupName();
1308
John McCalld681c392009-12-16 08:11:27 +00001309 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001310 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001311 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1312 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001313 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001314 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001315 diagnostic_suggest = diag::err_undeclared_use_suggest;
1316 }
John McCalld681c392009-12-16 08:11:27 +00001317
Douglas Gregor598b08f2009-12-31 05:20:13 +00001318 // If the original lookup was an unqualified lookup, fake an
1319 // unqualified lookup. This is useful when (for example) the
1320 // original lookup would not have found something because it was a
1321 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001322 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001323 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001324 if (isa<CXXRecordDecl>(DC)) {
1325 LookupQualifiedName(R, DC);
1326
1327 if (!R.empty()) {
1328 // Don't give errors about ambiguities in this lookup.
1329 R.suppressDiagnostics();
1330
1331 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1332 bool isInstance = CurMethod &&
1333 CurMethod->isInstance() &&
1334 DC == CurMethod->getParent();
1335
1336 // Give a code modification hint to insert 'this->'.
1337 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1338 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001339 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001340 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1341 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001342 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001343 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001344 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001345 Diag(R.getNameLoc(), diagnostic) << Name
1346 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1347 QualType DepThisType = DepMethod->getThisType(Context);
1348 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1349 R.getNameLoc(), DepThisType, false);
1350 TemplateArgumentListInfo TList;
1351 if (ULE->hasExplicitTemplateArgs())
1352 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001353
1354 // FIXME: We should have nested-name-specifier location info in
1355 // the ULE itself.
1356 CXXScopeSpec SS;
1357 SS.MakeTrivial(Context, ULE->getQualifier(),
1358 ULE->getQualifierRange());
1359
Nick Lewyckyfe712382010-08-20 20:54:15 +00001360 CXXDependentScopeMemberExpr *DepExpr =
1361 CXXDependentScopeMemberExpr::Create(
1362 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001363 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001364 R.getLookupNameInfo(), &TList);
1365 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001366 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001367 // FIXME: we should be able to handle this case too. It is correct
1368 // to add this-> here. This is a workaround for PR7947.
1369 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001370 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001371 } else {
John McCalld681c392009-12-16 08:11:27 +00001372 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001373 }
John McCalld681c392009-12-16 08:11:27 +00001374
1375 // Do we really want to note all of these?
1376 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1377 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1378
1379 // Tell the callee to try to recover.
1380 return false;
1381 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001382
1383 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001384 }
1385 }
1386
Douglas Gregor598b08f2009-12-31 05:20:13 +00001387 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001388 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001389 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001390 if (!R.empty()) {
1391 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1392 if (SS.isEmpty())
1393 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1394 << FixItHint::CreateReplacement(R.getNameLoc(),
1395 R.getLookupName().getAsString());
1396 else
1397 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1398 << Name << computeDeclContext(SS, false) << R.getLookupName()
1399 << SS.getRange()
1400 << FixItHint::CreateReplacement(R.getNameLoc(),
1401 R.getLookupName().getAsString());
1402 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1403 Diag(ND->getLocation(), diag::note_previous_decl)
1404 << ND->getDeclName();
1405
1406 // Tell the callee to try to recover.
1407 return false;
1408 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001409
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001410 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1411 // FIXME: If we ended up with a typo for a type name or
1412 // Objective-C class name, we're in trouble because the parser
1413 // is in the wrong place to recover. Suggest the typo
1414 // correction, but don't make it a fix-it since we're not going
1415 // to recover well anyway.
1416 if (SS.isEmpty())
1417 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1418 else
1419 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1420 << Name << computeDeclContext(SS, false) << R.getLookupName()
1421 << SS.getRange();
1422
1423 // Don't try to recover; it won't work.
1424 return true;
1425 }
1426 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001427 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001428 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001429 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001430 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001431 else
Douglas Gregor25363982010-01-01 00:15:04 +00001432 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001433 << Name << computeDeclContext(SS, false) << Corrected
1434 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001435 return true;
1436 }
Douglas Gregor25363982010-01-01 00:15:04 +00001437 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001438 }
1439
1440 // Emit a special diagnostic for failed member lookups.
1441 // FIXME: computing the declaration context might fail here (?)
1442 if (!SS.isEmpty()) {
1443 Diag(R.getNameLoc(), diag::err_no_member)
1444 << Name << computeDeclContext(SS, false)
1445 << SS.getRange();
1446 return true;
1447 }
1448
John McCalld681c392009-12-16 08:11:27 +00001449 // Give up, we can't recover.
1450 Diag(R.getNameLoc(), diagnostic) << Name;
1451 return true;
1452}
1453
Douglas Gregor05fcf842010-11-02 20:36:02 +00001454ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1455 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001456 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1457 if (!IDecl)
1458 return 0;
1459 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1460 if (!ClassImpDecl)
1461 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001462 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001463 if (!property)
1464 return 0;
1465 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001466 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1467 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001468 return 0;
1469 return property;
1470}
1471
Douglas Gregor05fcf842010-11-02 20:36:02 +00001472bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1473 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1474 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1475 if (!IDecl)
1476 return false;
1477 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1478 if (!ClassImpDecl)
1479 return false;
1480 if (ObjCPropertyImplDecl *PIDecl
1481 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1482 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1483 PIDecl->getPropertyIvarDecl())
1484 return false;
1485
1486 return true;
1487}
1488
Fariborz Jahanian18722982010-07-17 00:59:30 +00001489static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001490 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001491 IdentifierInfo *II,
1492 SourceLocation NameLoc) {
1493 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001494 bool LookForIvars;
1495 if (Lookup.empty())
1496 LookForIvars = true;
1497 else if (CurMeth->isClassMethod())
1498 LookForIvars = false;
1499 else
1500 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001501 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1502 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001503 if (!LookForIvars)
1504 return 0;
1505
Fariborz Jahanian18722982010-07-17 00:59:30 +00001506 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1507 if (!IDecl)
1508 return 0;
1509 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001510 if (!ClassImpDecl)
1511 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001512 bool DynamicImplSeen = false;
1513 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1514 if (!property)
1515 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001516 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001517 DynamicImplSeen =
1518 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001519 // property implementation has a designated ivar. No need to assume a new
1520 // one.
1521 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1522 return 0;
1523 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001524 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001525 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1526 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001527 NameLoc,
1528 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001529 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001530 (Expr *)0, true);
1531 ClassImpDecl->addDecl(Ivar);
1532 IDecl->makeDeclVisibleInContext(Ivar, false);
1533 property->setPropertyIvarDecl(Ivar);
1534 return Ivar;
1535 }
1536 return 0;
1537}
1538
John McCalldadc5752010-08-24 06:29:42 +00001539ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001540 CXXScopeSpec &SS,
1541 UnqualifiedId &Id,
1542 bool HasTrailingLParen,
1543 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001544 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1545 "cannot be direct & operand and have a trailing lparen");
1546
1547 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001548 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001549
John McCall10eae182009-11-30 22:42:35 +00001550 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001551
1552 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001553 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001554 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001555 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001556
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001557 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001558 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001559 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001560
John McCalle66edc12009-11-24 19:00:30 +00001561 // C++ [temp.dep.expr]p3:
1562 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001563 // -- an identifier that was declared with a dependent type,
1564 // (note: handled after lookup)
1565 // -- a template-id that is dependent,
1566 // (note: handled in BuildTemplateIdExpr)
1567 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001568 // -- a nested-name-specifier that contains a class-name that
1569 // names a dependent type.
1570 // Determine whether this is a member of an unknown specialization;
1571 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001572 bool DependentID = false;
1573 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1574 Name.getCXXNameType()->isDependentType()) {
1575 DependentID = true;
1576 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001577 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001578 if (RequireCompleteDeclContext(SS, DC))
1579 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001580 } else {
1581 DependentID = true;
1582 }
1583 }
1584
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001585 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001586 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001587 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001588
Fariborz Jahanian86151342010-07-22 23:33:21 +00001589 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001590 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001591 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001592 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001593 // Lookup the template name again to correctly establish the context in
1594 // which it was found. This is really unfortunate as we already did the
1595 // lookup to determine that it was a template name in the first place. If
1596 // this becomes a performance hit, we can work harder to preserve those
1597 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001598 bool MemberOfUnknownSpecialization;
1599 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1600 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001601
1602 if (MemberOfUnknownSpecialization ||
1603 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1604 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1605 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001606 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001607 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001608 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001609
Douglas Gregora5226932011-02-04 13:35:07 +00001610 // If the result might be in a dependent base class, this is a dependent
1611 // id-expression.
1612 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1613 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1614 TemplateArgs);
1615
John McCalle66edc12009-11-24 19:00:30 +00001616 // If this reference is in an Objective-C method, then we need to do
1617 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001618 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001619 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001620 if (E.isInvalid())
1621 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001622
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001623 if (Expr *Ex = E.takeAs<Expr>())
1624 return Owned(Ex);
1625
1626 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001627 if (getLangOptions().ObjCDefaultSynthProperties &&
1628 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001629 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1630 if (const ObjCPropertyDecl *Property =
1631 canSynthesizeProvisionalIvar(II)) {
1632 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1633 Diag(Property->getLocation(), diag::note_property_declare);
1634 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001635 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1636 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001637 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001638 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001639 // for further use, this must be set to false if in class method.
1640 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001641 }
Chris Lattner59a25942008-03-31 00:36:02 +00001642 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001643
John McCalle66edc12009-11-24 19:00:30 +00001644 if (R.isAmbiguous())
1645 return ExprError();
1646
Douglas Gregor171c45a2009-02-18 21:56:37 +00001647 // Determine whether this name might be a candidate for
1648 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001649 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001650
John McCalle66edc12009-11-24 19:00:30 +00001651 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001652 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001653 // in C90, extension in C99, forbidden in C++).
1654 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1655 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1656 if (D) R.addDecl(D);
1657 }
1658
1659 // If this name wasn't predeclared and if this is not a function
1660 // call, diagnose the problem.
1661 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001662 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001663 return ExprError();
1664
1665 assert(!R.empty() &&
1666 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001667
1668 // If we found an Objective-C instance variable, let
1669 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001670 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001671 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1672 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001673 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001674 assert(E.isInvalid() || E.get());
1675 return move(E);
1676 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001677 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001678 }
Mike Stump11289f42009-09-09 15:08:12 +00001679
John McCalle66edc12009-11-24 19:00:30 +00001680 // This is guaranteed from this point on.
1681 assert(!R.empty() || ADL);
1682
John McCall2d74de92009-12-01 22:10:20 +00001683 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001684 // C++ [class.mfct.non-static]p3:
1685 // When an id-expression that is not part of a class member access
1686 // syntax and not used to form a pointer to member is used in the
1687 // body of a non-static member function of class X, if name lookup
1688 // resolves the name in the id-expression to a non-static non-type
1689 // member of some class C, the id-expression is transformed into a
1690 // class member access expression using (*this) as the
1691 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001692 //
1693 // But we don't actually need to do this for '&' operands if R
1694 // resolved to a function or overloaded function set, because the
1695 // expression is ill-formed if it actually works out to be a
1696 // non-static member function:
1697 //
1698 // C++ [expr.ref]p4:
1699 // Otherwise, if E1.E2 refers to a non-static member function. . .
1700 // [t]he expression can be used only as the left-hand operand of a
1701 // member function call.
1702 //
1703 // There are other safeguards against such uses, but it's important
1704 // to get this right here so that we don't end up making a
1705 // spuriously dependent expression if we're inside a dependent
1706 // instance method.
John McCall57500772009-12-16 12:17:52 +00001707 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001708 bool MightBeImplicitMember;
1709 if (!isAddressOfOperand)
1710 MightBeImplicitMember = true;
1711 else if (!SS.isEmpty())
1712 MightBeImplicitMember = false;
1713 else if (R.isOverloadedResult())
1714 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001715 else if (R.isUnresolvableResult())
1716 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001717 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001718 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1719 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001720
1721 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001722 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001723 }
1724
John McCalle66edc12009-11-24 19:00:30 +00001725 if (TemplateArgs)
1726 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001727
John McCalle66edc12009-11-24 19:00:30 +00001728 return BuildDeclarationNameExpr(SS, R, ADL);
1729}
1730
John McCall57500772009-12-16 12:17:52 +00001731/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001732ExprResult
John McCall57500772009-12-16 12:17:52 +00001733Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1734 LookupResult &R,
1735 const TemplateArgumentListInfo *TemplateArgs) {
1736 switch (ClassifyImplicitMemberAccess(*this, R)) {
1737 case IMA_Instance:
1738 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1739
John McCall57500772009-12-16 12:17:52 +00001740 case IMA_Mixed:
1741 case IMA_Mixed_Unrelated:
1742 case IMA_Unresolved:
1743 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1744
1745 case IMA_Static:
1746 case IMA_Mixed_StaticContext:
1747 case IMA_Unresolved_StaticContext:
1748 if (TemplateArgs)
1749 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1750 return BuildDeclarationNameExpr(SS, R, false);
1751
1752 case IMA_Error_StaticContext:
1753 case IMA_Error_Unrelated:
John McCallf3a88602011-02-03 08:15:49 +00001754 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1755 R.getLookupNameInfo());
John McCall57500772009-12-16 12:17:52 +00001756 return ExprError();
1757 }
1758
1759 llvm_unreachable("unexpected instance member access kind");
1760 return ExprError();
1761}
1762
John McCall10eae182009-11-30 22:42:35 +00001763/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1764/// declaration name, generally during template instantiation.
1765/// There's a large number of things which don't need to be done along
1766/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001767ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001768Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001769 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001770 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001771 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001772 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001773
John McCall0b66eb32010-05-01 00:40:08 +00001774 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001775 return ExprError();
1776
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001777 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001778 LookupQualifiedName(R, DC);
1779
1780 if (R.isAmbiguous())
1781 return ExprError();
1782
1783 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001784 Diag(NameInfo.getLoc(), diag::err_no_member)
1785 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001786 return ExprError();
1787 }
1788
1789 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1790}
1791
1792/// LookupInObjCMethod - The parser has read a name in, and Sema has
1793/// detected that we're currently inside an ObjC method. Perform some
1794/// additional lookup.
1795///
1796/// Ideally, most of this would be done by lookup, but there's
1797/// actually quite a lot of extra work involved.
1798///
1799/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001800ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001801Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001802 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001803 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001804 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001805
John McCalle66edc12009-11-24 19:00:30 +00001806 // There are two cases to handle here. 1) scoped lookup could have failed,
1807 // in which case we should look for an ivar. 2) scoped lookup could have
1808 // found a decl, but that decl is outside the current instance method (i.e.
1809 // a global variable). In these two cases, we do a lookup for an ivar with
1810 // this name, if the lookup sucedes, we replace it our current decl.
1811
1812 // If we're in a class method, we don't normally want to look for
1813 // ivars. But if we don't find anything else, and there's an
1814 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001815 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001816
1817 bool LookForIvars;
1818 if (Lookup.empty())
1819 LookForIvars = true;
1820 else if (IsClassMethod)
1821 LookForIvars = false;
1822 else
1823 LookForIvars = (Lookup.isSingleResult() &&
1824 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001825 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001826 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001827 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001828 ObjCInterfaceDecl *ClassDeclared;
1829 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1830 // Diagnose using an ivar in a class method.
1831 if (IsClassMethod)
1832 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1833 << IV->getDeclName());
1834
1835 // If we're referencing an invalid decl, just return this as a silent
1836 // error node. The error diagnostic was already emitted on the decl.
1837 if (IV->isInvalidDecl())
1838 return ExprError();
1839
1840 // Check if referencing a field with __attribute__((deprecated)).
1841 if (DiagnoseUseOfDecl(IV, Loc))
1842 return ExprError();
1843
1844 // Diagnose the use of an ivar outside of the declaring class.
1845 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1846 ClassDeclared != IFace)
1847 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1848
1849 // FIXME: This should use a new expr for a direct reference, don't
1850 // turn this into Self->ivar, just return a BareIVarExpr or something.
1851 IdentifierInfo &II = Context.Idents.get("self");
1852 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001853 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001854 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001855 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001856 SelfName, false, false);
1857 if (SelfExpr.isInvalid())
1858 return ExprError();
1859
John McCall27584242010-12-06 20:48:59 +00001860 Expr *SelfE = SelfExpr.take();
1861 DefaultLvalueConversion(SelfE);
1862
John McCalle66edc12009-11-24 19:00:30 +00001863 MarkDeclarationReferenced(Loc, IV);
1864 return Owned(new (Context)
1865 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall27584242010-12-06 20:48:59 +00001866 SelfE, true, true));
John McCalle66edc12009-11-24 19:00:30 +00001867 }
Chris Lattner87313662010-04-12 05:10:17 +00001868 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001869 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001870 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001871 ObjCInterfaceDecl *ClassDeclared;
1872 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1873 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1874 IFace == ClassDeclared)
1875 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1876 }
1877 }
1878
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001879 if (Lookup.empty() && II && AllowBuiltinCreation) {
1880 // FIXME. Consolidate this with similar code in LookupName.
1881 if (unsigned BuiltinID = II->getBuiltinID()) {
1882 if (!(getLangOptions().CPlusPlus &&
1883 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1884 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1885 S, Lookup.isForRedeclaration(),
1886 Lookup.getNameLoc());
1887 if (D) Lookup.addDecl(D);
1888 }
1889 }
1890 }
John McCalle66edc12009-11-24 19:00:30 +00001891 // Sentinel value saying that we didn't do anything special.
1892 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001893}
John McCalld14a8642009-11-21 08:51:07 +00001894
John McCall16df1e52010-03-30 21:47:33 +00001895/// \brief Cast a base object to a member's actual type.
1896///
1897/// Logically this happens in three phases:
1898///
1899/// * First we cast from the base type to the naming class.
1900/// The naming class is the class into which we were looking
1901/// when we found the member; it's the qualifier type if a
1902/// qualifier was provided, and otherwise it's the base type.
1903///
1904/// * Next we cast from the naming class to the declaring class.
1905/// If the member we found was brought into a class's scope by
1906/// a using declaration, this is that class; otherwise it's
1907/// the class declaring the member.
1908///
1909/// * Finally we cast from the declaring class to the "true"
1910/// declaring class of the member. This conversion does not
1911/// obey access control.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001912bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001913Sema::PerformObjectMemberConversion(Expr *&From,
1914 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001915 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001916 NamedDecl *Member) {
1917 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1918 if (!RD)
1919 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001920
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001921 QualType DestRecordType;
1922 QualType DestType;
1923 QualType FromRecordType;
1924 QualType FromType = From->getType();
1925 bool PointerConversions = false;
1926 if (isa<FieldDecl>(Member)) {
1927 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001928
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001929 if (FromType->getAs<PointerType>()) {
1930 DestType = Context.getPointerType(DestRecordType);
1931 FromRecordType = FromType->getPointeeType();
1932 PointerConversions = true;
1933 } else {
1934 DestType = DestRecordType;
1935 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001936 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001937 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1938 if (Method->isStatic())
1939 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001940
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001941 DestType = Method->getThisType(Context);
1942 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001943
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001944 if (FromType->getAs<PointerType>()) {
1945 FromRecordType = FromType->getPointeeType();
1946 PointerConversions = true;
1947 } else {
1948 FromRecordType = FromType;
1949 DestType = DestRecordType;
1950 }
1951 } else {
1952 // No conversion necessary.
1953 return false;
1954 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001955
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001956 if (DestType->isDependentType() || FromType->isDependentType())
1957 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001958
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001959 // If the unqualified types are the same, no conversion is necessary.
1960 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1961 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001962
John McCall16df1e52010-03-30 21:47:33 +00001963 SourceRange FromRange = From->getSourceRange();
1964 SourceLocation FromLoc = FromRange.getBegin();
1965
John McCall2536c6d2010-08-25 10:28:54 +00001966 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001967
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001968 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001969 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001970 // class name.
1971 //
1972 // If the member was a qualified name and the qualified referred to a
1973 // specific base subobject type, we'll cast to that intermediate type
1974 // first and then to the object in which the member is declared. That allows
1975 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1976 //
1977 // class Base { public: int x; };
1978 // class Derived1 : public Base { };
1979 // class Derived2 : public Base { };
1980 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1981 //
1982 // void VeryDerived::f() {
1983 // x = 17; // error: ambiguous base subobjects
1984 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1985 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001986 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001987 QualType QType = QualType(Qualifier->getAsType(), 0);
1988 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1989 assert(QType->isRecordType() && "lookup done with non-record type");
1990
1991 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1992
1993 // In C++98, the qualifier type doesn't actually have to be a base
1994 // type of the object type, in which case we just ignore it.
1995 // Otherwise build the appropriate casts.
1996 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00001997 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001998 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001999 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00002000 return true;
2001
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002002 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002003 QType = Context.getPointerType(QType);
John McCall2536c6d2010-08-25 10:28:54 +00002004 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2005 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00002006
2007 FromType = QType;
2008 FromRecordType = QRecordType;
2009
2010 // If the qualifier type was the same as the destination type,
2011 // we're done.
2012 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2013 return false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002014 }
2015 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002016
John McCall16df1e52010-03-30 21:47:33 +00002017 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002018
John McCall16df1e52010-03-30 21:47:33 +00002019 // If we actually found the member through a using declaration, cast
2020 // down to the using declaration's type.
2021 //
2022 // Pointer equality is fine here because only one declaration of a
2023 // class ever has member declarations.
2024 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2025 assert(isa<UsingShadowDecl>(FoundDecl));
2026 QualType URecordType = Context.getTypeDeclType(
2027 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2028
2029 // We only need to do this if the naming-class to declaring-class
2030 // conversion is non-trivial.
2031 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2032 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002033 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002034 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002035 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00002036 return true;
Alexis Huntc46382e2010-04-28 23:02:27 +00002037
John McCall16df1e52010-03-30 21:47:33 +00002038 QualType UType = URecordType;
2039 if (PointerConversions)
2040 UType = Context.getPointerType(UType);
John McCalle3027922010-08-25 11:45:40 +00002041 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00002042 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00002043 FromType = UType;
2044 FromRecordType = URecordType;
2045 }
2046
2047 // We don't do access control for the conversion from the
2048 // declaring class to the true declaring class.
2049 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002050 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002051
John McCallcf142162010-08-07 06:22:56 +00002052 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002053 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2054 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002055 IgnoreAccess))
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002056 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002057
John McCalle3027922010-08-25 11:45:40 +00002058 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00002059 VK, &BasePath);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00002060 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002061}
Douglas Gregor3256d042009-06-30 15:47:41 +00002062
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002063/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00002064static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00002065 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00002066 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002067 const DeclarationNameInfo &MemberNameInfo,
2068 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00002069 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00002070 const TemplateArgumentListInfo *TemplateArgs = 0) {
2071 NestedNameSpecifier *Qualifier = 0;
2072 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00002073 if (SS.isSet()) {
2074 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
2075 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002076 }
Mike Stump11289f42009-09-09 15:08:12 +00002077
John McCalle66edc12009-11-24 19:00:30 +00002078 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002079 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002080 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00002081}
2082
John McCallfeb624a2010-11-23 20:48:44 +00002083static ExprResult
2084BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2085 const CXXScopeSpec &SS, FieldDecl *Field,
2086 DeclAccessPair FoundDecl,
2087 const DeclarationNameInfo &MemberNameInfo) {
2088 // x.a is an l-value if 'a' has a reference type. Otherwise:
2089 // x.a is an l-value/x-value/pr-value if the base is (and note
2090 // that *x is always an l-value), except that if the base isn't
2091 // an ordinary object then we must have an rvalue.
2092 ExprValueKind VK = VK_LValue;
2093 ExprObjectKind OK = OK_Ordinary;
2094 if (!IsArrow) {
2095 if (BaseExpr->getObjectKind() == OK_Ordinary)
2096 VK = BaseExpr->getValueKind();
2097 else
2098 VK = VK_RValue;
2099 }
2100 if (VK != VK_RValue && Field->isBitField())
2101 OK = OK_BitField;
2102
2103 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2104 QualType MemberType = Field->getType();
2105 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2106 MemberType = Ref->getPointeeType();
2107 VK = VK_LValue;
2108 } else {
2109 QualType BaseType = BaseExpr->getType();
2110 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2111
2112 Qualifiers BaseQuals = BaseType.getQualifiers();
2113
2114 // GC attributes are never picked up by members.
2115 BaseQuals.removeObjCGCAttr();
2116
2117 // CVR attributes from the base are picked up by members,
2118 // except that 'mutable' members don't pick up 'const'.
2119 if (Field->isMutable()) BaseQuals.removeConst();
2120
2121 Qualifiers MemberQuals
2122 = S.Context.getCanonicalType(MemberType).getQualifiers();
2123
2124 // TR 18037 does not allow fields to be declared with address spaces.
2125 assert(!MemberQuals.hasAddressSpace());
2126
2127 Qualifiers Combined = BaseQuals + MemberQuals;
2128 if (Combined != MemberQuals)
2129 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2130 }
2131
2132 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2133 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2134 FoundDecl, Field))
2135 return ExprError();
2136 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2137 Field, FoundDecl, MemberNameInfo,
2138 MemberType, VK, OK));
2139}
2140
John McCall2d74de92009-12-01 22:10:20 +00002141/// Builds an implicit member access expression. The current context
2142/// is known to be an instance method, and the given unqualified lookup
2143/// set is known to contain only instance members, at least one of which
2144/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002145ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002146Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2147 LookupResult &R,
2148 const TemplateArgumentListInfo *TemplateArgs,
2149 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002150 assert(!R.empty() && !R.isAmbiguous());
2151
John McCallf3a88602011-02-03 08:15:49 +00002152 SourceLocation loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002153
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002154 // We may have found a field within an anonymous union or struct
2155 // (C++ [class.union]).
John McCalle66edc12009-11-24 19:00:30 +00002156 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002157 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCallf3a88602011-02-03 08:15:49 +00002158 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002159
John McCallf3a88602011-02-03 08:15:49 +00002160 // If this is known to be an instance access, go ahead and build an
2161 // implicit 'this' expression now.
John McCall2d74de92009-12-01 22:10:20 +00002162 // 'this' expression now.
John McCallf3a88602011-02-03 08:15:49 +00002163 CXXMethodDecl *method = tryCaptureCXXThis();
2164 assert(method && "didn't correctly pre-flight capture of 'this'");
2165
2166 QualType thisType = method->getThisType(Context);
2167 Expr *baseExpr = 0; // null signifies implicit access
John McCall2d74de92009-12-01 22:10:20 +00002168 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002169 SourceLocation Loc = R.getNameLoc();
2170 if (SS.getRange().isValid())
2171 Loc = SS.getRange().getBegin();
John McCallf3a88602011-02-03 08:15:49 +00002172 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002173 }
2174
John McCallf3a88602011-02-03 08:15:49 +00002175 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCall2d74de92009-12-01 22:10:20 +00002176 /*OpLoc*/ SourceLocation(),
2177 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002178 SS,
2179 /*FirstQualifierInScope*/ 0,
2180 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002181}
2182
John McCalle66edc12009-11-24 19:00:30 +00002183bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002184 const LookupResult &R,
2185 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002186 // Only when used directly as the postfix-expression of a call.
2187 if (!HasTrailingLParen)
2188 return false;
2189
2190 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002191 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002192 return false;
2193
2194 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002195 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002196 return false;
2197
2198 // Turn off ADL when we find certain kinds of declarations during
2199 // normal lookup:
2200 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2201 NamedDecl *D = *I;
2202
2203 // C++0x [basic.lookup.argdep]p3:
2204 // -- a declaration of a class member
2205 // Since using decls preserve this property, we check this on the
2206 // original decl.
John McCall57500772009-12-16 12:17:52 +00002207 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002208 return false;
2209
2210 // C++0x [basic.lookup.argdep]p3:
2211 // -- a block-scope function declaration that is not a
2212 // using-declaration
2213 // NOTE: we also trigger this for function templates (in fact, we
2214 // don't check the decl type at all, since all other decl types
2215 // turn off ADL anyway).
2216 if (isa<UsingShadowDecl>(D))
2217 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2218 else if (D->getDeclContext()->isFunctionOrMethod())
2219 return false;
2220
2221 // C++0x [basic.lookup.argdep]p3:
2222 // -- a declaration that is neither a function or a function
2223 // template
2224 // And also for builtin functions.
2225 if (isa<FunctionDecl>(D)) {
2226 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2227
2228 // But also builtin functions.
2229 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2230 return false;
2231 } else if (!isa<FunctionTemplateDecl>(D))
2232 return false;
2233 }
2234
2235 return true;
2236}
2237
2238
John McCalld14a8642009-11-21 08:51:07 +00002239/// Diagnoses obvious problems with the use of the given declaration
2240/// as an expression. This is only actually called for lookups that
2241/// were not overloaded, and it doesn't promise that the declaration
2242/// will in fact be used.
2243static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2244 if (isa<TypedefDecl>(D)) {
2245 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2246 return true;
2247 }
2248
2249 if (isa<ObjCInterfaceDecl>(D)) {
2250 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2251 return true;
2252 }
2253
2254 if (isa<NamespaceDecl>(D)) {
2255 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2256 return true;
2257 }
2258
2259 return false;
2260}
2261
John McCalldadc5752010-08-24 06:29:42 +00002262ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002263Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002264 LookupResult &R,
2265 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002266 // If this is a single, fully-resolved result and we don't need ADL,
2267 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002268 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002269 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2270 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002271
2272 // We only need to check the declaration if there's exactly one
2273 // result, because in the overloaded case the results can only be
2274 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002275 if (R.isSingleResult() &&
2276 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002277 return ExprError();
2278
John McCall58cc69d2010-01-27 01:50:18 +00002279 // Otherwise, just build an unresolved lookup expression. Suppress
2280 // any lookup-related diagnostics; we'll hash these out later, when
2281 // we've picked a target.
2282 R.suppressDiagnostics();
2283
John McCalld14a8642009-11-21 08:51:07 +00002284 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002285 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00002286 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002287 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002288 NeedsADL, R.isOverloadedResult(),
2289 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002290
2291 return Owned(ULE);
2292}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002293
John McCalld14a8642009-11-21 08:51:07 +00002294/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002295ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002296Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002297 const DeclarationNameInfo &NameInfo,
2298 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002299 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002300 assert(!isa<FunctionTemplateDecl>(D) &&
2301 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002302
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002303 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002304 if (CheckDeclInExpr(*this, Loc, D))
2305 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002306
Douglas Gregore7488b92009-12-01 16:58:18 +00002307 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2308 // Specifically diagnose references to class templates that are missing
2309 // a template argument list.
2310 Diag(Loc, diag::err_template_decl_ref)
2311 << Template << SS.getRange();
2312 Diag(Template->getLocation(), diag::note_template_decl_here);
2313 return ExprError();
2314 }
2315
2316 // Make sure that we're referring to a value.
2317 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2318 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002319 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002320 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002321 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002322 return ExprError();
2323 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002324
Douglas Gregor171c45a2009-02-18 21:56:37 +00002325 // Check whether this declaration can be used. Note that we suppress
2326 // this check when we're going to perform argument-dependent lookup
2327 // on this function name, because this might not be the function
2328 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002329 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002330 return ExprError();
2331
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002332 // Only create DeclRefExpr's for valid Decl's.
2333 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002334 return ExprError();
2335
John McCallf3a88602011-02-03 08:15:49 +00002336 // Handle members of anonymous structs and unions. If we got here,
2337 // and the reference is to a class member indirect field, then this
2338 // must be the subject of a pointer-to-member expression.
2339 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2340 if (!indirectField->isCXXClassMember())
2341 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2342 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002343
Chris Lattner2a9d9892008-10-20 05:16:36 +00002344 // If the identifier reference is inside a block, and it refers to a value
2345 // that is outside the block, create a BlockDeclRefExpr instead of a
2346 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2347 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002348 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002349 // We do not do this for things like enum constants, global variables, etc,
2350 // as they do not get snapshotted.
2351 //
John McCall351762c2011-02-07 10:33:21 +00002352 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002353 case CR_Error:
2354 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002355
John McCallc63de662011-02-02 13:00:07 +00002356 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002357 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2358 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2359
2360 case CR_CaptureByRef:
2361 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2362 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002363
2364 case CR_NoCapture: {
2365 // If this reference is not in a block or if the referenced
2366 // variable is within the block, create a normal DeclRefExpr.
2367
2368 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002369 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002370
2371 switch (D->getKind()) {
2372 // Ignore all the non-ValueDecl kinds.
2373#define ABSTRACT_DECL(kind)
2374#define VALUE(type, base)
2375#define DECL(type, base) \
2376 case Decl::type:
2377#include "clang/AST/DeclNodes.inc"
2378 llvm_unreachable("invalid value decl kind");
2379 return ExprError();
2380
2381 // These shouldn't make it here.
2382 case Decl::ObjCAtDefsField:
2383 case Decl::ObjCIvar:
2384 llvm_unreachable("forming non-member reference to ivar?");
2385 return ExprError();
2386
2387 // Enum constants are always r-values and never references.
2388 // Unresolved using declarations are dependent.
2389 case Decl::EnumConstant:
2390 case Decl::UnresolvedUsingValue:
2391 valueKind = VK_RValue;
2392 break;
2393
2394 // Fields and indirect fields that got here must be for
2395 // pointer-to-member expressions; we just call them l-values for
2396 // internal consistency, because this subexpression doesn't really
2397 // exist in the high-level semantics.
2398 case Decl::Field:
2399 case Decl::IndirectField:
2400 assert(getLangOptions().CPlusPlus &&
2401 "building reference to field in C?");
2402
2403 // These can't have reference type in well-formed programs, but
2404 // for internal consistency we do this anyway.
2405 type = type.getNonReferenceType();
2406 valueKind = VK_LValue;
2407 break;
2408
2409 // Non-type template parameters are either l-values or r-values
2410 // depending on the type.
2411 case Decl::NonTypeTemplateParm: {
2412 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2413 type = reftype->getPointeeType();
2414 valueKind = VK_LValue; // even if the parameter is an r-value reference
2415 break;
2416 }
2417
2418 // For non-references, we need to strip qualifiers just in case
2419 // the template parameter was declared as 'const int' or whatever.
2420 valueKind = VK_RValue;
2421 type = type.getUnqualifiedType();
2422 break;
2423 }
2424
2425 case Decl::Var:
2426 // In C, "extern void blah;" is valid and is an r-value.
2427 if (!getLangOptions().CPlusPlus &&
2428 !type.hasQualifiers() &&
2429 type->isVoidType()) {
2430 valueKind = VK_RValue;
2431 break;
2432 }
2433 // fallthrough
2434
2435 case Decl::ImplicitParam:
2436 case Decl::ParmVar:
2437 // These are always l-values.
2438 valueKind = VK_LValue;
2439 type = type.getNonReferenceType();
2440 break;
2441
2442 case Decl::Function: {
2443 // Functions are l-values in C++.
2444 if (getLangOptions().CPlusPlus) {
2445 valueKind = VK_LValue;
2446 break;
2447 }
2448
2449 // C99 DR 316 says that, if a function type comes from a
2450 // function definition (without a prototype), that type is only
2451 // used for checking compatibility. Therefore, when referencing
2452 // the function, we pretend that we don't have the full function
2453 // type.
2454 if (!cast<FunctionDecl>(VD)->hasPrototype())
2455 if (const FunctionProtoType *proto = type->getAs<FunctionProtoType>())
2456 type = Context.getFunctionNoProtoType(proto->getResultType(),
2457 proto->getExtInfo());
2458
2459 // Functions are r-values in C.
2460 valueKind = VK_RValue;
2461 break;
2462 }
2463
2464 case Decl::CXXMethod:
2465 // C++ methods are l-values if static, r-values if non-static.
2466 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2467 valueKind = VK_LValue;
2468 break;
2469 }
2470 // fallthrough
2471
2472 case Decl::CXXConversion:
2473 case Decl::CXXDestructor:
2474 case Decl::CXXConstructor:
2475 valueKind = VK_RValue;
2476 break;
2477 }
2478
2479 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2480 }
2481
John McCallc63de662011-02-02 13:00:07 +00002482 }
John McCall7decc9e2010-11-18 06:31:45 +00002483
John McCall351762c2011-02-07 10:33:21 +00002484 llvm_unreachable("unknown capture result");
2485 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002486}
Chris Lattnere168f762006-11-10 05:29:30 +00002487
John McCalldadc5752010-08-24 06:29:42 +00002488ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlffbcf962009-01-18 18:53:16 +00002489 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002490 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002491
Chris Lattnere168f762006-11-10 05:29:30 +00002492 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002493 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002494 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2495 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2496 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002497 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002498
Chris Lattnera81a0272008-01-12 08:14:25 +00002499 // Pre-defined identifiers are of type char[x], where x is the length of the
2500 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002501
Anders Carlsson2fb08242009-09-08 18:24:21 +00002502 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002503 if (!currentDecl && getCurBlock())
2504 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002505 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002506 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002507 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002508 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002509
Anders Carlsson0b209a82009-09-11 01:22:35 +00002510 QualType ResTy;
2511 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2512 ResTy = Context.DependentTy;
2513 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002514 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002515
Anders Carlsson0b209a82009-09-11 01:22:35 +00002516 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002517 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002518 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2519 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002520 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002521}
2522
John McCalldadc5752010-08-24 06:29:42 +00002523ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002524 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002525 bool Invalid = false;
2526 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2527 if (Invalid)
2528 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002529
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002530 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2531 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002532 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002533 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002534
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002535 QualType Ty;
2536 if (!getLangOptions().CPlusPlus)
2537 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2538 else if (Literal.isWide())
2539 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002540 else if (Literal.isMultiChar())
2541 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002542 else
2543 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002544
Sebastian Redl20614a72009-01-20 22:23:13 +00002545 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2546 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002547 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002548}
2549
John McCalldadc5752010-08-24 06:29:42 +00002550ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002551 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002552 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2553 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002554 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002555 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002556 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002557 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002558 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002559
Chris Lattner23b7eb62007-06-15 23:05:46 +00002560 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002561 // Add padding so that NumericLiteralParser can overread by one character.
2562 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002563 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002564
Chris Lattner67ca9252007-05-21 01:08:44 +00002565 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002566 bool Invalid = false;
2567 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2568 if (Invalid)
2569 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002570
Mike Stump11289f42009-09-09 15:08:12 +00002571 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002572 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002573 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002574 return ExprError();
2575
Chris Lattner1c20a172007-08-26 03:42:43 +00002576 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002577
Chris Lattner1c20a172007-08-26 03:42:43 +00002578 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002579 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002580 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002581 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002582 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002583 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002584 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002585 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002586
2587 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2588
John McCall53b93a02009-12-24 09:08:04 +00002589 using llvm::APFloat;
2590 APFloat Val(Format);
2591
2592 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002593
2594 // Overflow is always an error, but underflow is only an error if
2595 // we underflowed to zero (APFloat reports denormals as underflow).
2596 if ((result & APFloat::opOverflow) ||
2597 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002598 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002599 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002600 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002601 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002602 APFloat::getLargest(Format).toString(buffer);
2603 } else {
John McCall62abc942010-02-26 23:35:57 +00002604 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002605 APFloat::getSmallest(Format).toString(buffer);
2606 }
2607
2608 Diag(Tok.getLocation(), diagnostic)
2609 << Ty
2610 << llvm::StringRef(buffer.data(), buffer.size());
2611 }
2612
2613 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002614 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002615
Peter Collingbourne0b69e1a2010-12-04 01:50:56 +00002616 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2617 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2618
Chris Lattner1c20a172007-08-26 03:42:43 +00002619 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002620 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002621 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002622 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002623
Neil Boothac582c52007-08-29 22:00:19 +00002624 // long long is a C99 feature.
2625 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002626 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002627 Diag(Tok.getLocation(), diag::ext_longlong);
2628
Chris Lattner67ca9252007-05-21 01:08:44 +00002629 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002630 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002631
Chris Lattner67ca9252007-05-21 01:08:44 +00002632 if (Literal.GetIntegerValue(ResultVal)) {
2633 // If this value didn't fit into uintmax_t, warn and force to ull.
2634 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002635 Ty = Context.UnsignedLongLongTy;
2636 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002637 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002638 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002639 // If this value fits into a ULL, try to figure out what else it fits into
2640 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002641
Chris Lattner67ca9252007-05-21 01:08:44 +00002642 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2643 // be an unsigned int.
2644 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2645
2646 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002647 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002648 if (!Literal.isLong && !Literal.isLongLong) {
2649 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002650 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002651
Chris Lattner67ca9252007-05-21 01:08:44 +00002652 // Does it fit in a unsigned int?
2653 if (ResultVal.isIntN(IntSize)) {
2654 // Does it fit in a signed int?
2655 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002656 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002657 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002658 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002659 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002660 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002661 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002662
Chris Lattner67ca9252007-05-21 01:08:44 +00002663 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002664 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002665 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002666
Chris Lattner67ca9252007-05-21 01:08:44 +00002667 // Does it fit in a unsigned long?
2668 if (ResultVal.isIntN(LongSize)) {
2669 // Does it fit in a signed long?
2670 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002671 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002672 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002673 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002674 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002675 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002676 }
2677
Chris Lattner67ca9252007-05-21 01:08:44 +00002678 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002679 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002680 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002681
Chris Lattner67ca9252007-05-21 01:08:44 +00002682 // Does it fit in a unsigned long long?
2683 if (ResultVal.isIntN(LongLongSize)) {
2684 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002685 // To be compatible with MSVC, hex integer literals ending with the
2686 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002687 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2688 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002689 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002690 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002691 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002692 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002693 }
2694 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002695
Chris Lattner67ca9252007-05-21 01:08:44 +00002696 // If we still couldn't decide a type, we probably have something that
2697 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002698 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002699 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002700 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002701 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002702 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002703
Chris Lattner55258cf2008-05-09 05:59:00 +00002704 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002705 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002706 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002707 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002708 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002709
Chris Lattner1c20a172007-08-26 03:42:43 +00002710 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2711 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002712 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002713 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002714
2715 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002716}
2717
John McCalldadc5752010-08-24 06:29:42 +00002718ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002719 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002720 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002721 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002722}
2723
Steve Naroff71b59a92007-06-04 22:22:31 +00002724/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002725/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002726bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00002727 SourceLocation OpLoc,
John McCall36e7fe32010-10-12 00:20:44 +00002728 SourceRange ExprRange,
Sebastian Redl6f282892008-11-11 17:56:53 +00002729 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002730 if (exprType->isDependentType())
2731 return false;
2732
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002733 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2734 // the result is the size of the referenced type."
2735 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2736 // result shall be the alignment of the referenced type."
2737 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2738 exprType = Ref->getPointeeType();
2739
Steve Naroff043d45d2007-05-15 02:32:35 +00002740 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002741 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002742 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002743 if (isSizeof)
2744 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2745 return false;
2746 }
Mike Stump11289f42009-09-09 15:08:12 +00002747
Chris Lattner62975a72009-04-24 00:30:45 +00002748 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002749 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002750 Diag(OpLoc, diag::ext_sizeof_void_type)
2751 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002752 return false;
2753 }
Mike Stump11289f42009-09-09 15:08:12 +00002754
Chris Lattner62975a72009-04-24 00:30:45 +00002755 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002756 PDiag(diag::err_sizeof_alignof_incomplete_type)
2757 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002758 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002759
Chris Lattner62975a72009-04-24 00:30:45 +00002760 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002761 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002762 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002763 << exprType << isSizeof << ExprRange;
2764 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002765 }
Mike Stump11289f42009-09-09 15:08:12 +00002766
Chris Lattner62975a72009-04-24 00:30:45 +00002767 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002768}
2769
John McCall36e7fe32010-10-12 00:20:44 +00002770static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2771 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002772 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002773
Mike Stump11289f42009-09-09 15:08:12 +00002774 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002775 if (isa<DeclRefExpr>(E))
2776 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002777
2778 // Cannot know anything else if the expression is dependent.
2779 if (E->isTypeDependent())
2780 return false;
2781
Douglas Gregor71235ec2009-05-02 02:18:30 +00002782 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00002783 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00002784 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002785 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002786
2787 // Alignment of a field access is always okay, so long as it isn't a
2788 // bit-field.
2789 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002790 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002791 return false;
2792
John McCall36e7fe32010-10-12 00:20:44 +00002793 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
Chris Lattner8dff0172009-01-24 20:17:12 +00002794}
2795
Douglas Gregor0950e412009-03-13 21:01:28 +00002796/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002797ExprResult
John McCallbcd03502009-12-07 02:54:59 +00002798Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00002799 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002800 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002801 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002802 return ExprError();
2803
John McCallbcd03502009-12-07 02:54:59 +00002804 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002805
Douglas Gregor0950e412009-03-13 21:01:28 +00002806 if (!T->isDependentType() &&
2807 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2808 return ExprError();
2809
2810 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00002811 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00002812 Context.getSizeType(), OpLoc,
2813 R.getEnd()));
2814}
2815
2816/// \brief Build a sizeof or alignof expression given an expression
2817/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002818ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00002819Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002820 bool isSizeOf, SourceRange R) {
2821 // Verify that the operand is valid.
2822 bool isInvalid = false;
2823 if (E->isTypeDependent()) {
2824 // Delay type-checking for type-dependent expressions.
2825 } else if (!isSizeOf) {
John McCall36e7fe32010-10-12 00:20:44 +00002826 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002827 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002828 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2829 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00002830 } else if (E->getType()->isPlaceholderType()) {
2831 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2832 if (PE.isInvalid()) return ExprError();
2833 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00002834 } else {
2835 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2836 }
2837
2838 if (isInvalid)
2839 return ExprError();
2840
2841 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2842 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2843 Context.getSizeType(), OpLoc,
2844 R.getEnd()));
2845}
2846
Sebastian Redl6f282892008-11-11 17:56:53 +00002847/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2848/// the same for @c alignof and @c __alignof
2849/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002850ExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00002851Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2852 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002853 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002854 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002855
Sebastian Redl6f282892008-11-11 17:56:53 +00002856 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002857 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002858 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
John McCallbcd03502009-12-07 02:54:59 +00002859 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002860 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002861
Douglas Gregor0950e412009-03-13 21:01:28 +00002862 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00002863 ExprResult Result
Douglas Gregor0950e412009-03-13 21:01:28 +00002864 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2865
Douglas Gregor0950e412009-03-13 21:01:28 +00002866 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002867}
2868
John McCall4bc41ae2010-11-18 19:01:18 +00002869static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2870 bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002871 if (V->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002872 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002873
John McCall34376a62010-12-04 03:47:34 +00002874 // _Real and _Imag are only l-values for normal l-values.
2875 if (V->getObjectKind() != OK_Ordinary)
John McCall27584242010-12-06 20:48:59 +00002876 S.DefaultLvalueConversion(V);
John McCall34376a62010-12-04 03:47:34 +00002877
Chris Lattnere267f5d2007-08-26 05:39:26 +00002878 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00002879 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002880 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002881
Chris Lattnere267f5d2007-08-26 05:39:26 +00002882 // Otherwise they pass through real integer and floating point types here.
2883 if (V->getType()->isArithmeticType())
2884 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002885
John McCall36226622010-10-12 02:09:17 +00002886 // Test for placeholders.
John McCall4bc41ae2010-11-18 19:01:18 +00002887 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall36226622010-10-12 02:09:17 +00002888 if (PR.isInvalid()) return QualType();
2889 if (PR.take() != V) {
2890 V = PR.take();
John McCall4bc41ae2010-11-18 19:01:18 +00002891 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002892 }
2893
Chris Lattnere267f5d2007-08-26 05:39:26 +00002894 // Reject anything else.
John McCall4bc41ae2010-11-18 19:01:18 +00002895 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002896 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002897 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002898}
2899
2900
Chris Lattnere168f762006-11-10 05:29:30 +00002901
John McCalldadc5752010-08-24 06:29:42 +00002902ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002903Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002904 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002905 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002906 switch (Kind) {
2907 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002908 case tok::plusplus: Opc = UO_PostInc; break;
2909 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002910 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002911
John McCallb268a282010-08-23 23:25:46 +00002912 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002913}
2914
John McCall4bc41ae2010-11-18 19:01:18 +00002915/// Expressions of certain arbitrary types are forbidden by C from
2916/// having l-value type. These are:
2917/// - 'void', but not qualified void
2918/// - function types
2919///
2920/// The exact rule here is C99 6.3.2.1:
2921/// An lvalue is an expression with an object type or an incomplete
2922/// type other than void.
2923static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2924 return ((T->isVoidType() && !T.hasQualifiers()) ||
2925 T->isFunctionType());
2926}
2927
John McCalldadc5752010-08-24 06:29:42 +00002928ExprResult
John McCallb268a282010-08-23 23:25:46 +00002929Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2930 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002931 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002932 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002933 if (Result.isInvalid()) return ExprError();
2934 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002935
John McCallb268a282010-08-23 23:25:46 +00002936 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002937
Douglas Gregor40412ac2008-11-19 17:17:41 +00002938 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002939 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002940 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002941 Context.DependentTy,
2942 VK_LValue, OK_Ordinary,
2943 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002944 }
2945
Mike Stump11289f42009-09-09 15:08:12 +00002946 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002947 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002948 LHSExp->getType()->isEnumeralType() ||
2949 RHSExp->getType()->isRecordType() ||
2950 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002951 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002952 }
2953
John McCallb268a282010-08-23 23:25:46 +00002954 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002955}
2956
2957
John McCalldadc5752010-08-24 06:29:42 +00002958ExprResult
John McCallb268a282010-08-23 23:25:46 +00002959Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2960 Expr *Idx, SourceLocation RLoc) {
2961 Expr *LHSExp = Base;
2962 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002963
Chris Lattner36d572b2007-07-16 00:14:47 +00002964 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002965 if (!LHSExp->getType()->getAs<VectorType>())
2966 DefaultFunctionArrayLvalueConversion(LHSExp);
2967 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002968
Chris Lattner36d572b2007-07-16 00:14:47 +00002969 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00002970 ExprValueKind VK = VK_LValue;
2971 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00002972
Steve Naroffc1aadb12007-03-28 21:49:40 +00002973 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002974 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002975 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002976 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002977 Expr *BaseExpr, *IndexExpr;
2978 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002979 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2980 BaseExpr = LHSExp;
2981 IndexExpr = RHSExp;
2982 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002983 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002984 BaseExpr = LHSExp;
2985 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002986 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002987 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002988 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002989 BaseExpr = RHSExp;
2990 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002991 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002992 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002993 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002994 BaseExpr = LHSExp;
2995 IndexExpr = RHSExp;
2996 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002997 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002998 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002999 // Handle the uncommon case of "123[Ptr]".
3000 BaseExpr = RHSExp;
3001 IndexExpr = LHSExp;
3002 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003003 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003004 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003005 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003006 VK = LHSExp->getValueKind();
3007 if (VK != VK_RValue)
3008 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003009
Chris Lattner36d572b2007-07-16 00:14:47 +00003010 // FIXME: need to deal with const...
3011 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003012 } else if (LHSTy->isArrayType()) {
3013 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003014 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003015 // wasn't promoted because of the C90 rule that doesn't
3016 // allow promoting non-lvalue arrays. Warn, then
3017 // force the promotion here.
3018 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3019 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003020 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCalle3027922010-08-25 11:45:40 +00003021 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00003022 LHSTy = LHSExp->getType();
3023
3024 BaseExpr = LHSExp;
3025 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003026 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003027 } else if (RHSTy->isArrayType()) {
3028 // Same as previous, except for 123[f().a] case
3029 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3030 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003031 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCalle3027922010-08-25 11:45:40 +00003032 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00003033 RHSTy = RHSExp->getType();
3034
3035 BaseExpr = RHSExp;
3036 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003037 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003038 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003039 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3040 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003041 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003042 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003043 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003044 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3045 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003046
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003047 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003048 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3049 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003050 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3051
Douglas Gregorac1fb652009-03-24 19:52:54 +00003052 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003053 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3054 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003055 // incomplete types are not object types.
3056 if (ResultType->isFunctionType()) {
3057 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3058 << ResultType << BaseExpr->getSourceRange();
3059 return ExprError();
3060 }
Mike Stump11289f42009-09-09 15:08:12 +00003061
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003062 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3063 // GNU extension: subscripting on pointer to void
3064 Diag(LLoc, diag::ext_gnu_void_ptr)
3065 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003066
3067 // C forbids expressions of unqualified void type from being l-values.
3068 // See IsCForbiddenLValueType.
3069 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003070 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003071 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003072 PDiag(diag::err_subscript_incomplete_type)
3073 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003074 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003075
Chris Lattner62975a72009-04-24 00:30:45 +00003076 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003077 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003078 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3079 << ResultType << BaseExpr->getSourceRange();
3080 return ExprError();
3081 }
Mike Stump11289f42009-09-09 15:08:12 +00003082
John McCall4bc41ae2010-11-18 19:01:18 +00003083 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3084 !IsCForbiddenLValueType(Context, ResultType));
3085
Mike Stump4e1f26a2009-02-19 03:04:26 +00003086 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003087 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003088}
3089
John McCall4bc41ae2010-11-18 19:01:18 +00003090/// Check an ext-vector component access expression.
3091///
3092/// VK should be set in advance to the value kind of the base
3093/// expression.
3094static QualType
3095CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3096 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00003097 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00003098 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3099 // see FIXME there.
3100 //
3101 // FIXME: This logic can be greatly simplified by splitting it along
3102 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00003103 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00003104
Steve Narofff8fd09e2007-07-27 22:15:19 +00003105 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003106 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003107
Mike Stump4e1f26a2009-02-19 03:04:26 +00003108 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00003109 // special names that indicate a subset of exactly half the elements are
3110 // to be selected.
3111 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003112
Nate Begemanbb70bf62009-01-18 01:47:54 +00003113 // This flag determines whether or not CompName has an 's' char prefix,
3114 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00003115 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00003116
John McCall4bc41ae2010-11-18 19:01:18 +00003117 bool HasRepeated = false;
3118 bool HasIndex[16] = {};
3119
3120 int Idx;
3121
Nate Begemanf322eab2008-05-09 06:41:27 +00003122 // Check that we've found one of the special components, or that the component
3123 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003124 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00003125 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3126 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00003127 } else if (!HexSwizzle &&
3128 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3129 do {
3130 if (HasIndex[Idx]) HasRepeated = true;
3131 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003132 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003133 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3134 } else {
3135 if (HexSwizzle) compStr++;
3136 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3137 if (HasIndex[Idx]) HasRepeated = true;
3138 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003139 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003140 }
Chris Lattner7e152db2007-08-02 22:33:49 +00003141 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00003142
Mike Stump4e1f26a2009-02-19 03:04:26 +00003143 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00003144 // We didn't get to the end of the string. This means the component names
3145 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00003146 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003147 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00003148 return QualType();
3149 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003150
Nate Begemanbb70bf62009-01-18 01:47:54 +00003151 // Ensure no component accessor exceeds the width of the vector type it
3152 // operates on.
3153 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003154 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003155
3156 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00003157 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00003158
3159 while (*compStr) {
3160 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00003161 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00003162 << baseType << SourceRange(CompLoc);
3163 return QualType();
3164 }
3165 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00003166 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003167
Steve Narofff8fd09e2007-07-27 22:15:19 +00003168 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003169 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00003170 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00003171 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00003172 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00003173 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00003174 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003175 if (HexSwizzle)
3176 CompSize--;
3177
Steve Narofff8fd09e2007-07-27 22:15:19 +00003178 if (CompSize == 1)
3179 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003180
John McCall4bc41ae2010-11-18 19:01:18 +00003181 if (HasRepeated) VK = VK_RValue;
3182
3183 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003184 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003185 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003186 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3187 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3188 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003189 }
3190 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003191}
3192
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003193static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003194 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003195 const Selector &Sel,
3196 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003197 if (Member)
3198 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3199 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003200 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003201 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003202
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003203 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3204 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003205 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3206 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003207 return D;
3208 }
3209 return 0;
3210}
3211
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003212static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3213 IdentifierInfo *Member,
3214 const Selector &Sel,
3215 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003216 // Check protocols on qualified interfaces.
3217 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003218 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003219 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003220 if (Member)
3221 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3222 GDecl = PD;
3223 break;
3224 }
3225 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003226 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003227 GDecl = OMD;
3228 break;
3229 }
3230 }
3231 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003232 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003233 E = QIdTy->qual_end(); I != E; ++I) {
3234 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003235 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3236 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003237 if (GDecl)
3238 return GDecl;
3239 }
3240 }
3241 return GDecl;
3242}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003243
John McCalldadc5752010-08-24 06:29:42 +00003244ExprResult
John McCallb268a282010-08-23 23:25:46 +00003245Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003246 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003247 const CXXScopeSpec &SS,
3248 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003249 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003250 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003251 // Even in dependent contexts, try to diagnose base expressions with
3252 // obviously wrong types, e.g.:
3253 //
3254 // T* t;
3255 // t.f;
3256 //
3257 // In Obj-C++, however, the above expression is valid, since it could be
3258 // accessing the 'f' property if T is an Obj-C interface. The extra check
3259 // allows this, while still reporting an error if T is a struct pointer.
3260 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003261 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003262 if (PT && (!getLangOptions().ObjC1 ||
3263 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003264 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003265 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003266 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003267 return ExprError();
3268 }
3269 }
3270
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003271 assert(BaseType->isDependentType() ||
3272 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003273 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003274
3275 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3276 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003277 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003278 IsArrow, OpLoc,
Douglas Gregore16af532011-02-28 18:50:33 +00003279 SS.getWithLocInContext(Context),
John McCall10eae182009-11-30 22:42:35 +00003280 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003281 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003282}
3283
3284/// We know that the given qualified member reference points only to
3285/// declarations which do not belong to the static type of the base
3286/// expression. Diagnose the problem.
3287static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3288 Expr *BaseExpr,
3289 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003290 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00003291 NamedDecl *rep,
3292 const DeclarationNameInfo &nameInfo) {
John McCallcd4b4772009-12-02 03:53:29 +00003293 // If this is an implicit member access, use a different set of
3294 // diagnostics.
3295 if (!BaseExpr)
John McCallf3a88602011-02-03 08:15:49 +00003296 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall10eae182009-11-30 22:42:35 +00003297
John McCallf3a88602011-02-03 08:15:49 +00003298 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3299 << SS.getRange() << rep << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003300}
3301
3302// Check whether the declarations we found through a nested-name
3303// specifier in a member expression are actually members of the base
3304// type. The restriction here is:
3305//
3306// C++ [expr.ref]p2:
3307// ... In these cases, the id-expression shall name a
3308// member of the class or of one of its base classes.
3309//
3310// So it's perfectly legitimate for the nested-name specifier to name
3311// an unrelated class, and for us to find an overload set including
3312// decls from classes which are not superclasses, as long as the decl
3313// we actually pick through overload resolution is from a superclass.
3314bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3315 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003316 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003317 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003318 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3319 if (!BaseRT) {
3320 // We can't check this yet because the base type is still
3321 // dependent.
3322 assert(BaseType->isDependentType());
3323 return false;
3324 }
3325 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003326
3327 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003328 // If this is an implicit member reference and we find a
3329 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003330 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003331 return false;
John McCall10eae182009-11-30 22:42:35 +00003332
John McCall2d74de92009-12-01 22:10:20 +00003333 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003334 DeclContext *DC = (*I)->getDeclContext();
3335 while (DC->isTransparentContext())
3336 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003337
Douglas Gregora9c3e822010-07-28 22:27:52 +00003338 if (!DC->isRecord())
3339 continue;
3340
John McCall2d74de92009-12-01 22:10:20 +00003341 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003342 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003343
3344 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3345 return false;
3346 }
3347
John McCallf3a88602011-02-03 08:15:49 +00003348 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3349 R.getRepresentativeDecl(),
3350 R.getLookupNameInfo());
John McCall2d74de92009-12-01 22:10:20 +00003351 return true;
3352}
3353
3354static bool
3355LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3356 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003357 SourceLocation OpLoc, CXXScopeSpec &SS,
3358 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003359 RecordDecl *RDecl = RTy->getDecl();
3360 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003361 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003362 << BaseRange))
3363 return true;
3364
John McCalle9cccd82010-06-16 08:42:20 +00003365 if (HasTemplateArgs) {
3366 // LookupTemplateName doesn't expect these both to exist simultaneously.
3367 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3368
3369 bool MOUS;
3370 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3371 return false;
3372 }
3373
John McCall2d74de92009-12-01 22:10:20 +00003374 DeclContext *DC = RDecl;
3375 if (SS.isSet()) {
3376 // If the member name was a qualified-id, look into the
3377 // nested-name-specifier.
3378 DC = SemaRef.computeDeclContext(SS, false);
3379
John McCall0b66eb32010-05-01 00:40:08 +00003380 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003381 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3382 << SS.getRange() << DC;
3383 return true;
3384 }
3385
John McCall2d74de92009-12-01 22:10:20 +00003386 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003387
John McCall2d74de92009-12-01 22:10:20 +00003388 if (!isa<TypeDecl>(DC)) {
3389 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3390 << DC << SS.getRange();
3391 return true;
John McCall10eae182009-11-30 22:42:35 +00003392 }
3393 }
3394
John McCall2d74de92009-12-01 22:10:20 +00003395 // The record definition is complete, now look up the member.
3396 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003397
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003398 if (!R.empty())
3399 return false;
3400
3401 // We didn't find anything with the given name, so try to correct
3402 // for typos.
3403 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003404 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003405 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003406 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3407 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3408 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003409 << FixItHint::CreateReplacement(R.getNameLoc(),
3410 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003411 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3412 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3413 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003414 return false;
3415 } else {
3416 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003417 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003418 }
3419
John McCall10eae182009-11-30 22:42:35 +00003420 return false;
3421}
3422
John McCalldadc5752010-08-24 06:29:42 +00003423ExprResult
John McCallb268a282010-08-23 23:25:46 +00003424Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003425 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003426 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003427 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003428 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003429 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003430 if (BaseType->isDependentType() ||
3431 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003432 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003433 IsArrow, OpLoc,
3434 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003435 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003436
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003437 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003438
John McCall2d74de92009-12-01 22:10:20 +00003439 // Implicit member accesses.
3440 if (!Base) {
3441 QualType RecordTy = BaseType;
3442 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3443 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3444 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003445 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003446 return ExprError();
3447
3448 // Explicit member accesses.
3449 } else {
John McCalldadc5752010-08-24 06:29:42 +00003450 ExprResult Result =
John McCall2d74de92009-12-01 22:10:20 +00003451 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003452 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003453
3454 if (Result.isInvalid()) {
3455 Owned(Base);
3456 return ExprError();
3457 }
3458
3459 if (Result.get())
3460 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003461
3462 // LookupMemberExpr can modify Base, and thus change BaseType
3463 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003464 }
3465
John McCallb268a282010-08-23 23:25:46 +00003466 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003467 OpLoc, IsArrow, SS, FirstQualifierInScope,
3468 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003469}
3470
John McCalldadc5752010-08-24 06:29:42 +00003471ExprResult
John McCallb268a282010-08-23 23:25:46 +00003472Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003473 SourceLocation OpLoc, bool IsArrow,
3474 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003475 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003476 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003477 const TemplateArgumentListInfo *TemplateArgs,
3478 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003479 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003480 if (IsArrow) {
3481 assert(BaseType->isPointerType());
3482 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3483 }
John McCalla8ae2222010-04-06 21:38:20 +00003484 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003485
John McCallb268a282010-08-23 23:25:46 +00003486 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003487 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3488 DeclarationName MemberName = MemberNameInfo.getName();
3489 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003490
3491 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003492 return ExprError();
3493
John McCall10eae182009-11-30 22:42:35 +00003494 if (R.empty()) {
3495 // Rederive where we looked up.
3496 DeclContext *DC = (SS.isSet()
3497 ? computeDeclContext(SS, false)
3498 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003499
John McCall10eae182009-11-30 22:42:35 +00003500 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003501 << MemberName << DC
3502 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003503 return ExprError();
3504 }
3505
John McCall38836f02010-01-15 08:34:02 +00003506 // Diagnose lookups that find only declarations from a non-base
3507 // type. This is possible for either qualified lookups (which may
3508 // have been qualified with an unrelated type) or implicit member
3509 // expressions (which were found with unqualified lookup and thus
3510 // may have come from an enclosing scope). Note that it's okay for
3511 // lookup to find declarations from a non-base type as long as those
3512 // aren't the ones picked by overload resolution.
3513 if ((SS.isSet() || !BaseExpr ||
3514 (isa<CXXThisExpr>(BaseExpr) &&
3515 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003516 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003517 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003518 return ExprError();
3519
3520 // Construct an unresolved result if we in fact got an unresolved
3521 // result.
3522 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003523 // Suppress any lookup-related diagnostics; we'll do these when we
3524 // pick a member.
3525 R.suppressDiagnostics();
3526
John McCall10eae182009-11-30 22:42:35 +00003527 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003528 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003529 BaseExpr, BaseExprType,
3530 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003531 Qualifier, SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003532 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003533 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003534
3535 return Owned(MemExpr);
3536 }
3537
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003538 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003539 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003540 NamedDecl *MemberDecl = R.getFoundDecl();
3541
3542 // FIXME: diagnose the presence of template arguments now.
3543
3544 // If the decl being referenced had an error, return an error for this
3545 // sub-expr without emitting another error, in order to avoid cascading
3546 // error cases.
3547 if (MemberDecl->isInvalidDecl())
3548 return ExprError();
3549
John McCall2d74de92009-12-01 22:10:20 +00003550 // Handle the implicit-member-access case.
3551 if (!BaseExpr) {
3552 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003553 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003554 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003555
Douglas Gregorb15af892010-01-07 23:12:05 +00003556 SourceLocation Loc = R.getNameLoc();
3557 if (SS.getRange().isValid())
3558 Loc = SS.getRange().getBegin();
3559 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003560 }
3561
John McCall10eae182009-11-30 22:42:35 +00003562 bool ShouldCheckUse = true;
3563 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3564 // Don't diagnose the use of a virtual member function unless it's
3565 // explicitly qualified.
3566 if (MD->isVirtual() && !SS.isSet())
3567 ShouldCheckUse = false;
3568 }
3569
3570 // Check the use of this member.
3571 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3572 Owned(BaseExpr);
3573 return ExprError();
3574 }
3575
John McCall34376a62010-12-04 03:47:34 +00003576 // Perform a property load on the base regardless of whether we
3577 // actually need it for the declaration.
3578 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3579 ConvertPropertyForRValue(BaseExpr);
3580
John McCallfeb624a2010-11-23 20:48:44 +00003581 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3582 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3583 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003584
Francois Pichet783dd6e2010-11-21 06:08:52 +00003585 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3586 // We may have found a field within an anonymous union or struct
3587 // (C++ [class.union]).
John McCallf3a88602011-02-03 08:15:49 +00003588 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00003589 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003590
John McCall10eae182009-11-30 22:42:35 +00003591 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3592 MarkDeclarationReferenced(MemberLoc, Var);
3593 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003594 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003595 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003596 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003597 }
3598
John McCall7decc9e2010-11-18 06:31:45 +00003599 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall10eae182009-11-30 22:42:35 +00003600 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3601 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003602 MemberFn, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003603 MemberFn->getType(),
3604 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3605 OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003606 }
John McCall7decc9e2010-11-18 06:31:45 +00003607 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003608
3609 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3610 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3611 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003612 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003613 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003614 }
3615
3616 Owned(BaseExpr);
3617
Douglas Gregor861eb802010-04-25 20:55:08 +00003618 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003619 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003620 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003621 << MemberName << BaseType << int(IsArrow);
3622 else
3623 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3624 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003625
Douglas Gregor861eb802010-04-25 20:55:08 +00003626 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3627 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003628 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003629 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003630}
3631
John McCall68fc88ec2010-12-15 16:46:44 +00003632/// Given that normal member access failed on the given expression,
3633/// and given that the expression's type involves builtin-id or
3634/// builtin-Class, decide whether substituting in the redefinition
3635/// types would be profitable. The redefinition type is whatever
3636/// this translation unit tried to typedef to id/Class; we store
3637/// it to the side and then re-use it in places like this.
3638static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3639 const ObjCObjectPointerType *opty
3640 = base->getType()->getAs<ObjCObjectPointerType>();
3641 if (!opty) return false;
3642
3643 const ObjCObjectType *ty = opty->getObjectType();
3644
3645 QualType redef;
3646 if (ty->isObjCId()) {
3647 redef = S.Context.ObjCIdRedefinitionType;
3648 } else if (ty->isObjCClass()) {
3649 redef = S.Context.ObjCClassRedefinitionType;
3650 } else {
3651 return false;
3652 }
3653
3654 // Do the substitution as long as the redefinition type isn't just a
3655 // possibly-qualified pointer to builtin-id or builtin-Class again.
3656 opty = redef->getAs<ObjCObjectPointerType>();
3657 if (opty && !opty->getObjectType()->getInterface() != 0)
3658 return false;
3659
3660 S.ImpCastExprToType(base, redef, CK_BitCast);
3661 return true;
3662}
3663
John McCall10eae182009-11-30 22:42:35 +00003664/// Look up the given member of the given non-type-dependent
3665/// expression. This can return in one of two ways:
3666/// * If it returns a sentinel null-but-valid result, the caller will
3667/// assume that lookup was performed and the results written into
3668/// the provided structure. It will take over from there.
3669/// * Otherwise, the returned expression will be produced in place of
3670/// an ordinary member expression.
3671///
3672/// The ObjCImpDecl bit is a gross hack that will need to be properly
3673/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00003674ExprResult
John McCall10eae182009-11-30 22:42:35 +00003675Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00003676 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003677 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00003678 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003679 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00003680
Steve Naroffeaaae462007-12-16 21:42:28 +00003681 // Perform default conversions.
3682 DefaultFunctionArrayConversion(BaseExpr);
John McCall15317a22010-12-15 04:42:30 +00003683 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003684
Steve Naroff185616f2007-07-26 03:11:44 +00003685 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00003686 assert(!BaseType->isDependentType());
3687
3688 DeclarationName MemberName = R.getLookupName();
3689 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00003690
John McCall68fc88ec2010-12-15 16:46:44 +00003691 // For later type-checking purposes, turn arrow accesses into dot
3692 // accesses. The only access type we support that doesn't follow
3693 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3694 // and those never use arrows, so this is unaffected.
3695 if (IsArrow) {
3696 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3697 BaseType = Ptr->getPointeeType();
3698 else if (const ObjCObjectPointerType *Ptr
3699 = BaseType->getAs<ObjCObjectPointerType>())
3700 BaseType = Ptr->getPointeeType();
3701 else if (BaseType->isRecordType()) {
3702 // Recover from arrow accesses to records, e.g.:
3703 // struct MyRecord foo;
3704 // foo->bar
3705 // This is actually well-formed in C++ if MyRecord has an
3706 // overloaded operator->, but that should have been dealt with
3707 // by now.
3708 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3709 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3710 << FixItHint::CreateReplacement(OpLoc, ".");
3711 IsArrow = false;
3712 } else {
3713 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3714 << BaseType << BaseExpr->getSourceRange();
3715 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00003716 }
3717 }
3718
John McCall68fc88ec2010-12-15 16:46:44 +00003719 // Handle field access to simple records.
3720 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3721 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3722 RTy, OpLoc, SS, HasTemplateArgs))
3723 return ExprError();
3724
3725 // Returning valid-but-null is how we indicate to the caller that
3726 // the lookup result was filled in.
3727 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00003728 }
John McCall10eae182009-11-30 22:42:35 +00003729
John McCall68fc88ec2010-12-15 16:46:44 +00003730 // Handle ivar access to Objective-C objects.
3731 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003732 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00003733
3734 // There are three cases for the base type:
3735 // - builtin id (qualified or unqualified)
3736 // - builtin Class (qualified or unqualified)
3737 // - an interface
3738 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3739 if (!IDecl) {
3740 // There's an implicit 'isa' ivar on all objects.
3741 // But we only actually find it this way on objects of type 'id',
3742 // apparently.
3743 if (OTy->isObjCId() && Member->isStr("isa"))
3744 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3745 Context.getObjCClassType()));
3746
3747 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3748 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3749 ObjCImpDecl, HasTemplateArgs);
3750 goto fail;
3751 }
3752
3753 ObjCInterfaceDecl *ClassDeclared;
3754 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3755
3756 if (!IV) {
3757 // Attempt to correct for typos in ivar names.
3758 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3759 LookupMemberName);
3760 if (CorrectTypo(Res, 0, 0, IDecl, false,
3761 IsArrow ? CTC_ObjCIvarLookup
3762 : CTC_ObjCPropertyLookup) &&
3763 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3764 Diag(R.getNameLoc(),
3765 diag::err_typecheck_member_reference_ivar_suggest)
3766 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3767 << FixItHint::CreateReplacement(R.getNameLoc(),
3768 IV->getNameAsString());
3769 Diag(IV->getLocation(), diag::note_previous_decl)
3770 << IV->getDeclName();
3771 } else {
3772 Res.clear();
3773 Res.setLookupName(Member);
3774
3775 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3776 << IDecl->getDeclName() << MemberName
3777 << BaseExpr->getSourceRange();
3778 return ExprError();
3779 }
3780 }
3781
3782 // If the decl being referenced had an error, return an error for this
3783 // sub-expr without emitting another error, in order to avoid cascading
3784 // error cases.
3785 if (IV->isInvalidDecl())
3786 return ExprError();
3787
3788 // Check whether we can reference this field.
3789 if (DiagnoseUseOfDecl(IV, MemberLoc))
3790 return ExprError();
3791 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3792 IV->getAccessControl() != ObjCIvarDecl::Package) {
3793 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3794 if (ObjCMethodDecl *MD = getCurMethodDecl())
3795 ClassOfMethodDecl = MD->getClassInterface();
3796 else if (ObjCImpDecl && getCurFunctionDecl()) {
3797 // Case of a c-function declared inside an objc implementation.
3798 // FIXME: For a c-style function nested inside an objc implementation
3799 // class, there is no implementation context available, so we pass
3800 // down the context as argument to this routine. Ideally, this context
3801 // need be passed down in the AST node and somehow calculated from the
3802 // AST for a function decl.
3803 if (ObjCImplementationDecl *IMPD =
3804 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3805 ClassOfMethodDecl = IMPD->getClassInterface();
3806 else if (ObjCCategoryImplDecl* CatImplClass =
3807 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3808 ClassOfMethodDecl = CatImplClass->getClassInterface();
3809 }
3810
3811 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3812 if (ClassDeclared != IDecl ||
3813 ClassOfMethodDecl != ClassDeclared)
3814 Diag(MemberLoc, diag::error_private_ivar_access)
3815 << IV->getDeclName();
3816 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3817 // @protected
3818 Diag(MemberLoc, diag::error_protected_ivar_access)
3819 << IV->getDeclName();
3820 }
3821
3822 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3823 MemberLoc, BaseExpr,
3824 IsArrow));
3825 }
3826
3827 // Objective-C property access.
3828 const ObjCObjectPointerType *OPT;
3829 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3830 // This actually uses the base as an r-value.
3831 DefaultLvalueConversion(BaseExpr);
3832 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3833
3834 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3835
3836 const ObjCObjectType *OT = OPT->getObjectType();
3837
3838 // id, with and without qualifiers.
3839 if (OT->isObjCId()) {
3840 // Check protocols on qualified interfaces.
3841 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3842 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3843 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3844 // Check the use of this declaration
3845 if (DiagnoseUseOfDecl(PD, MemberLoc))
3846 return ExprError();
3847
3848 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3849 VK_LValue,
3850 OK_ObjCProperty,
3851 MemberLoc,
3852 BaseExpr));
3853 }
3854
3855 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3856 // Check the use of this method.
3857 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3858 return ExprError();
3859 Selector SetterSel =
3860 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3861 PP.getSelectorTable(), Member);
3862 ObjCMethodDecl *SMD = 0;
3863 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3864 SetterSel, Context))
3865 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3866 QualType PType = OMD->getSendResultType();
3867
3868 ExprValueKind VK = VK_LValue;
3869 if (!getLangOptions().CPlusPlus &&
3870 IsCForbiddenLValueType(Context, PType))
3871 VK = VK_RValue;
3872 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3873
3874 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3875 VK, OK,
3876 MemberLoc, BaseExpr));
3877 }
3878 }
3879
3880 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3881 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3882 ObjCImpDecl, HasTemplateArgs);
3883
3884 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3885 << MemberName << BaseType);
3886 }
3887
3888 // 'Class', unqualified only.
3889 if (OT->isObjCClass()) {
3890 // Only works in a method declaration (??!).
3891 ObjCMethodDecl *MD = getCurMethodDecl();
3892 if (!MD) {
3893 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3894 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3895 ObjCImpDecl, HasTemplateArgs);
3896
3897 goto fail;
3898 }
3899
3900 // Also must look for a getter name which uses property syntax.
3901 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003902 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3903 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003904 if ((Getter = IFace->lookupClassMethod(Sel))) {
3905 // Check the use of this method.
3906 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3907 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00003908 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003909 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003910 // If we found a getter then this may be a valid dot-reference, we
3911 // will look for the matching setter, in case it is needed.
3912 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00003913 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3914 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003915 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3916 if (!Setter) {
3917 // If this reference is in an @implementation, also check for 'private'
3918 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003919 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003920 }
3921 // Look through local category implementations associated with the class.
3922 if (!Setter)
3923 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003924
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003925 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3926 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003927
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003928 if (Getter || Setter) {
3929 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003930
John McCall4bc41ae2010-11-18 19:01:18 +00003931 ExprValueKind VK = VK_LValue;
3932 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00003933 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00003934 if (!getLangOptions().CPlusPlus &&
3935 IsCForbiddenLValueType(Context, PType))
3936 VK = VK_RValue;
3937 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003938 // Get the expression type from Setter's incoming parameter.
3939 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00003940 }
3941 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3942
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003943 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00003944 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3945 PType, VK, OK,
3946 MemberLoc, BaseExpr));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003947 }
John McCall68fc88ec2010-12-15 16:46:44 +00003948
3949 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3950 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3951 ObjCImpDecl, HasTemplateArgs);
3952
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003953 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00003954 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003955 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003956
John McCall68fc88ec2010-12-15 16:46:44 +00003957 // Normal property access.
3958 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3959 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003960 }
Alexis Huntc46382e2010-04-28 23:02:27 +00003961
Chris Lattnerb63a7452008-07-21 04:28:12 +00003962 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003963 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00003964 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00003965 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall15317a22010-12-15 04:42:30 +00003966 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00003967 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3968 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00003969 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003970 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00003971
3972 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3973 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003974 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003975
John McCall68fc88ec2010-12-15 16:46:44 +00003976 // Adjust builtin-sel to the appropriate redefinition type if that's
3977 // not just a pointer to builtin-sel again.
3978 if (IsArrow &&
3979 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
3980 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
3981 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
3982 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3983 ObjCImpDecl, HasTemplateArgs);
3984 }
3985
3986 // Failure cases.
3987 fail:
3988
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00003989 // Recover from dot accesses to pointers, e.g.:
3990 // type *foo;
3991 // foo.bar
3992 // This is actually well-formed in two cases:
3993 // - 'type' is an Objective C type
3994 // - 'bar' is a pseudo-destructor name which happens to refer to
3995 // the appropriate pointer type
John McCall68fc88ec2010-12-15 16:46:44 +00003996 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00003997 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
3998 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall68fc88ec2010-12-15 16:46:44 +00003999 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004000 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
4001 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall68fc88ec2010-12-15 16:46:44 +00004002
4003 // Recurse as an -> access.
4004 IsArrow = true;
4005 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4006 ObjCImpDecl, HasTemplateArgs);
4007 }
John McCall68fc88ec2010-12-15 16:46:44 +00004008 }
4009
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004010 // If the user is trying to apply -> or . to a function name, it's probably
4011 // because they forgot parentheses to call that function.
4012 bool TryCall = false;
4013 bool Overloaded = false;
4014 UnresolvedSet<8> AllOverloads;
4015 if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr)) {
4016 AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end());
4017 TryCall = true;
4018 Overloaded = true;
4019 } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr)) {
4020 if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
4021 AllOverloads.addDecl(Fun);
4022 TryCall = true;
4023 }
4024 }
John McCall68fc88ec2010-12-15 16:46:44 +00004025
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004026 if (TryCall) {
4027 // Plunder the overload set for something that would make the member
4028 // expression valid.
4029 UnresolvedSet<4> ViableOverloads;
4030 bool HasViableZeroArgOverload = false;
4031 for (OverloadExpr::decls_iterator it = AllOverloads.begin(),
4032 DeclsEnd = AllOverloads.end(); it != DeclsEnd; ++it) {
4033 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*it);
4034 QualType ResultTy = OverloadDecl->getResultType();
4035 if ((!IsArrow && ResultTy->isRecordType()) ||
4036 (IsArrow && ResultTy->isPointerType() &&
4037 ResultTy->getPointeeType()->isRecordType())) {
4038 ViableOverloads.addDecl(*it);
4039 if (OverloadDecl->getMinRequiredArguments() == 0) {
4040 HasViableZeroArgOverload = true;
4041 }
John McCall68fc88ec2010-12-15 16:46:44 +00004042 }
4043 }
4044
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004045 if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) {
4046 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
4047 << 1 << 0
4048 << BaseExpr->getSourceRange();
4049 int ViableOverloadCount = ViableOverloads.size();
4050 int I;
4051 for (I = 0; I < ViableOverloadCount; ++I) {
4052 // FIXME: Magic number for max shown overloads stolen from
4053 // OverloadCandidateSet::NoteCandidates.
4054 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4055 break;
4056 }
4057 Diag(ViableOverloads[I].getDecl()->getSourceRange().getBegin(),
4058 diag::note_member_ref_possible_intended_overload);
4059 }
4060 if (I != ViableOverloadCount) {
4061 Diag(BaseExpr->getExprLoc(), diag::note_ovl_too_many_candidates)
4062 << int(ViableOverloadCount - I);
4063 }
4064 return ExprError();
4065 }
4066 } else {
4067 // We don't have an expression that's convenient to get a Decl from, but we
4068 // can at least check if the type is "function of 0 arguments which returns
4069 // an acceptable type".
4070 const FunctionType *Fun = NULL;
4071 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4072 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4073 TryCall = true;
4074 }
4075 } else if ((Fun = BaseType->getAs<FunctionType>())) {
4076 TryCall = true;
4077 }
John McCall68fc88ec2010-12-15 16:46:44 +00004078
4079 if (TryCall) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004080 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4081 if (FPT->getNumArgs() == 0) {
4082 QualType ResultTy = Fun->getResultType();
4083 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4084 (IsArrow && ResultTy->isPointerType() &&
4085 ResultTy->getPointeeType()->isRecordType());
4086 }
Matt Beaumont-Gay956fc1c2011-02-17 02:54:17 +00004087 }
John McCall68fc88ec2010-12-15 16:46:44 +00004088 }
4089 }
4090
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004091 if (TryCall) {
4092 // At this point, we know BaseExpr looks like it's potentially callable with
4093 // 0 arguments, and that it returns something of a reasonable type, so we
4094 // can emit a fixit and carry on pretending that BaseExpr was actually a
4095 // CallExpr.
4096 SourceLocation ParenInsertionLoc =
4097 PP.getLocForEndOfToken(BaseExpr->getLocEnd());
4098 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
4099 << int(Overloaded) << 1
4100 << BaseExpr->getSourceRange()
4101 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4102 ExprResult NewBase = ActOnCallExpr(0, BaseExpr, ParenInsertionLoc,
4103 MultiExprArg(*this, 0, 0),
4104 ParenInsertionLoc);
4105 if (NewBase.isInvalid())
4106 return ExprError();
4107 BaseExpr = NewBase.takeAs<Expr>();
4108 DefaultFunctionArrayConversion(BaseExpr);
4109 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4110 ObjCImpDecl, HasTemplateArgs);
4111 }
4112
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004113 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
4114 << BaseType << BaseExpr->getSourceRange();
4115
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004116 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00004117}
4118
John McCall10eae182009-11-30 22:42:35 +00004119/// The main callback when the parser finds something like
4120/// expression . [nested-name-specifier] identifier
4121/// expression -> [nested-name-specifier] identifier
4122/// where 'identifier' encompasses a fairly broad spectrum of
4123/// possibilities, including destructor and operator references.
4124///
4125/// \param OpKind either tok::arrow or tok::period
4126/// \param HasTrailingLParen whether the next token is '(', which
4127/// is used to diagnose mis-uses of special members that can
4128/// only be called
4129/// \param ObjCImpDecl the current ObjC @implementation decl;
4130/// this is an ugly hack around the fact that ObjC @implementations
4131/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00004132ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00004133 SourceLocation OpLoc,
4134 tok::TokenKind OpKind,
4135 CXXScopeSpec &SS,
4136 UnqualifiedId &Id,
4137 Decl *ObjCImpDecl,
4138 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00004139 if (SS.isSet() && SS.isInvalid())
4140 return ExprError();
4141
Francois Pichet64225792011-01-18 05:04:39 +00004142 // Warn about the explicit constructor calls Microsoft extension.
4143 if (getLangOptions().Microsoft &&
4144 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4145 Diag(Id.getSourceRange().getBegin(),
4146 diag::ext_ms_explicit_constructor_call);
4147
John McCall10eae182009-11-30 22:42:35 +00004148 TemplateArgumentListInfo TemplateArgsBuffer;
4149
4150 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004151 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00004152 const TemplateArgumentListInfo *TemplateArgs;
4153 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004154 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004155
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004156 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00004157 bool IsArrow = (OpKind == tok::arrow);
4158
4159 NamedDecl *FirstQualifierInScope
4160 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4161 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4162
4163 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004164 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004165 if (Result.isInvalid()) return ExprError();
4166 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00004167
Douglas Gregor41f90302010-04-12 20:54:26 +00004168 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4169 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00004170 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00004171 IsArrow, OpLoc,
4172 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004173 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004174 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004175 LookupResult R(*this, NameInfo, LookupMemberName);
John McCalle9cccd82010-06-16 08:42:20 +00004176 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
4177 SS, ObjCImpDecl, TemplateArgs != 0);
Alexis Huntc46382e2010-04-28 23:02:27 +00004178
John McCalle9cccd82010-06-16 08:42:20 +00004179 if (Result.isInvalid()) {
4180 Owned(Base);
4181 return ExprError();
4182 }
John McCall10eae182009-11-30 22:42:35 +00004183
John McCalle9cccd82010-06-16 08:42:20 +00004184 if (Result.get()) {
4185 // The only way a reference to a destructor can be used is to
4186 // immediately call it, which falls into this case. If the
4187 // next token is not a '(', produce a diagnostic and build the
4188 // call now.
4189 if (!HasTrailingLParen &&
4190 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00004191 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00004192
John McCalle9cccd82010-06-16 08:42:20 +00004193 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00004194 }
4195
John McCallb268a282010-08-23 23:25:46 +00004196 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00004197 OpLoc, IsArrow, SS, FirstQualifierInScope,
4198 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004199 }
4200
4201 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00004202}
4203
John McCalldadc5752010-08-24 06:29:42 +00004204ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004205 FunctionDecl *FD,
4206 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004207 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004208 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004209 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004210 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004211 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004212 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004213 return ExprError();
4214 }
4215
4216 if (Param->hasUninstantiatedDefaultArg()) {
4217 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004218
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004219 // Instantiate the expression.
4220 MultiLevelTemplateArgumentList ArgList
4221 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004222
Nico Weber44887f62010-11-29 18:19:25 +00004223 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004224 = ArgList.getInnermost();
4225 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4226 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00004227
Nico Weber44887f62010-11-29 18:19:25 +00004228 ExprResult Result;
4229 {
4230 // C++ [dcl.fct.default]p5:
4231 // The names in the [default argument] expression are bound, and
4232 // the semantic constraints are checked, at the point where the
4233 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004234 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004235 Result = SubstExpr(UninstExpr, ArgList);
4236 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004237 if (Result.isInvalid())
4238 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004239
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004240 // Check the expression as an initializer for the parameter.
4241 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004242 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004243 InitializationKind Kind
4244 = InitializationKind::CreateCopy(Param->getLocation(),
4245 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4246 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004247
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004248 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4249 Result = InitSeq.Perform(*this, Entity, Kind,
4250 MultiExprArg(*this, &ResultE, 1));
4251 if (Result.isInvalid())
4252 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004253
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004254 // Build the default argument expression.
4255 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4256 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004257 }
4258
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004259 // If the default expression creates temporaries, we need to
4260 // push them to the current stack of expression temporaries so they'll
4261 // be properly destroyed.
4262 // FIXME: We should really be rebuilding the default argument with new
4263 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004264 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4265 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4266 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4267 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4268 ExprTemporaries.push_back(Temporary);
4269 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004270
4271 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004272 // Just mark all of the declarations in this potentially-evaluated expression
4273 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004274 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004275 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004276}
4277
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004278/// ConvertArgumentsForCall - Converts the arguments specified in
4279/// Args/NumArgs to the parameter types of the function FDecl with
4280/// function prototype Proto. Call is the call expression itself, and
4281/// Fn is the function expression. For a C++ member function, this
4282/// routine does not attempt to convert the object argument. Returns
4283/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004284bool
4285Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004286 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004287 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004288 Expr **Args, unsigned NumArgs,
4289 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00004290 // Bail out early if calling a builtin with custom typechecking.
4291 // We don't need to do this in the
4292 if (FDecl)
4293 if (unsigned ID = FDecl->getBuiltinID())
4294 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4295 return false;
4296
Mike Stump4e1f26a2009-02-19 03:04:26 +00004297 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004298 // assignment, to the types of the corresponding parameter, ...
4299 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004300 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004301
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004302 // If too few arguments are available (and we don't have default
4303 // arguments for the remaining parameters), don't make the call.
4304 if (NumArgs < NumArgsInProto) {
4305 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4306 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004307 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004308 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004309 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004310 }
4311
4312 // If too many are passed and not variadic, error on the extras and drop
4313 // them.
4314 if (NumArgs > NumArgsInProto) {
4315 if (!Proto->isVariadic()) {
4316 Diag(Args[NumArgsInProto]->getLocStart(),
4317 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004318 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004319 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004320 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4321 Args[NumArgs-1]->getLocEnd());
4322 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004323 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004324 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004325 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004326 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004327 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004328 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004329 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4330 if (Fn->getType()->isBlockPointerType())
4331 CallType = VariadicBlock; // Block
4332 else if (isa<MemberExpr>(Fn))
4333 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004334 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004335 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004336 if (Invalid)
4337 return true;
4338 unsigned TotalNumArgs = AllArgs.size();
4339 for (unsigned i = 0; i < TotalNumArgs; ++i)
4340 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004341
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004342 return false;
4343}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004344
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004345bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4346 FunctionDecl *FDecl,
4347 const FunctionProtoType *Proto,
4348 unsigned FirstProtoArg,
4349 Expr **Args, unsigned NumArgs,
4350 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004351 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004352 unsigned NumArgsInProto = Proto->getNumArgs();
4353 unsigned NumArgsToCheck = NumArgs;
4354 bool Invalid = false;
4355 if (NumArgs != NumArgsInProto)
4356 // Use default arguments for missing arguments
4357 NumArgsToCheck = NumArgsInProto;
4358 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004359 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004360 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004361 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004362
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004363 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004364 if (ArgIx < NumArgs) {
4365 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004366
Eli Friedman3164fb12009-03-22 22:00:50 +00004367 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4368 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004369 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004370 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004371 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004372
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004373 // Pass the argument
4374 ParmVarDecl *Param = 0;
4375 if (FDecl && i < FDecl->getNumParams())
4376 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004377
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004378 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004379 Param? InitializedEntity::InitializeParameter(Context, Param)
4380 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004381 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004382 SourceLocation(),
4383 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004384 if (ArgE.isInvalid())
4385 return true;
4386
4387 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004388 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004389 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004390
John McCalldadc5752010-08-24 06:29:42 +00004391 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004392 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004393 if (ArgExpr.isInvalid())
4394 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004395
Anders Carlsson355933d2009-08-25 03:49:14 +00004396 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004397 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004398 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004399 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004400
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004401 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004402 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004403 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004404 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004405 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004406 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004407 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004408 }
4409 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004410 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004411}
4412
Steve Naroff83895f72007-09-16 03:34:24 +00004413/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004414/// This provides the location of the left/right parens and a list of comma
4415/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004416ExprResult
John McCallb268a282010-08-23 23:25:46 +00004417Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004418 MultiExprArg args, SourceLocation RParenLoc,
4419 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004420 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004421
4422 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004423 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004424 if (Result.isInvalid()) return ExprError();
4425 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004426
John McCallb268a282010-08-23 23:25:46 +00004427 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004428
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004429 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004430 // If this is a pseudo-destructor expression, build the call immediately.
4431 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4432 if (NumArgs > 0) {
4433 // Pseudo-destructor calls should not have any arguments.
4434 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004435 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004436 SourceRange(Args[0]->getLocStart(),
4437 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004438
Douglas Gregorad8a3362009-09-04 17:36:40 +00004439 NumArgs = 0;
4440 }
Mike Stump11289f42009-09-09 15:08:12 +00004441
Douglas Gregorad8a3362009-09-04 17:36:40 +00004442 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004443 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004444 }
Mike Stump11289f42009-09-09 15:08:12 +00004445
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004446 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004447 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004448 // FIXME: Will need to cache the results of name lookup (including ADL) in
4449 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004450 bool Dependent = false;
4451 if (Fn->isTypeDependent())
4452 Dependent = true;
4453 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4454 Dependent = true;
4455
Peter Collingbourne41f85462011-02-09 21:07:24 +00004456 if (Dependent) {
4457 if (ExecConfig) {
4458 return Owned(new (Context) CUDAKernelCallExpr(
4459 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4460 Context.DependentTy, VK_RValue, RParenLoc));
4461 } else {
4462 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4463 Context.DependentTy, VK_RValue,
4464 RParenLoc));
4465 }
4466 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004467
4468 // Determine whether this is a call to an object (C++ [over.call.object]).
4469 if (Fn->getType()->isRecordType())
4470 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004471 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004472
John McCall10eae182009-11-30 22:42:35 +00004473 Expr *NakedFn = Fn->IgnoreParens();
4474
4475 // Determine whether this is a call to an unresolved member function.
4476 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4477 // If lookup was unresolved but not dependent (i.e. didn't find
4478 // an unresolved using declaration), it has to be an overloaded
4479 // function set, which means it must contain either multiple
4480 // declarations (all methods or method templates) or a single
4481 // method template.
4482 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00004483 isa<FunctionTemplateDecl>(
4484 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00004485 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00004486
John McCall2d74de92009-12-01 22:10:20 +00004487 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004488 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004489 }
4490
Douglas Gregore254f902009-02-04 00:32:51 +00004491 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00004492 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004493 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00004494 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00004495 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004496 RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004497 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004498
Anders Carlsson61914b52009-10-03 17:40:22 +00004499 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00004500 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCalle3027922010-08-25 11:45:40 +00004501 if (BO->getOpcode() == BO_PtrMemD ||
4502 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00004503 if (const FunctionProtoType *FPT
4504 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004505 QualType ResultTy = FPT->getCallResultType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004506 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004507
Douglas Gregor125fa402011-02-04 12:57:49 +00004508 // Check that the object type isn't more qualified than the
4509 // member function we're calling.
4510 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4511 Qualifiers ObjectQuals
4512 = BO->getOpcode() == BO_PtrMemD
4513 ? BO->getLHS()->getType().getQualifiers()
4514 : BO->getLHS()->getType()->getAs<PointerType>()
4515 ->getPointeeType().getQualifiers();
4516
4517 Qualifiers Difference = ObjectQuals - FuncQuals;
4518 Difference.removeObjCGCAttr();
4519 Difference.removeAddressSpace();
4520 if (Difference) {
4521 std::string QualsString = Difference.getAsString();
4522 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4523 << BO->getType().getUnqualifiedType()
4524 << QualsString
4525 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4526 }
4527
John McCallb268a282010-08-23 23:25:46 +00004528 CXXMemberCallExpr *TheCall
Abramo Bagnara21e9d862010-12-03 21:39:42 +00004529 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCall7decc9e2010-11-18 06:31:45 +00004530 NumArgs, ResultTy, VK,
John McCallb268a282010-08-23 23:25:46 +00004531 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004532
4533 if (CheckCallReturnType(FPT->getResultType(),
4534 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00004535 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004536 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00004537
John McCallb268a282010-08-23 23:25:46 +00004538 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004539 RParenLoc))
4540 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00004541
John McCallb268a282010-08-23 23:25:46 +00004542 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004543 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004544 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004545 diag::err_typecheck_call_not_function)
4546 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00004547 }
4548 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004549 }
4550
Douglas Gregore254f902009-02-04 00:32:51 +00004551 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004552 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00004553 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004554
Eli Friedmane14b1992009-12-26 03:35:45 +00004555 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004556 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4557 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4558 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004559 RParenLoc, ExecConfig);
Douglas Gregor928479e2010-11-09 20:03:54 +00004560 }
4561
John McCall57500772009-12-16 12:17:52 +00004562 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004563 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4564 if (UnOp->getOpcode() == UO_AddrOf)
4565 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4566
John McCall57500772009-12-16 12:17:52 +00004567 if (isa<DeclRefExpr>(NakedFn))
4568 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4569
Peter Collingbourne41f85462011-02-09 21:07:24 +00004570 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4571 ExecConfig);
4572}
4573
4574ExprResult
4575Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4576 MultiExprArg execConfig, SourceLocation GGGLoc) {
4577 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4578 if (!ConfigDecl)
4579 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4580 << "cudaConfigureCall");
4581 QualType ConfigQTy = ConfigDecl->getType();
4582
4583 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4584 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4585
4586 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00004587}
4588
John McCall57500772009-12-16 12:17:52 +00004589/// BuildResolvedCallExpr - Build a call to a resolved expression,
4590/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004591/// unary-convert to an expression of function-pointer or
4592/// block-pointer type.
4593///
4594/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004595ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004596Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4597 SourceLocation LParenLoc,
4598 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004599 SourceLocation RParenLoc,
4600 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00004601 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4602
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004603 // Promote the function operand.
4604 UsualUnaryConversions(Fn);
4605
Chris Lattner08464942007-12-28 05:29:59 +00004606 // Make the call expr early, before semantic checks. This guarantees cleanup
4607 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00004608 CallExpr *TheCall;
4609 if (Config) {
4610 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4611 cast<CallExpr>(Config),
4612 Args, NumArgs,
4613 Context.BoolTy,
4614 VK_RValue,
4615 RParenLoc);
4616 } else {
4617 TheCall = new (Context) CallExpr(Context, Fn,
4618 Args, NumArgs,
4619 Context.BoolTy,
4620 VK_RValue,
4621 RParenLoc);
4622 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004623
John McCallbebede42011-02-26 05:39:39 +00004624 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4625
4626 // Bail out early if calling a builtin with custom typechecking.
4627 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4628 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4629
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004630 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00004631 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004632 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4633 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00004634 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00004635 if (FuncT == 0)
4636 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4637 << Fn->getType() << Fn->getSourceRange());
4638 } else if (const BlockPointerType *BPT =
4639 Fn->getType()->getAs<BlockPointerType>()) {
4640 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4641 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004642 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4643 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00004644 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004645
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004646 if (getLangOptions().CUDA) {
4647 if (Config) {
4648 // CUDA: Kernel calls must be to global functions
4649 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4650 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4651 << FDecl->getName() << Fn->getSourceRange());
4652
4653 // CUDA: Kernel function must have 'void' return type
4654 if (!FuncT->getResultType()->isVoidType())
4655 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4656 << Fn->getType() << Fn->getSourceRange());
4657 }
4658 }
4659
Eli Friedman3164fb12009-03-22 22:00:50 +00004660 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004661 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00004662 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004663 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004664 return ExprError();
4665
Chris Lattner08464942007-12-28 05:29:59 +00004666 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004667 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004668 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004669
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004670 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00004671 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004672 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004673 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004674 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004675 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004676
Douglas Gregord8e97de2009-04-02 15:37:10 +00004677 if (FDecl) {
4678 // Check if we have too few/too many template arguments, based
4679 // on our knowledge of the function definition.
4680 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004681 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004682 const FunctionProtoType *Proto
4683 = Def->getType()->getAs<FunctionProtoType>();
4684 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004685 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4686 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004687 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004688
4689 // If the function we're calling isn't a function prototype, but we have
4690 // a function prototype from a prior declaratiom, use that prototype.
4691 if (!FDecl->hasPrototype())
4692 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004693 }
4694
Steve Naroff0b661582007-08-28 23:30:39 +00004695 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004696 for (unsigned i = 0; i != NumArgs; i++) {
4697 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004698
4699 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004700 InitializedEntity Entity
4701 = InitializedEntity::InitializeParameter(Context,
4702 Proto->getArgType(i));
4703 ExprResult ArgE = PerformCopyInitialization(Entity,
4704 SourceLocation(),
4705 Owned(Arg));
4706 if (ArgE.isInvalid())
4707 return true;
4708
4709 Arg = ArgE.takeAs<Expr>();
4710
4711 } else {
4712 DefaultArgumentPromotion(Arg);
Douglas Gregor8e09a722010-10-25 20:39:23 +00004713 }
4714
Douglas Gregor83025412010-10-26 05:45:40 +00004715 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4716 Arg->getType(),
4717 PDiag(diag::err_call_incomplete_argument)
4718 << Arg->getSourceRange()))
4719 return ExprError();
4720
Chris Lattner08464942007-12-28 05:29:59 +00004721 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004722 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004723 }
Chris Lattner08464942007-12-28 05:29:59 +00004724
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004725 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4726 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004727 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4728 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004729
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004730 // Check for sentinels
4731 if (NDecl)
4732 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004733
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004734 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004735 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00004736 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004737 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004738
John McCallbebede42011-02-26 05:39:39 +00004739 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004740 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004741 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00004742 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004743 return ExprError();
4744 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004745
John McCallb268a282010-08-23 23:25:46 +00004746 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004747}
4748
John McCalldadc5752010-08-24 06:29:42 +00004749ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004750Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004751 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004752 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004753 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004754 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004755
4756 TypeSourceInfo *TInfo;
4757 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4758 if (!TInfo)
4759 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4760
John McCallb268a282010-08-23 23:25:46 +00004761 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004762}
4763
John McCalldadc5752010-08-24 06:29:42 +00004764ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004765Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00004766 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004767 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004768
Eli Friedman37a186d2008-05-20 05:22:08 +00004769 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004770 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4771 PDiag(diag::err_illegal_decl_array_incomplete_type)
4772 << SourceRange(LParenLoc,
4773 literalExpr->getSourceRange().getEnd())))
4774 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004775 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004776 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4777 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004778 } else if (!literalType->isDependentType() &&
4779 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00004780 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00004781 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00004782 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004783 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004784
Douglas Gregor85dabae2009-12-16 01:38:02 +00004785 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004786 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004787 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004788 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004789 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004790 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004791 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004792 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004793 &literalType);
4794 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004795 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004796 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004797
Chris Lattner79413952008-12-04 23:50:19 +00004798 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004799 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00004800 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004801 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004802 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004803
John McCall7decc9e2010-11-18 06:31:45 +00004804 // In C, compound literals are l-values for some reason.
4805 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4806
John McCall5d7aa7f2010-01-19 22:33:45 +00004807 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00004808 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004809}
4810
John McCalldadc5752010-08-24 06:29:42 +00004811ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00004812Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004813 SourceLocation RBraceLoc) {
4814 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00004815 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004816
Steve Naroff30d242c2007-09-15 18:49:24 +00004817 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004818 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004819
Ted Kremenekac034612010-04-13 23:39:13 +00004820 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4821 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004822 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004823 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004824}
4825
John McCalld7646252010-11-14 08:17:51 +00004826/// Prepares for a scalar cast, performing all the necessary stages
4827/// except the final cast and returning the kind required.
4828static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4829 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4830 // Also, callers should have filtered out the invalid cases with
4831 // pointers. Everything else should be possible.
4832
Abramo Bagnaraba854972011-01-04 09:50:03 +00004833 QualType SrcTy = Src->getType();
John McCalld7646252010-11-14 08:17:51 +00004834 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004835 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004836
John McCall8cb679e2010-11-15 09:13:47 +00004837 switch (SrcTy->getScalarTypeKind()) {
4838 case Type::STK_MemberPointer:
4839 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004840
John McCall8cb679e2010-11-15 09:13:47 +00004841 case Type::STK_Pointer:
4842 switch (DestTy->getScalarTypeKind()) {
4843 case Type::STK_Pointer:
4844 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00004845 CK_AnyPointerToObjCPointerCast :
4846 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00004847 case Type::STK_Bool:
4848 return CK_PointerToBoolean;
4849 case Type::STK_Integral:
4850 return CK_PointerToIntegral;
4851 case Type::STK_Floating:
4852 case Type::STK_FloatingComplex:
4853 case Type::STK_IntegralComplex:
4854 case Type::STK_MemberPointer:
4855 llvm_unreachable("illegal cast from pointer");
4856 }
4857 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004858
John McCall8cb679e2010-11-15 09:13:47 +00004859 case Type::STK_Bool: // casting from bool is like casting from an integer
4860 case Type::STK_Integral:
4861 switch (DestTy->getScalarTypeKind()) {
4862 case Type::STK_Pointer:
John McCalld7646252010-11-14 08:17:51 +00004863 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004864 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004865 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004866 case Type::STK_Bool:
4867 return CK_IntegralToBoolean;
4868 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004869 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004870 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004871 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004872 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004873 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004874 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004875 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004876 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004877 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004878 CK_IntegralToFloating);
4879 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004880 case Type::STK_MemberPointer:
4881 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004882 }
4883 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004884
John McCall8cb679e2010-11-15 09:13:47 +00004885 case Type::STK_Floating:
4886 switch (DestTy->getScalarTypeKind()) {
4887 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004888 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004889 case Type::STK_Bool:
4890 return CK_FloatingToBoolean;
4891 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004892 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004893 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004894 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004895 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004896 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004897 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004898 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004899 CK_FloatingToIntegral);
4900 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004901 case Type::STK_Pointer:
4902 llvm_unreachable("valid float->pointer cast?");
4903 case Type::STK_MemberPointer:
4904 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004905 }
4906 break;
4907
John McCall8cb679e2010-11-15 09:13:47 +00004908 case Type::STK_FloatingComplex:
4909 switch (DestTy->getScalarTypeKind()) {
4910 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004911 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004912 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004913 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004914 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004915 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004916 if (S.Context.hasSameType(ET, DestTy))
4917 return CK_FloatingComplexToReal;
4918 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4919 return CK_FloatingCast;
4920 }
John McCall8cb679e2010-11-15 09:13:47 +00004921 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004922 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004923 case Type::STK_Integral:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004924 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004925 CK_FloatingComplexToReal);
4926 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004927 case Type::STK_Pointer:
4928 llvm_unreachable("valid complex float->pointer cast?");
4929 case Type::STK_MemberPointer:
4930 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004931 }
4932 break;
4933
John McCall8cb679e2010-11-15 09:13:47 +00004934 case Type::STK_IntegralComplex:
4935 switch (DestTy->getScalarTypeKind()) {
4936 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004937 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004938 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004939 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004940 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004941 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004942 if (S.Context.hasSameType(ET, DestTy))
4943 return CK_IntegralComplexToReal;
4944 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4945 return CK_IntegralCast;
4946 }
John McCall8cb679e2010-11-15 09:13:47 +00004947 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004948 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004949 case Type::STK_Floating:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004950 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004951 CK_IntegralComplexToReal);
4952 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004953 case Type::STK_Pointer:
4954 llvm_unreachable("valid complex int->pointer cast?");
4955 case Type::STK_MemberPointer:
4956 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004957 }
4958 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004959 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004960
John McCalld7646252010-11-14 08:17:51 +00004961 llvm_unreachable("Unhandled scalar cast");
4962 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00004963}
4964
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004965/// CheckCastTypes - Check type constraints for casting between types.
John McCall7decc9e2010-11-18 06:31:45 +00004966bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4967 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4968 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00004969 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00004970 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4971 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00004972 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00004973 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00004974
John McCall7decc9e2010-11-18 06:31:45 +00004975 // We only support r-value casts in C.
4976 VK = VK_RValue;
4977
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004978 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4979 // type needs to be scalar.
4980 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004981 // We don't necessarily do lvalue-to-rvalue conversions on this.
4982 IgnoredValueConversions(castExpr);
4983
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004984 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004985 Kind = CK_ToVoid;
Anders Carlssonef918ac2009-10-16 02:35:04 +00004986 return false;
4987 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004988
John McCall34376a62010-12-04 03:47:34 +00004989 DefaultFunctionArrayLvalueConversion(castExpr);
4990
Eli Friedmane98194d2010-07-17 20:43:49 +00004991 if (RequireCompleteType(TyR.getBegin(), castType,
4992 diag::err_typecheck_cast_to_incomplete))
4993 return true;
4994
Anders Carlssonef918ac2009-10-16 02:35:04 +00004995 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004996 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004997 (castType->isStructureType() || castType->isUnionType())) {
4998 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004999 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005000 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5001 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005002 Kind = CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00005003 return false;
5004 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005005
Anders Carlsson525b76b2009-10-16 02:48:28 +00005006 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005007 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005008 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005009 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005010 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005011 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005012 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00005013 castExpr->getType()) &&
5014 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005015 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5016 << castExpr->getSourceRange();
5017 break;
5018 }
5019 }
5020 if (Field == FieldEnd)
5021 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
5022 << castExpr->getType() << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005023 Kind = CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00005024 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005025 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005026
Anders Carlsson525b76b2009-10-16 02:48:28 +00005027 // Reject any other conversions to non-scalar types.
5028 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
5029 << castType << castExpr->getSourceRange();
5030 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005031
John McCalld7646252010-11-14 08:17:51 +00005032 // The type we're casting to is known to be a scalar or vector.
5033
5034 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005035 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00005036 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00005037 return Diag(castExpr->getLocStart(),
5038 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005039 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005040 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005041
5042 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00005043 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005044
Anders Carlsson525b76b2009-10-16 02:48:28 +00005045 if (castType->isVectorType())
5046 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
5047 if (castExpr->getType()->isVectorType())
5048 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
5049
John McCalld7646252010-11-14 08:17:51 +00005050 // The source and target types are both scalars, i.e.
5051 // - arithmetic types (fundamental, enum, and complex)
5052 // - all kinds of pointers
5053 // Note that member pointers were filtered out with C++, above.
5054
Anders Carlsson43d70f82009-10-16 05:23:41 +00005055 if (isa<ObjCSelectorExpr>(castExpr))
5056 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005057
John McCalld7646252010-11-14 08:17:51 +00005058 // If either type is a pointer, the other type has to be either an
5059 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00005060 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005061 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005062 if (!castExprType->isIntegralType(Context) &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005063 castExprType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005064 return Diag(castExpr->getLocStart(),
5065 diag::err_cast_pointer_from_non_pointer_int)
5066 << castExprType << castExpr->getSourceRange();
5067 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00005068 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005069 return Diag(castExpr->getLocStart(),
5070 diag::err_cast_pointer_to_non_pointer_int)
5071 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005072 }
Anders Carlsson094c4592009-10-18 18:12:03 +00005073
John McCalld7646252010-11-14 08:17:51 +00005074 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCall2b5c1b22010-08-12 21:44:57 +00005075
John McCalld7646252010-11-14 08:17:51 +00005076 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00005077 CheckCastAlign(castExpr, castType, TyR);
5078
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005079 return false;
5080}
5081
Anders Carlsson525b76b2009-10-16 02:48:28 +00005082bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005083 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005084 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005085
Anders Carlssonde71adf2007-11-27 05:51:55 +00005086 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00005087 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005088 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005089 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005090 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005091 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005092 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005093 } else
5094 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005095 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005096 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005097
John McCalle3027922010-08-25 11:45:40 +00005098 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005099 return false;
5100}
5101
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005102bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCalle3027922010-08-25 11:45:40 +00005103 CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005104 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005105
Anders Carlsson43d70f82009-10-16 05:23:41 +00005106 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005107
Nate Begemanc8961a42009-06-27 22:05:55 +00005108 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5109 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00005110 if (SrcTy->isVectorType()) {
5111 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
5112 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5113 << DestTy << SrcTy << R;
John McCalle3027922010-08-25 11:45:40 +00005114 Kind = CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00005115 return false;
5116 }
5117
Nate Begemanbd956c42009-06-28 02:36:38 +00005118 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00005119 // conversion will take place first from scalar to elt type, and then
5120 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00005121 if (SrcTy->isPointerType())
5122 return Diag(R.getBegin(),
5123 diag::err_invalid_conversion_between_vector_and_scalar)
5124 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00005125
5126 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5127 ImpCastExprToType(CastExpr, DestElemTy,
John McCalld7646252010-11-14 08:17:51 +00005128 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005129
John McCalle3027922010-08-25 11:45:40 +00005130 Kind = CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00005131 return false;
5132}
5133
John McCalldadc5752010-08-24 06:29:42 +00005134ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005135Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005136 SourceLocation RParenLoc, Expr *castExpr) {
5137 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00005138 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00005139
John McCall97513962010-01-15 18:39:57 +00005140 TypeSourceInfo *castTInfo;
5141 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5142 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00005143 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00005144
Nate Begeman5ec4b312009-08-10 23:49:36 +00005145 // If the Expr being casted is a ParenListExpr, handle it specially.
5146 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00005147 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00005148 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00005149
John McCallb268a282010-08-23 23:25:46 +00005150 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00005151}
5152
John McCalldadc5752010-08-24 06:29:42 +00005153ExprResult
John McCallebe54742010-01-15 18:56:44 +00005154Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00005155 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00005156 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00005157 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00005158 CXXCastPath BasePath;
John McCallebe54742010-01-15 18:56:44 +00005159 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCall7decc9e2010-11-18 06:31:45 +00005160 Kind, VK, BasePath))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005161 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00005162
John McCallcf142162010-08-07 06:22:56 +00005163 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +00005164 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00005165 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00005166 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00005167}
5168
Nate Begeman5ec4b312009-08-10 23:49:36 +00005169/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5170/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005171ExprResult
John McCallb268a282010-08-23 23:25:46 +00005172Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005173 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5174 if (!E)
5175 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00005176
John McCalldadc5752010-08-24 06:29:42 +00005177 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005178
Nate Begeman5ec4b312009-08-10 23:49:36 +00005179 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005180 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5181 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005182
John McCallb268a282010-08-23 23:25:46 +00005183 if (Result.isInvalid()) return ExprError();
5184
5185 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005186}
5187
John McCalldadc5752010-08-24 06:29:42 +00005188ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00005189Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00005190 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00005191 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00005192 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00005193 QualType Ty = TInfo->getType();
John Thompson781ad172010-06-30 22:55:51 +00005194 bool isAltiVecLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00005195
John Thompson781ad172010-06-30 22:55:51 +00005196 // Check for an altivec literal,
5197 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005198 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5199 if (PE->getNumExprs() == 0) {
5200 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5201 return ExprError();
5202 }
John Thompson781ad172010-06-30 22:55:51 +00005203 if (PE->getNumExprs() == 1) {
5204 if (!PE->getExpr(0)->getType()->isVectorType())
5205 isAltiVecLiteral = true;
5206 }
5207 else
5208 isAltiVecLiteral = true;
5209 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00005210
John Thompson781ad172010-06-30 22:55:51 +00005211 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
5212 // then handle it as such.
5213 if (isAltiVecLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005214 llvm::SmallVector<Expr *, 8> initExprs;
5215 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5216 initExprs.push_back(PE->getExpr(i));
5217
5218 // FIXME: This means that pretty-printing the final AST will produce curly
5219 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00005220 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5221 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00005222 initExprs.size(), RParenLoc);
5223 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00005224 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005225 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005226 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00005227 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00005228 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00005229 if (Result.isInvalid()) return ExprError();
5230 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005231 }
5232}
5233
John McCalldadc5752010-08-24 06:29:42 +00005234ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00005235 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005236 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00005237 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005238 unsigned nexprs = Val.size();
5239 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005240 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5241 Expr *expr;
5242 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5243 expr = new (Context) ParenExpr(L, R, exprs[0]);
5244 else
5245 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005246 return Owned(expr);
5247}
5248
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005249/// \brief Emit a specialized diagnostic when one expression is a null pointer
5250/// constant and the other is not a pointer.
5251bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5252 SourceLocation QuestionLoc) {
5253 Expr *NullExpr = LHS;
5254 Expr *NonPointerExpr = RHS;
5255 Expr::NullPointerConstantKind NullKind =
5256 NullExpr->isNullPointerConstant(Context,
5257 Expr::NPC_ValueDependentIsNotNull);
5258
5259 if (NullKind == Expr::NPCK_NotNull) {
5260 NullExpr = RHS;
5261 NonPointerExpr = LHS;
5262 NullKind =
5263 NullExpr->isNullPointerConstant(Context,
5264 Expr::NPC_ValueDependentIsNotNull);
5265 }
5266
5267 if (NullKind == Expr::NPCK_NotNull)
5268 return false;
5269
5270 if (NullKind == Expr::NPCK_ZeroInteger) {
5271 // In this case, check to make sure that we got here from a "NULL"
5272 // string in the source code.
5273 NullExpr = NullExpr->IgnoreParenImpCasts();
5274 SourceManager& SM = Context.getSourceManager();
5275 SourceLocation Loc = SM.getInstantiationLoc(NullExpr->getExprLoc());
5276 unsigned Len =
5277 Lexer::MeasureTokenLength(Loc, SM, Context.getLangOptions());
5278 if (Len != 4 || memcmp(SM.getCharacterData(Loc), "NULL", 4))
5279 return false;
5280 }
5281
5282 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5283 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5284 << NonPointerExpr->getType() << DiagType
5285 << NonPointerExpr->getSourceRange();
5286 return true;
5287}
5288
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005289/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5290/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00005291/// C99 6.5.15
5292QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005293 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00005294 SourceLocation QuestionLoc) {
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005295 // If both LHS and RHS are overloaded functions, try to resolve them.
5296 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
5297 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
5298 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
5299 if (LHSResult.isInvalid())
5300 return QualType();
5301
5302 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
5303 if (RHSResult.isInvalid())
5304 return QualType();
5305
5306 LHS = LHSResult.take();
5307 RHS = RHSResult.take();
5308 }
5309
Sebastian Redl1a99f442009-04-16 17:51:27 +00005310 // C++ is sufficiently different to merit its own checker.
5311 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00005312 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00005313
5314 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005315 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005316
Chris Lattner432cff52009-02-18 04:28:32 +00005317 UsualUnaryConversions(Cond);
John McCallc07a0c72011-02-17 10:25:35 +00005318 UsualUnaryConversions(LHS);
Chris Lattner432cff52009-02-18 04:28:32 +00005319 UsualUnaryConversions(RHS);
5320 QualType CondTy = Cond->getType();
5321 QualType LHSTy = LHS->getType();
5322 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00005323
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005324 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005325 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00005326 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5327 // Throw an error if its not either.
5328 if (getLangOptions().OpenCL) {
5329 if (!CondTy->isVectorType()) {
5330 Diag(Cond->getLocStart(),
5331 diag::err_typecheck_cond_expect_scalar_or_vector)
5332 << CondTy;
5333 return QualType();
5334 }
5335 }
5336 else {
5337 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5338 << CondTy;
5339 return QualType();
5340 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005341 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005342
Chris Lattnere2949f42008-01-06 22:42:25 +00005343 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005344 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5345 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00005346
Nate Begemanabb5a732010-09-20 22:41:17 +00005347 // OpenCL: If the condition is a vector, and both operands are scalar,
5348 // attempt to implicity convert them to the vector type to act like the
5349 // built in select.
5350 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5351 // Both operands should be of scalar type.
5352 if (!LHSTy->isScalarType()) {
5353 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5354 << CondTy;
5355 return QualType();
5356 }
5357 if (!RHSTy->isScalarType()) {
5358 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5359 << CondTy;
5360 return QualType();
5361 }
5362 // Implicity convert these scalars to the type of the condition.
5363 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5364 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5365 }
5366
Chris Lattnere2949f42008-01-06 22:42:25 +00005367 // If both operands have arithmetic type, do the usual arithmetic conversions
5368 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005369 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5370 UsualArithmeticConversions(LHS, RHS);
5371 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005372 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005373
Chris Lattnere2949f42008-01-06 22:42:25 +00005374 // If both operands are the same structure or union type, the result is that
5375 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005376 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5377 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005378 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005379 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005380 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005381 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005382 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005383 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005384
Chris Lattnere2949f42008-01-06 22:42:25 +00005385 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005386 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005387 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5388 if (!LHSTy->isVoidType())
5389 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5390 << RHS->getSourceRange();
5391 if (!RHSTy->isVoidType())
5392 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5393 << LHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005394 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5395 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005396 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005397 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005398 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5399 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005400 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005401 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005402 // promote the null to a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005403 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005404 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005405 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005406 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005407 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00005408 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005409 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005410 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005411
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005412 // All objective-c pointer type analysis is done here.
5413 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5414 QuestionLoc);
5415 if (!compositeType.isNull())
5416 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005417
5418
Steve Naroff05efa972009-07-01 14:36:47 +00005419 // Handle block pointer types.
5420 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5421 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5422 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5423 QualType destType = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005424 ImpCastExprToType(LHS, destType, CK_BitCast);
5425 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005426 return destType;
5427 }
5428 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005429 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005430 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005431 }
Steve Naroff05efa972009-07-01 14:36:47 +00005432 // We have 2 block pointer types.
5433 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5434 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005435 return LHSTy;
5436 }
Steve Naroff05efa972009-07-01 14:36:47 +00005437 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005438 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5439 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005440
Steve Naroff05efa972009-07-01 14:36:47 +00005441 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5442 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005443 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005444 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005445 // In this situation, we assume void* type. No especially good
5446 // reason, but this is what gcc does, and we do have to pick
5447 // to get a consistent AST.
5448 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005449 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5450 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005451 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005452 }
Steve Naroff05efa972009-07-01 14:36:47 +00005453 // The block pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005454 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5455 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005456 return LHSTy;
5457 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005458
Steve Naroff05efa972009-07-01 14:36:47 +00005459 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5460 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5461 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005462 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5463 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005464
5465 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5466 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5467 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005468 QualType destPointee
5469 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005470 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005471 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005472 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005473 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005474 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005475 return destType;
5476 }
5477 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005478 QualType destPointee
5479 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005480 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005481 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005482 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005483 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005484 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005485 return destType;
5486 }
5487
5488 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5489 // Two identical pointer types are always compatible.
5490 return LHSTy;
5491 }
5492 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5493 rhptee.getUnqualifiedType())) {
5494 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5495 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5496 // In this situation, we assume void* type. No especially good
5497 // reason, but this is what gcc does, and we do have to pick
5498 // to get a consistent AST.
5499 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005500 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5501 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005502 return incompatTy;
5503 }
5504 // The pointer types are compatible.
5505 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5506 // differently qualified versions of compatible types, the result type is
5507 // a pointer to an appropriately qualified version of the *composite*
5508 // type.
5509 // FIXME: Need to calculate the composite type.
5510 // FIXME: Need to add qualifiers
John McCalle3027922010-08-25 11:45:40 +00005511 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5512 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005513 return LHSTy;
5514 }
Mike Stump11289f42009-09-09 15:08:12 +00005515
John McCalle84af4e2010-11-13 01:35:44 +00005516 // GCC compatibility: soften pointer/integer mismatch. Note that
5517 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005518 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5519 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5520 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005521 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005522 return RHSTy;
5523 }
5524 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5525 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5526 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005527 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005528 return LHSTy;
5529 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005530
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005531 // Emit a better diagnostic if one of the expressions is a null pointer
5532 // constant and the other is not a pointer type. In this case, the user most
5533 // likely forgot to take the address of the other expression.
5534 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
5535 return QualType();
5536
Chris Lattnere2949f42008-01-06 22:42:25 +00005537 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005538 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5539 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005540 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005541}
5542
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005543/// FindCompositeObjCPointerType - Helper method to find composite type of
5544/// two objective-c pointer types of the two input expressions.
5545QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5546 SourceLocation QuestionLoc) {
5547 QualType LHSTy = LHS->getType();
5548 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005549
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005550 // Handle things like Class and struct objc_class*. Here we case the result
5551 // to the pseudo-builtin, because that will be implicitly cast back to the
5552 // redefinition type if an attempt is made to access its fields.
5553 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005554 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005555 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005556 return LHSTy;
5557 }
5558 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005559 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005560 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005561 return RHSTy;
5562 }
5563 // And the same for struct objc_object* / id
5564 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005565 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005566 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005567 return LHSTy;
5568 }
5569 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005570 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005571 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005572 return RHSTy;
5573 }
5574 // And the same for struct objc_selector* / SEL
5575 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005576 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005577 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005578 return LHSTy;
5579 }
5580 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005581 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005582 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005583 return RHSTy;
5584 }
5585 // Check constraints for Objective-C object pointers types.
5586 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005587
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005588 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5589 // Two identical object pointer types are always compatible.
5590 return LHSTy;
5591 }
5592 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5593 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5594 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005595
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005596 // If both operands are interfaces and either operand can be
5597 // assigned to the other, use that type as the composite
5598 // type. This allows
5599 // xxx ? (A*) a : (B*) b
5600 // where B is a subclass of A.
5601 //
5602 // Additionally, as for assignment, if either type is 'id'
5603 // allow silent coercion. Finally, if the types are
5604 // incompatible then make sure to use 'id' as the composite
5605 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005606
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005607 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5608 // It could return the composite type.
5609 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5610 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5611 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5612 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5613 } else if ((LHSTy->isObjCQualifiedIdType() ||
5614 RHSTy->isObjCQualifiedIdType()) &&
5615 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5616 // Need to handle "id<xx>" explicitly.
5617 // GCC allows qualified id and any Objective-C type to devolve to
5618 // id. Currently localizing to here until clear this should be
5619 // part of ObjCQualifiedIdTypesAreCompatible.
5620 compositeType = Context.getObjCIdType();
5621 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5622 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005623 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005624 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5625 ;
5626 else {
5627 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5628 << LHSTy << RHSTy
5629 << LHS->getSourceRange() << RHS->getSourceRange();
5630 QualType incompatTy = Context.getObjCIdType();
John McCalle3027922010-08-25 11:45:40 +00005631 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5632 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005633 return incompatTy;
5634 }
5635 // The object pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005636 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5637 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005638 return compositeType;
5639 }
5640 // Check Objective-C object pointer types and 'void *'
5641 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5642 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5643 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5644 QualType destPointee
5645 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5646 QualType destType = Context.getPointerType(destPointee);
5647 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005648 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005649 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005650 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005651 return destType;
5652 }
5653 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5654 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5655 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5656 QualType destPointee
5657 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5658 QualType destType = Context.getPointerType(destPointee);
5659 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005660 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005661 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005662 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005663 return destType;
5664 }
5665 return QualType();
5666}
5667
Steve Naroff83895f72007-09-16 03:34:24 +00005668/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005669/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005670ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005671 SourceLocation ColonLoc,
5672 Expr *CondExpr, Expr *LHSExpr,
5673 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005674 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5675 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005676 OpaqueValueExpr *opaqueValue = 0;
5677 Expr *commonExpr = 0;
5678 if (LHSExpr == 0) {
5679 commonExpr = CondExpr;
5680
5681 // We usually want to apply unary conversions *before* saving, except
5682 // in the special case of a C++ l-value conditional.
5683 if (!(getLangOptions().CPlusPlus
5684 && !commonExpr->isTypeDependent()
5685 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5686 && commonExpr->isGLValue()
5687 && commonExpr->isOrdinaryOrBitFieldObject()
5688 && RHSExpr->isOrdinaryOrBitFieldObject()
5689 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5690 UsualUnaryConversions(commonExpr);
5691 }
5692
5693 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5694 commonExpr->getType(),
5695 commonExpr->getValueKind(),
5696 commonExpr->getObjectKind());
5697 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005698 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005699
John McCall7decc9e2010-11-18 06:31:45 +00005700 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005701 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00005702 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCallc07a0c72011-02-17 10:25:35 +00005703 VK, OK, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00005704 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005705 return ExprError();
5706
John McCallc07a0c72011-02-17 10:25:35 +00005707 if (!commonExpr)
5708 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
5709 LHSExpr, ColonLoc,
5710 RHSExpr, result, VK, OK));
5711
5712 return Owned(new (Context)
5713 BinaryConditionalOperator(commonExpr, opaqueValue, CondExpr, LHSExpr,
5714 RHSExpr, QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005715}
5716
John McCallaba90822011-01-31 23:13:11 +00005717// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005718// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005719// routine is it effectively iqnores the qualifiers on the top level pointee.
5720// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5721// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005722static Sema::AssignConvertType
5723checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5724 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5725 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005726
Steve Naroff1f4d7272007-05-11 04:00:31 +00005727 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005728 const Type *lhptee, *rhptee;
5729 Qualifiers lhq, rhq;
5730 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5731 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005732
John McCallaba90822011-01-31 23:13:11 +00005733 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005734
5735 // C99 6.5.16.1p1: This following citation is common to constraints
5736 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5737 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005738 Qualifiers lq;
5739
5740 if (!lhq.compatiblyIncludes(rhq)) {
5741 // Treat address-space mismatches as fatal. TODO: address subspaces
5742 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5743 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5744
5745 // For GCC compatibility, other qualifier mismatches are treated
5746 // as still compatible in C.
5747 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5748 }
Steve Naroff3f597292007-05-11 22:18:03 +00005749
Mike Stump4e1f26a2009-02-19 03:04:26 +00005750 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5751 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005752 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005753 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005754 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005755 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005756
Chris Lattner0a788432008-01-03 22:56:36 +00005757 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005758 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005759 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005760 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005761
Chris Lattner0a788432008-01-03 22:56:36 +00005762 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005763 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005764 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005765
5766 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005767 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005768 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005769 }
John McCall4fff8f62011-02-01 00:10:29 +00005770
Mike Stump4e1f26a2009-02-19 03:04:26 +00005771 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005772 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005773 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5774 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005775 // Check if the pointee types are compatible ignoring the sign.
5776 // We explicitly check for char so that we catch "char" vs
5777 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005778 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005779 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005780 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005781 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005782
Chris Lattnerec3a1562009-10-17 20:33:28 +00005783 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005784 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005785 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005786 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005787
John McCall4fff8f62011-02-01 00:10:29 +00005788 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005789 // Types are compatible ignoring the sign. Qualifier incompatibility
5790 // takes priority over sign incompatibility because the sign
5791 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005792 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005793 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005794
John McCallaba90822011-01-31 23:13:11 +00005795 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005796 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005797
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005798 // If we are a multi-level pointer, it's possible that our issue is simply
5799 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5800 // the eventual target type is the same and the pointers have the same
5801 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005802 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005803 do {
John McCall4fff8f62011-02-01 00:10:29 +00005804 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5805 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005806 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005807
John McCall4fff8f62011-02-01 00:10:29 +00005808 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005809 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005810 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005811
Eli Friedman80160bd2009-03-22 23:59:44 +00005812 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005813 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005814 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005815 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005816}
5817
John McCallaba90822011-01-31 23:13:11 +00005818/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005819/// block pointer types are compatible or whether a block and normal pointer
5820/// are compatible. It is more restrict than comparing two function pointer
5821// types.
John McCallaba90822011-01-31 23:13:11 +00005822static Sema::AssignConvertType
5823checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5824 QualType rhsType) {
5825 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5826 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5827
Steve Naroff081c7422008-09-04 15:10:53 +00005828 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005829
Steve Naroff081c7422008-09-04 15:10:53 +00005830 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005831 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5832 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005833
John McCallaba90822011-01-31 23:13:11 +00005834 // In C++, the types have to match exactly.
5835 if (S.getLangOptions().CPlusPlus)
5836 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005837
John McCallaba90822011-01-31 23:13:11 +00005838 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005839
Steve Naroff081c7422008-09-04 15:10:53 +00005840 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005841 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5842 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005843
John McCallaba90822011-01-31 23:13:11 +00005844 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5845 return Sema::IncompatibleBlockPointer;
5846
Steve Naroff081c7422008-09-04 15:10:53 +00005847 return ConvTy;
5848}
5849
John McCallaba90822011-01-31 23:13:11 +00005850/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005851/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005852static Sema::AssignConvertType
5853checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5854 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5855 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5856
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005857 if (lhsType->isObjCBuiltinType()) {
5858 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005859 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5860 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005861 return Sema::IncompatiblePointer;
5862 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005863 }
5864 if (rhsType->isObjCBuiltinType()) {
5865 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005866 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5867 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005868 return Sema::IncompatiblePointer;
5869 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005870 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005871 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005872 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005873 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005874 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005875
John McCallaba90822011-01-31 23:13:11 +00005876 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5877 return Sema::CompatiblePointerDiscardsQualifiers;
5878
5879 if (S.Context.typesAreCompatible(lhsType, rhsType))
5880 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005881 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005882 return Sema::IncompatibleObjCQualifiedId;
5883 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005884}
5885
John McCall29600e12010-11-16 02:32:08 +00005886Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005887Sema::CheckAssignmentConstraints(SourceLocation Loc,
5888 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005889 // Fake up an opaque expression. We don't actually care about what
5890 // cast operations are required, so if CheckAssignmentConstraints
5891 // adds casts to this they'll be wasted, but fortunately that doesn't
5892 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00005893 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John McCall29600e12010-11-16 02:32:08 +00005894 Expr *rhsPtr = &rhs;
5895 CastKind K = CK_Invalid;
5896
5897 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5898}
5899
Mike Stump4e1f26a2009-02-19 03:04:26 +00005900/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5901/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005902/// pointers. Here are some objectionable examples that GCC considers warnings:
5903///
5904/// int a, *pint;
5905/// short *pshort;
5906/// struct foo *pfoo;
5907///
5908/// pint = pshort; // warning: assignment from incompatible pointer type
5909/// a = pint; // warning: assignment makes integer from pointer without a cast
5910/// pint = a; // warning: assignment makes pointer from integer without a cast
5911/// pint = pfoo; // warning: assignment from incompatible pointer type
5912///
5913/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005914/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005915///
John McCall8cb679e2010-11-15 09:13:47 +00005916/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005917Sema::AssignConvertType
John McCall29600e12010-11-16 02:32:08 +00005918Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005919 CastKind &Kind) {
John McCall29600e12010-11-16 02:32:08 +00005920 QualType rhsType = rhs->getType();
5921
Chris Lattnera52c2f22008-01-04 23:18:45 +00005922 // Get canonical types. We're not formatting these types, just comparing
5923 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005924 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5925 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005926
John McCalle5255932011-01-31 22:28:28 +00005927 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00005928 if (lhsType == rhsType) {
5929 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005930 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005931 }
5932
Douglas Gregor6b754842008-10-28 00:22:11 +00005933 // If the left-hand side is a reference type, then we are in a
5934 // (rare!) case where we've allowed the use of references in C,
5935 // e.g., as a parameter type in a built-in function. In this case,
5936 // just make sure that the type referenced is compatible with the
5937 // right-hand side type. The caller is responsible for adjusting
5938 // lhsType so that the resulting expression does not have reference
5939 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005940 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005941 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5942 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005943 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005944 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005945 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005946 }
John McCalle5255932011-01-31 22:28:28 +00005947
Nate Begemanbd956c42009-06-28 02:36:38 +00005948 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5949 // to the same ExtVector type.
5950 if (lhsType->isExtVectorType()) {
5951 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005952 return Incompatible;
5953 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005954 // CK_VectorSplat does T -> vector T, so first cast to the
5955 // element type.
5956 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5957 if (elType != rhsType) {
5958 Kind = PrepareScalarCast(*this, rhs, elType);
5959 ImpCastExprToType(rhs, elType, Kind);
5960 }
5961 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005962 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005963 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005964 }
Mike Stump11289f42009-09-09 15:08:12 +00005965
John McCalle5255932011-01-31 22:28:28 +00005966 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00005967 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005968 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005969 // Allow assignments of an AltiVec vector type to an equivalent GCC
5970 // vector type and vice versa
5971 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5972 Kind = CK_BitCast;
5973 return Compatible;
5974 }
5975
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005976 // If we are allowing lax vector conversions, and LHS and RHS are both
5977 // vectors, the total size only needs to be the same. This is a bitcast;
5978 // no bits are changed but the result type is different.
5979 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005980 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005981 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005982 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005983 }
Chris Lattner881a2122008-01-04 23:32:24 +00005984 }
5985 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005986 }
Eli Friedman3360d892008-05-30 18:07:22 +00005987
John McCalle5255932011-01-31 22:28:28 +00005988 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00005989 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005990 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005991 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005992 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005993 }
Eli Friedman3360d892008-05-30 18:07:22 +00005994
John McCalle5255932011-01-31 22:28:28 +00005995 // Conversions to normal pointers.
5996 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5997 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00005998 if (isa<PointerType>(rhsType)) {
5999 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006000 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00006001 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006002
John McCalle5255932011-01-31 22:28:28 +00006003 // int -> T*
6004 if (rhsType->isIntegerType()) {
6005 Kind = CK_IntegralToPointer; // FIXME: null?
6006 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006007 }
John McCalle5255932011-01-31 22:28:28 +00006008
6009 // C pointers are not compatible with ObjC object pointers,
6010 // with two exceptions:
6011 if (isa<ObjCObjectPointerType>(rhsType)) {
6012 // - conversions to void*
6013 if (lhsPointer->getPointeeType()->isVoidType()) {
6014 Kind = CK_AnyPointerToObjCPointerCast;
6015 return Compatible;
6016 }
6017
6018 // - conversions from 'Class' to the redefinition type
6019 if (rhsType->isObjCClassType() &&
6020 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006021 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006022 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006023 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006024
John McCalle5255932011-01-31 22:28:28 +00006025 Kind = CK_BitCast;
6026 return IncompatiblePointer;
6027 }
6028
6029 // U^ -> void*
6030 if (rhsType->getAs<BlockPointerType>()) {
6031 if (lhsPointer->getPointeeType()->isVoidType()) {
6032 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006033 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006034 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006035 }
John McCalle5255932011-01-31 22:28:28 +00006036
Steve Naroff081c7422008-09-04 15:10:53 +00006037 return Incompatible;
6038 }
6039
John McCalle5255932011-01-31 22:28:28 +00006040 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00006041 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006042 // U^ -> T^
6043 if (rhsType->isBlockPointerType()) {
6044 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00006045 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006046 }
6047
6048 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006049 if (rhsType->isIntegerType()) {
6050 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00006051 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006052 }
6053
John McCalle5255932011-01-31 22:28:28 +00006054 // id -> T^
6055 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6056 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006057 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006058 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006059
John McCalle5255932011-01-31 22:28:28 +00006060 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006061 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00006062 if (RHSPT->getPointeeType()->isVoidType()) {
6063 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006064 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006065 }
John McCall8cb679e2010-11-15 09:13:47 +00006066
Chris Lattnera52c2f22008-01-04 23:18:45 +00006067 return Incompatible;
6068 }
6069
John McCalle5255932011-01-31 22:28:28 +00006070 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006071 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006072 // A* -> B*
6073 if (rhsType->isObjCObjectPointerType()) {
6074 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006075 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006076 }
6077
6078 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00006079 if (rhsType->isIntegerType()) {
6080 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00006081 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006082 }
6083
John McCalle5255932011-01-31 22:28:28 +00006084 // In general, C pointers are not compatible with ObjC object pointers,
6085 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00006086 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006087 // - conversions from 'void*'
6088 if (rhsType->isVoidPointerType()) {
6089 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006090 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006091 }
6092
6093 // - conversions to 'Class' from its redefinition type
6094 if (lhsType->isObjCClassType() &&
6095 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6096 Kind = CK_BitCast;
6097 return Compatible;
6098 }
6099
6100 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006101 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006102 }
John McCalle5255932011-01-31 22:28:28 +00006103
6104 // T^ -> A*
6105 if (rhsType->isBlockPointerType()) {
6106 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006107 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006108 }
6109
Steve Naroff7cae42b2009-07-10 23:34:53 +00006110 return Incompatible;
6111 }
John McCalle5255932011-01-31 22:28:28 +00006112
6113 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00006114 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006115 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006116 if (lhsType == Context.BoolTy) {
6117 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00006118 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006119 }
Eli Friedman3360d892008-05-30 18:07:22 +00006120
John McCalle5255932011-01-31 22:28:28 +00006121 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006122 if (lhsType->isIntegerType()) {
6123 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006124 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006125 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006126
Chris Lattnera52c2f22008-01-04 23:18:45 +00006127 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00006128 }
John McCalle5255932011-01-31 22:28:28 +00006129
6130 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006131 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006132 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006133 if (lhsType == Context.BoolTy) {
6134 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006135 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006136 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006137
John McCalle5255932011-01-31 22:28:28 +00006138 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006139 if (lhsType->isIntegerType()) {
6140 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006141 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006142 }
6143
Steve Naroff7cae42b2009-07-10 23:34:53 +00006144 return Incompatible;
6145 }
Eli Friedman3360d892008-05-30 18:07:22 +00006146
John McCalle5255932011-01-31 22:28:28 +00006147 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00006148 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006149 if (Context.typesAreCompatible(lhsType, rhsType)) {
6150 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00006151 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006152 }
Bill Wendling216423b2007-05-30 06:30:29 +00006153 }
John McCalle5255932011-01-31 22:28:28 +00006154
Steve Naroff98cf3e92007-06-06 18:38:38 +00006155 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00006156}
6157
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006158/// \brief Constructs a transparent union from an expression that is
6159/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00006160static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006161 QualType UnionType, FieldDecl *Field) {
6162 // Build an initializer list that designates the appropriate member
6163 // of the transparent union.
Ted Kremenekac034612010-04-13 23:39:13 +00006164 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00006165 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006166 SourceLocation());
6167 Initializer->setType(UnionType);
6168 Initializer->setInitializedFieldInUnion(Field);
6169
6170 // Build a compound literal constructing a value of the transparent
6171 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00006172 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00006173 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall7decc9e2010-11-18 06:31:45 +00006174 VK_RValue, Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006175}
6176
6177Sema::AssignConvertType
6178Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
6179 QualType FromType = rExpr->getType();
6180
Mike Stump11289f42009-09-09 15:08:12 +00006181 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006182 // transparent_union GCC extension.
6183 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006184 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006185 return Incompatible;
6186
6187 // The field to initialize within the transparent union.
6188 RecordDecl *UD = UT->getDecl();
6189 FieldDecl *InitField = 0;
6190 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006191 for (RecordDecl::field_iterator it = UD->field_begin(),
6192 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006193 it != itend; ++it) {
6194 if (it->getType()->isPointerType()) {
6195 // If the transparent union contains a pointer type, we allow:
6196 // 1) void pointer
6197 // 2) null pointer constant
6198 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006199 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +00006200 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006201 InitField = *it;
6202 break;
6203 }
Mike Stump11289f42009-09-09 15:08:12 +00006204
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006205 if (rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006206 Expr::NPC_ValueDependentIsNull)) {
John McCalle84af4e2010-11-13 01:35:44 +00006207 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006208 InitField = *it;
6209 break;
6210 }
6211 }
6212
John McCall29600e12010-11-16 02:32:08 +00006213 Expr *rhs = rExpr;
John McCall8cb679e2010-11-15 09:13:47 +00006214 CastKind Kind = CK_Invalid;
John McCall29600e12010-11-16 02:32:08 +00006215 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006216 == Compatible) {
John McCall29600e12010-11-16 02:32:08 +00006217 ImpCastExprToType(rhs, it->getType(), Kind);
6218 rExpr = rhs;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006219 InitField = *it;
6220 break;
6221 }
6222 }
6223
6224 if (!InitField)
6225 return Incompatible;
6226
6227 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
6228 return Compatible;
6229}
6230
Chris Lattner9bad62c2008-01-04 18:04:52 +00006231Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006232Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00006233 if (getLangOptions().CPlusPlus) {
6234 if (!lhsType->isRecordType()) {
6235 // C++ 5.17p3: If the left operand is not of class type, the
6236 // expression is implicitly converted (C++ 4) to the
6237 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00006238 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006239 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00006240 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00006241 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00006242 }
6243
6244 // FIXME: Currently, we fall through and treat C++ classes like C
6245 // structures.
John McCall34376a62010-12-04 03:47:34 +00006246 }
Douglas Gregor9a657932008-10-21 23:43:52 +00006247
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006248 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6249 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00006250 if ((lhsType->isPointerType() ||
6251 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00006252 lhsType->isBlockPointerType())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006253 && rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006254 Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00006255 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006256 return Compatible;
6257 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006258
Chris Lattnere6dcd502007-10-16 02:55:40 +00006259 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006260 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00006261 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00006262 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00006263 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00006264 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00006265 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00006266 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006267
John McCall8cb679e2010-11-15 09:13:47 +00006268 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006269 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00006270 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006271
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006272 // C99 6.5.16.1p2: The value of the right operand is converted to the
6273 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006274 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6275 // so that we can use references in built-in functions even in C.
6276 // The getNonReferenceType() call makes sure that the resulting expression
6277 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006278 if (result != Incompatible && rExpr->getType() != lhsType)
John McCall8cb679e2010-11-15 09:13:47 +00006279 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006280 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006281}
6282
Chris Lattner326f7572008-11-18 01:30:42 +00006283QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006284 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006285 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00006286 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006287 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006288}
6289
Chris Lattnerfaa54172010-01-12 21:23:57 +00006290QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00006291 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006292 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00006293 QualType lhsType =
6294 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
6295 QualType rhsType =
6296 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006297
Nate Begeman191a6b12008-07-14 18:02:46 +00006298 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006299 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00006300 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006301
Nate Begeman191a6b12008-07-14 18:02:46 +00006302 // Handle the case of a vector & extvector type of the same size and element
6303 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006304 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00006305 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006306 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006307 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006308 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006309 if (lhsType->isExtVectorType()) {
John McCalle3027922010-08-25 11:45:40 +00006310 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006311 return lhsType;
6312 }
6313
John McCalle3027922010-08-25 11:45:40 +00006314 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006315 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00006316 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6317 // If we are allowing lax vector conversions, and LHS and RHS are both
6318 // vectors, the total size only needs to be the same. This is a
6319 // bitcast; no bits are changed but the result type is different.
6320 ImpCastExprToType(rex, lhsType, CK_BitCast);
6321 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006322 }
Eric Christophera613f562010-08-26 00:42:16 +00006323 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006324 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006325 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006326
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006327 // Handle the case of equivalent AltiVec and GCC vector types
6328 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6329 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCalle3027922010-08-25 11:45:40 +00006330 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006331 return rhsType;
6332 }
6333
Nate Begemanbd956c42009-06-28 02:36:38 +00006334 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6335 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6336 bool swapped = false;
6337 if (rhsType->isExtVectorType()) {
6338 swapped = true;
6339 std::swap(rex, lex);
6340 std::swap(rhsType, lhsType);
6341 }
Mike Stump11289f42009-09-09 15:08:12 +00006342
Nate Begeman886448d2009-06-28 19:12:57 +00006343 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00006344 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006345 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00006346 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00006347 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6348 if (order > 0)
6349 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
6350 if (order >= 0) {
6351 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006352 if (swapped) std::swap(rex, lex);
6353 return lhsType;
6354 }
6355 }
6356 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6357 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00006358 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6359 if (order > 0)
6360 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
6361 if (order >= 0) {
6362 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006363 if (swapped) std::swap(rex, lex);
6364 return lhsType;
6365 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006366 }
6367 }
Mike Stump11289f42009-09-09 15:08:12 +00006368
Nate Begeman886448d2009-06-28 19:12:57 +00006369 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00006370 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006371 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00006372 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006373 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006374}
6375
Chris Lattnerfaa54172010-01-12 21:23:57 +00006376QualType Sema::CheckMultiplyDivideOperands(
6377 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00006378 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006379 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006380
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006381 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006382
Chris Lattnerfaa54172010-01-12 21:23:57 +00006383 if (!lex->getType()->isArithmeticType() ||
6384 !rex->getType()->isArithmeticType())
6385 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006386
Chris Lattnerfaa54172010-01-12 21:23:57 +00006387 // Check for division by zero.
6388 if (isDiv &&
6389 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Ted Kremenek55ae3192011-02-23 01:51:43 +00006390 DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_division_by_zero)
6391 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006392
Chris Lattnerfaa54172010-01-12 21:23:57 +00006393 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006394}
6395
Chris Lattnerfaa54172010-01-12 21:23:57 +00006396QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00006397 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006398 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006399 if (lex->getType()->hasIntegerRepresentation() &&
6400 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006401 return CheckVectorOperands(Loc, lex, rex);
6402 return InvalidOperands(Loc, lex, rex);
6403 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006404
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006405 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006406
Chris Lattnerfaa54172010-01-12 21:23:57 +00006407 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6408 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006409
Chris Lattnerfaa54172010-01-12 21:23:57 +00006410 // Check for remainder by zero.
6411 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Ted Kremenek55ae3192011-02-23 01:51:43 +00006412 DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_remainder_by_zero)
6413 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006414
Chris Lattnerfaa54172010-01-12 21:23:57 +00006415 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006416}
6417
Chris Lattnerfaa54172010-01-12 21:23:57 +00006418QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00006419 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006420 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6421 QualType compType = CheckVectorOperands(Loc, lex, rex);
6422 if (CompLHSTy) *CompLHSTy = compType;
6423 return compType;
6424 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006425
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006426 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006427
Steve Naroffe4718892007-04-27 18:30:00 +00006428 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006429 if (lex->getType()->isArithmeticType() &&
6430 rex->getType()->isArithmeticType()) {
6431 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006432 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006433 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006434
Eli Friedman8e122982008-05-18 18:08:51 +00006435 // Put any potential pointer into PExp
6436 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00006437 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006438 std::swap(PExp, IExp);
6439
Steve Naroff6b712a72009-07-14 18:25:06 +00006440 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006441
Eli Friedman8e122982008-05-18 18:08:51 +00006442 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006443 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006444
Chris Lattner12bdebb2009-04-24 23:50:08 +00006445 // Check for arithmetic on pointers to incomplete types.
6446 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006447 if (getLangOptions().CPlusPlus) {
6448 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00006449 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00006450 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006451 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006452
6453 // GNU extension: arithmetic on pointer to void
6454 Diag(Loc, diag::ext_gnu_void_ptr)
6455 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006456 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006457 if (getLangOptions().CPlusPlus) {
6458 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6459 << lex->getType() << lex->getSourceRange();
6460 return QualType();
6461 }
6462
6463 // GNU extension: arithmetic on pointer to function
6464 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6465 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00006466 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006467 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00006468 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00006469 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006470 PExp->getType()->isObjCObjectPointerType()) &&
6471 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00006472 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6473 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006474 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006475 return QualType();
6476 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00006477 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006478 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006479 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6480 << PointeeTy << PExp->getSourceRange();
6481 return QualType();
6482 }
Mike Stump11289f42009-09-09 15:08:12 +00006483
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006484 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00006485 QualType LHSTy = Context.isPromotableBitField(lex);
6486 if (LHSTy.isNull()) {
6487 LHSTy = lex->getType();
6488 if (LHSTy->isPromotableIntegerType())
6489 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006490 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006491 *CompLHSTy = LHSTy;
6492 }
Eli Friedman8e122982008-05-18 18:08:51 +00006493 return PExp->getType();
6494 }
6495 }
6496
Chris Lattner326f7572008-11-18 01:30:42 +00006497 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006498}
6499
Chris Lattner2a3569b2008-04-07 05:30:13 +00006500// C99 6.5.6
6501QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006502 SourceLocation Loc, QualType* CompLHSTy) {
6503 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6504 QualType compType = CheckVectorOperands(Loc, lex, rex);
6505 if (CompLHSTy) *CompLHSTy = compType;
6506 return compType;
6507 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006508
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006509 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006510
Chris Lattner4d62f422007-12-09 21:53:25 +00006511 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006512
Chris Lattner4d62f422007-12-09 21:53:25 +00006513 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00006514 if (lex->getType()->isArithmeticType()
6515 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006516 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006517 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006518 }
Mike Stump11289f42009-09-09 15:08:12 +00006519
Chris Lattner4d62f422007-12-09 21:53:25 +00006520 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00006521 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00006522 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006523
Douglas Gregorac1fb652009-03-24 19:52:54 +00006524 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006525
Douglas Gregorac1fb652009-03-24 19:52:54 +00006526 bool ComplainAboutVoid = false;
6527 Expr *ComplainAboutFunc = 0;
6528 if (lpointee->isVoidType()) {
6529 if (getLangOptions().CPlusPlus) {
6530 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6531 << lex->getSourceRange() << rex->getSourceRange();
6532 return QualType();
6533 }
6534
6535 // GNU C extension: arithmetic on pointer to void
6536 ComplainAboutVoid = true;
6537 } else if (lpointee->isFunctionType()) {
6538 if (getLangOptions().CPlusPlus) {
6539 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006540 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006541 return QualType();
6542 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006543
6544 // GNU C extension: arithmetic on pointer to function
6545 ComplainAboutFunc = lex;
6546 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00006547 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006548 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00006549 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006550 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006551 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006552
Chris Lattner12bdebb2009-04-24 23:50:08 +00006553 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006554 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006555 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6556 << lpointee << lex->getSourceRange();
6557 return QualType();
6558 }
Mike Stump11289f42009-09-09 15:08:12 +00006559
Chris Lattner4d62f422007-12-09 21:53:25 +00006560 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00006561 if (rex->getType()->isIntegerType()) {
6562 if (ComplainAboutVoid)
6563 Diag(Loc, diag::ext_gnu_void_ptr)
6564 << lex->getSourceRange() << rex->getSourceRange();
6565 if (ComplainAboutFunc)
6566 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006567 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006568 << ComplainAboutFunc->getSourceRange();
6569
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006570 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006571 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006572 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006573
Chris Lattner4d62f422007-12-09 21:53:25 +00006574 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006575 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006576 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006577
Douglas Gregorac1fb652009-03-24 19:52:54 +00006578 // RHS must be a completely-type object type.
6579 // Handle the GNU void* extension.
6580 if (rpointee->isVoidType()) {
6581 if (getLangOptions().CPlusPlus) {
6582 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6583 << lex->getSourceRange() << rex->getSourceRange();
6584 return QualType();
6585 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006586
Douglas Gregorac1fb652009-03-24 19:52:54 +00006587 ComplainAboutVoid = true;
6588 } else if (rpointee->isFunctionType()) {
6589 if (getLangOptions().CPlusPlus) {
6590 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006591 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006592 return QualType();
6593 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006594
6595 // GNU extension: arithmetic on pointer to function
6596 if (!ComplainAboutFunc)
6597 ComplainAboutFunc = rex;
6598 } else if (!rpointee->isDependentType() &&
6599 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006600 PDiag(diag::err_typecheck_sub_ptr_object)
6601 << rex->getSourceRange()
6602 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006603 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006604
Eli Friedman168fe152009-05-16 13:54:38 +00006605 if (getLangOptions().CPlusPlus) {
6606 // Pointee types must be the same: C++ [expr.add]
6607 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6608 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6609 << lex->getType() << rex->getType()
6610 << lex->getSourceRange() << rex->getSourceRange();
6611 return QualType();
6612 }
6613 } else {
6614 // Pointee types must be compatible C99 6.5.6p3
6615 if (!Context.typesAreCompatible(
6616 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6617 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6618 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6619 << lex->getType() << rex->getType()
6620 << lex->getSourceRange() << rex->getSourceRange();
6621 return QualType();
6622 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006623 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006624
Douglas Gregorac1fb652009-03-24 19:52:54 +00006625 if (ComplainAboutVoid)
6626 Diag(Loc, diag::ext_gnu_void_ptr)
6627 << lex->getSourceRange() << rex->getSourceRange();
6628 if (ComplainAboutFunc)
6629 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006630 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006631 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006632
6633 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006634 return Context.getPointerDiffType();
6635 }
6636 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006637
Chris Lattner326f7572008-11-18 01:30:42 +00006638 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006639}
6640
Douglas Gregor0bf31402010-10-08 23:50:27 +00006641static bool isScopedEnumerationType(QualType T) {
6642 if (const EnumType *ET = dyn_cast<EnumType>(T))
6643 return ET->getDecl()->isScoped();
6644 return false;
6645}
6646
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006647static void DiagnoseBadShiftValues(Sema& S, Expr *&lex, Expr *&rex,
6648 SourceLocation Loc, unsigned Opc,
6649 QualType LHSTy) {
6650 llvm::APSInt Right;
6651 // Check right/shifter operand
6652 if (rex->isValueDependent() || !rex->isIntegerConstantExpr(Right, S.Context))
6653 return;
6654
6655 if (Right.isNegative()) {
6656 S.Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6657 return;
6658 }
6659 llvm::APInt LeftBits(Right.getBitWidth(),
6660 S.Context.getTypeSize(lex->getType()));
6661 if (Right.uge(LeftBits)) {
6662 S.Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6663 return;
6664 }
6665 if (Opc != BO_Shl)
6666 return;
6667
6668 // When left shifting an ICE which is signed, we can check for overflow which
6669 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6670 // integers have defined behavior modulo one more than the maximum value
6671 // representable in the result type, so never warn for those.
6672 llvm::APSInt Left;
Chandler Carruth60ed89d2011-02-24 00:03:53 +00006673 if (lex->isValueDependent() || !lex->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006674 LHSTy->hasUnsignedIntegerRepresentation())
6675 return;
6676 llvm::APInt ResultBits =
6677 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6678 if (LeftBits.uge(ResultBits))
6679 return;
6680 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6681 Result = Result.shl(Right);
6682
6683 // If we are only missing a sign bit, this is less likely to result in actual
6684 // bugs -- if the result is cast back to an unsigned type, it will have the
6685 // expected value. Thus we place this behind a different warning that can be
6686 // turned off separately if needed.
6687 if (LeftBits == ResultBits - 1) {
6688 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
6689 << Result.toString(10) << LHSTy
6690 << lex->getSourceRange() << rex->getSourceRange();
6691 return;
6692 }
6693
6694 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6695 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
6696 << Left.getBitWidth() << lex->getSourceRange() << rex->getSourceRange();
6697}
6698
Chris Lattner2a3569b2008-04-07 05:30:13 +00006699// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00006700QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006701 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006702 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006703 if (!lex->getType()->hasIntegerRepresentation() ||
6704 !rex->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006705 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006706
Douglas Gregor0bf31402010-10-08 23:50:27 +00006707 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6708 // hasIntegerRepresentation() above instead of this.
6709 if (isScopedEnumerationType(lex->getType()) ||
6710 isScopedEnumerationType(rex->getType())) {
6711 return InvalidOperands(Loc, lex, rex);
6712 }
6713
Nate Begemane46ee9a2009-10-25 02:26:48 +00006714 // Vector shifts promote their scalar inputs to vector type.
6715 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6716 return CheckVectorOperands(Loc, lex, rex);
6717
Chris Lattner5c11c412007-12-12 05:47:28 +00006718 // Shifts don't perform usual arithmetic conversions, they just do integer
6719 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006720
John McCall57cdd882010-12-16 19:28:59 +00006721 // For the LHS, do usual unary conversions, but then reset them away
6722 // if this is a compound assignment.
6723 Expr *old_lex = lex;
6724 UsualUnaryConversions(lex);
6725 QualType LHSTy = lex->getType();
6726 if (isCompAssign) lex = old_lex;
6727
6728 // The RHS is simpler.
Chris Lattner5c11c412007-12-12 05:47:28 +00006729 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006730
Ryan Flynnf53fab82009-08-07 16:20:20 +00006731 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006732 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006733
Chris Lattner5c11c412007-12-12 05:47:28 +00006734 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006735 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006736}
6737
Chandler Carruth17773fc2010-07-10 12:30:03 +00006738static bool IsWithinTemplateSpecialization(Decl *D) {
6739 if (DeclContext *DC = D->getDeclContext()) {
6740 if (isa<ClassTemplateSpecializationDecl>(DC))
6741 return true;
6742 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6743 return FD->isFunctionTemplateSpecialization();
6744 }
6745 return false;
6746}
6747
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006748// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00006749QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006750 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006751 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006752
Chris Lattner9a152e22009-12-05 05:40:13 +00006753 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00006754 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006755 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006756
Steve Naroff31090012007-07-16 21:54:35 +00006757 QualType lType = lex->getType();
6758 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006759
Chandler Carruth712563b2011-02-17 08:37:06 +00006760 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6761 Expr *RHSStripped = rex->IgnoreParenImpCasts();
6762 QualType LHSStrippedType = LHSStripped->getType();
6763 QualType RHSStrippedType = RHSStripped->getType();
6764
6765 // Two different enums will raise a warning when compared.
6766 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6767 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6768 if (LHSEnumType->getDecl()->getIdentifier() &&
6769 RHSEnumType->getDecl()->getIdentifier() &&
6770 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6771 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6772 << LHSStrippedType << RHSStrippedType
6773 << lex->getSourceRange() << rex->getSourceRange();
6774 }
6775 }
6776 }
6777
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006778 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006779 !(lType->isBlockPointerType() && isRelational) &&
6780 !lex->getLocStart().isMacroID() &&
6781 !rex->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006782 // For non-floating point types, check for self-comparisons of the form
6783 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6784 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006785 //
6786 // NOTE: Don't warn about comparison expressions resulting from macro
6787 // expansion. Also don't warn about comparisons which are only self
6788 // comparisons within a template specialization. The warnings should catch
6789 // obvious cases in the definition of the template anyways. The idea is to
6790 // warn when the typed comparison operator will always evaluate to the same
6791 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006792 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006793 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006794 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006795 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006796 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006797 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006798 << (Opc == BO_EQ
6799 || Opc == BO_LE
6800 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006801 } else if (lType->isArrayType() && rType->isArrayType() &&
6802 !DRL->getDecl()->getType()->isReferenceType() &&
6803 !DRR->getDecl()->getType()->isReferenceType()) {
6804 // what is it always going to eval to?
6805 char always_evals_to;
6806 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006807 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006808 always_evals_to = 0; // false
6809 break;
John McCalle3027922010-08-25 11:45:40 +00006810 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006811 always_evals_to = 1; // true
6812 break;
6813 default:
6814 // best we can say is 'a constant'
6815 always_evals_to = 2; // e.g. array1 <= array2
6816 break;
6817 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006818 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006819 << 1 // array
6820 << always_evals_to);
6821 }
6822 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006823 }
Mike Stump11289f42009-09-09 15:08:12 +00006824
Chris Lattner222b8bd2009-03-08 19:39:53 +00006825 if (isa<CastExpr>(LHSStripped))
6826 LHSStripped = LHSStripped->IgnoreParenCasts();
6827 if (isa<CastExpr>(RHSStripped))
6828 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006829
Chris Lattner222b8bd2009-03-08 19:39:53 +00006830 // Warn about comparisons against a string constant (unless the other
6831 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006832 Expr *literalString = 0;
6833 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006834 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006835 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006836 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006837 literalString = lex;
6838 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006839 } else if ((isa<StringLiteral>(RHSStripped) ||
6840 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006841 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006842 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006843 literalString = rex;
6844 literalStringStripped = RHSStripped;
6845 }
6846
6847 if (literalString) {
6848 std::string resultComparison;
6849 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006850 case BO_LT: resultComparison = ") < 0"; break;
6851 case BO_GT: resultComparison = ") > 0"; break;
6852 case BO_LE: resultComparison = ") <= 0"; break;
6853 case BO_GE: resultComparison = ") >= 0"; break;
6854 case BO_EQ: resultComparison = ") == 0"; break;
6855 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006856 default: assert(false && "Invalid comparison operator");
6857 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006858
Ted Kremenek3427fac2011-02-23 01:52:04 +00006859 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006860 PDiag(diag::warn_stringcompare)
6861 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006862 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006863 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006864 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006865
Douglas Gregorec170db2010-06-08 19:50:34 +00006866 // C99 6.5.8p3 / C99 6.5.9p4
6867 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6868 UsualArithmeticConversions(lex, rex);
6869 else {
6870 UsualUnaryConversions(lex);
6871 UsualUnaryConversions(rex);
6872 }
6873
6874 lType = lex->getType();
6875 rType = rex->getType();
6876
Douglas Gregorca63811b2008-11-19 03:25:36 +00006877 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006878 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006879
Chris Lattnerb620c342007-08-26 01:18:55 +00006880 if (isRelational) {
6881 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006882 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006883 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006884 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006885 if (lType->hasFloatingRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006886 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006887
Chris Lattnerb620c342007-08-26 01:18:55 +00006888 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006889 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006890 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006891
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006892 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006893 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006894 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006895 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006896
Douglas Gregorf267edd2010-06-15 21:38:40 +00006897 // All of the following pointer-related warnings are GCC extensions, except
6898 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006899 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006900 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006901 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006902 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006903 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006904
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006905 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006906 if (LCanPointeeTy == RCanPointeeTy)
6907 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006908 if (!isRelational &&
6909 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6910 // Valid unless comparison between non-null pointer and function pointer
6911 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006912 // In a SFINAE context, we treat this as a hard error to maintain
6913 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006914 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6915 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006916 Diag(Loc,
6917 isSFINAEContext()?
6918 diag::err_typecheck_comparison_of_fptr_to_void
6919 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006920 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006921
6922 if (isSFINAEContext())
6923 return QualType();
6924
John McCalle3027922010-08-25 11:45:40 +00006925 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006926 return ResultTy;
6927 }
6928 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006929
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006930 // C++ [expr.rel]p2:
6931 // [...] Pointer conversions (4.10) and qualification
6932 // conversions (4.4) are performed on pointer operands (or on
6933 // a pointer operand and a null pointer constant) to bring
6934 // them to their composite pointer type. [...]
6935 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006936 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006937 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006938 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006939 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006940 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006941 if (T.isNull()) {
6942 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6943 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6944 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006945 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006946 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006947 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006948 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006949 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006950 }
6951
John McCalle3027922010-08-25 11:45:40 +00006952 ImpCastExprToType(lex, T, CK_BitCast);
6953 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006954 return ResultTy;
6955 }
Eli Friedman16c209612009-08-23 00:27:47 +00006956 // C99 6.5.9p2 and C99 6.5.8p2
6957 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6958 RCanPointeeTy.getUnqualifiedType())) {
6959 // Valid unless a relational comparison of function pointers
6960 if (isRelational && LCanPointeeTy->isFunctionType()) {
6961 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6962 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6963 }
6964 } else if (!isRelational &&
6965 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6966 // Valid unless comparison between non-null pointer and function pointer
6967 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6968 && !LHSIsNull && !RHSIsNull) {
6969 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6970 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6971 }
6972 } else {
6973 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006974 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006975 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006976 }
Eli Friedman16c209612009-08-23 00:27:47 +00006977 if (LCanPointeeTy != RCanPointeeTy)
John McCalle3027922010-08-25 11:45:40 +00006978 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006979 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006980 }
Mike Stump11289f42009-09-09 15:08:12 +00006981
Sebastian Redl576fd422009-05-10 18:38:11 +00006982 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006983 // Comparison of nullptr_t with itself.
6984 if (lType->isNullPtrType() && rType->isNullPtrType())
6985 return ResultTy;
6986
Mike Stump11289f42009-09-09 15:08:12 +00006987 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006988 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006989 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006990 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006991 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006992 ImpCastExprToType(rex, lType,
6993 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006994 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006995 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006996 return ResultTy;
6997 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006998 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006999 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007000 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00007001 ImpCastExprToType(lex, rType,
7002 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007003 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007004 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007005 return ResultTy;
7006 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007007
7008 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00007009 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007010 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7011 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00007012 // In addition, pointers to members can be compared, or a pointer to
7013 // member and a null pointer constant. Pointer to member conversions
7014 // (4.11) and qualification conversions (4.4) are performed to bring
7015 // them to a common type. If one operand is a null pointer constant,
7016 // the common type is the type of the other operand. Otherwise, the
7017 // common type is a pointer to member type similar (4.4) to the type
7018 // of one of the operands, with a cv-qualification signature (4.4)
7019 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007020 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007021 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007022 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007023 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007024 if (T.isNull()) {
7025 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007026 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007027 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007028 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007029 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007030 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007031 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007032 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007033 }
Mike Stump11289f42009-09-09 15:08:12 +00007034
John McCalle3027922010-08-25 11:45:40 +00007035 ImpCastExprToType(lex, T, CK_BitCast);
7036 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007037 return ResultTy;
7038 }
Sebastian Redl576fd422009-05-10 18:38:11 +00007039 }
Mike Stump11289f42009-09-09 15:08:12 +00007040
Steve Naroff081c7422008-09-04 15:10:53 +00007041 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00007042 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007043 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7044 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007045
Steve Naroff081c7422008-09-04 15:10:53 +00007046 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007047 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007048 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007049 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007050 }
John McCalle3027922010-08-25 11:45:40 +00007051 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007052 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007053 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00007054 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00007055 if (!isRelational
7056 && ((lType->isBlockPointerType() && rType->isPointerType())
7057 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007058 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007059 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007060 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007061 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007062 ->getPointeeType()->isVoidType())))
7063 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7064 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007065 }
John McCalle3027922010-08-25 11:45:40 +00007066 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007067 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007068 }
Steve Naroff081c7422008-09-04 15:10:53 +00007069
Steve Naroff7cae42b2009-07-10 23:34:53 +00007070 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007071 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007072 const PointerType *LPT = lType->getAs<PointerType>();
7073 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007074 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00007075 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007076 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00007077 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007078
Steve Naroff753567f2008-11-17 19:49:16 +00007079 if (!LPtrToVoid && !RPtrToVoid &&
7080 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007081 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007082 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007083 }
John McCalle3027922010-08-25 11:45:40 +00007084 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007085 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007086 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007087 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007088 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007089 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
7090 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007091 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007092 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007093 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007094 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007095 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7096 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007097 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007098 bool isError = false;
7099 if ((LHSIsNull && lType->isIntegerType()) ||
7100 (RHSIsNull && rType->isIntegerType())) {
7101 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007102 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007103 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007104 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007105 else if (getLangOptions().CPlusPlus) {
7106 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7107 isError = true;
7108 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007109 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007110
Chris Lattnerd99bd522009-08-23 00:03:44 +00007111 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007112 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00007113 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007114 if (isError)
7115 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007116 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007117
7118 if (lType->isIntegerType())
John McCalle84af4e2010-11-13 01:35:44 +00007119 ImpCastExprToType(lex, rType,
7120 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007121 else
John McCalle84af4e2010-11-13 01:35:44 +00007122 ImpCastExprToType(rex, lType,
7123 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007124 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007125 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007126
Steve Naroff4b191572008-09-04 16:56:14 +00007127 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00007128 if (!isRelational && RHSIsNull
7129 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00007130 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007131 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007132 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00007133 if (!isRelational && LHSIsNull
7134 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00007135 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007136 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007137 }
Chris Lattner326f7572008-11-18 01:30:42 +00007138 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007139}
7140
Nate Begeman191a6b12008-07-14 18:02:46 +00007141/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007142/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007143/// like a scalar comparison, a vector comparison produces a vector of integer
7144/// types.
7145QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00007146 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00007147 bool isRelational) {
7148 // Check to make sure we're operating on vectors of the same type and width,
7149 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00007150 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007151 if (vType.isNull())
7152 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007153
Anton Yartsev3f8f2882010-11-18 03:19:30 +00007154 // If AltiVec, the comparison results in a numeric type, i.e.
7155 // bool for C++, int for C
7156 if (getLangOptions().AltiVec)
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007157 return Context.getLogicalOperationType();
Anton Yartsev3f8f2882010-11-18 03:19:30 +00007158
Nate Begeman191a6b12008-07-14 18:02:46 +00007159 QualType lType = lex->getType();
7160 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007161
Nate Begeman191a6b12008-07-14 18:02:46 +00007162 // For non-floating point types, check for self-comparisons of the form
7163 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7164 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007165 if (!lType->hasFloatingRepresentation()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007166 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
7167 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
7168 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007169 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007170 PDiag(diag::warn_comparison_always)
7171 << 0 // self-
7172 << 2 // "a constant"
7173 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007174 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007175
Nate Begeman191a6b12008-07-14 18:02:46 +00007176 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007177 if (!isRelational && lType->hasFloatingRepresentation()) {
7178 assert (rType->hasFloatingRepresentation());
Chris Lattner326f7572008-11-18 01:30:42 +00007179 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007180 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007181
Nate Begeman191a6b12008-07-14 18:02:46 +00007182 // Return the type for the comparison, which is the same as vector type for
7183 // integer vectors, or an integer type of identical size and number of
7184 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007185 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00007186 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007187
John McCall9dd450b2009-09-21 23:43:11 +00007188 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00007189 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007190 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00007191 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00007192 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007193 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7194
Mike Stump4e1f26a2009-02-19 03:04:26 +00007195 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007196 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00007197 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7198}
7199
Steve Naroff218bc2b2007-05-04 21:54:46 +00007200inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00007201 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007202 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
7203 if (lex->getType()->hasIntegerRepresentation() &&
7204 rex->getType()->hasIntegerRepresentation())
7205 return CheckVectorOperands(Loc, lex, rex);
7206
7207 return InvalidOperands(Loc, lex, rex);
7208 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007209
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007210 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007211
Douglas Gregor0bf31402010-10-08 23:50:27 +00007212 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
7213 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007214 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00007215 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007216}
7217
Steve Naroff218bc2b2007-05-04 21:54:46 +00007218inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner8406c512010-07-13 19:41:32 +00007219 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
7220
7221 // Diagnose cases where the user write a logical and/or but probably meant a
7222 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7223 // is a constant.
7224 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman6b197e02010-07-27 19:14:53 +00007225 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00007226 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00007227 !Loc.isMacroID()) {
7228 // If the RHS can be constant folded, and if it constant folds to something
7229 // that isn't 0 or 1 (which indicate a potential logical operation that
7230 // happened to fold to true/false) then warn.
7231 Expr::EvalResult Result;
7232 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
7233 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7234 Diag(Loc, diag::warn_logical_instead_of_bitwise)
7235 << rex->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00007236 << (Opc == BO_LAnd ? "&&" : "||")
7237 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00007238 }
7239 }
Chris Lattner8406c512010-07-13 19:41:32 +00007240
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007241 if (!Context.getLangOptions().CPlusPlus) {
7242 UsualUnaryConversions(lex);
7243 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007244
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007245 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
7246 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007247
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007248 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007249 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007250
John McCall4a2429a2010-06-04 00:29:51 +00007251 // The following is safe because we only use this method for
7252 // non-overloadable operands.
7253
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007254 // C++ [expr.log.and]p1
7255 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007256 // The operands are both contextually converted to type bool.
7257 if (PerformContextuallyConvertToBool(lex) ||
7258 PerformContextuallyConvertToBool(rex))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007259 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007260
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007261 // C++ [expr.log.and]p2
7262 // C++ [expr.log.or]p2
7263 // The result is a bool.
7264 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007265}
7266
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007267/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7268/// is a read-only property; return true if so. A readonly property expression
7269/// depends on various declarations and thus must be treated specially.
7270///
Mike Stump11289f42009-09-09 15:08:12 +00007271static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007272 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7273 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00007274 if (PropExpr->isImplicitProperty()) return false;
7275
7276 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7277 QualType BaseType = PropExpr->isSuperReceiver() ?
7278 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007279 PropExpr->getBase()->getType();
7280
John McCallb7bd14f2010-12-02 01:19:52 +00007281 if (const ObjCObjectPointerType *OPT =
7282 BaseType->getAsObjCInterfacePointerType())
7283 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7284 if (S.isPropertyReadonly(PDecl, IFace))
7285 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007286 }
7287 return false;
7288}
7289
Chris Lattner30bd3272008-11-18 01:22:49 +00007290/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7291/// emit an error and return true. If so, return false.
7292static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007293 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007294 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007295 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007296 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7297 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00007298 if (IsLV == Expr::MLV_Valid)
7299 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007300
Chris Lattner30bd3272008-11-18 01:22:49 +00007301 unsigned Diag = 0;
7302 bool NeedType = false;
7303 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00007304 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007305 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007306 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7307 NeedType = true;
7308 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007309 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007310 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7311 NeedType = true;
7312 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007313 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007314 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7315 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007316 case Expr::MLV_Valid:
7317 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007318 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007319 case Expr::MLV_MemberFunction:
7320 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007321 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7322 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007323 case Expr::MLV_IncompleteType:
7324 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007325 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007326 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007327 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007328 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007329 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7330 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007331 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007332 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7333 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007334 case Expr::MLV_ReadonlyProperty:
7335 Diag = diag::error_readonly_property_assignment;
7336 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007337 case Expr::MLV_NoSetterProperty:
7338 Diag = diag::error_nosetter_property_assignment;
7339 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007340 case Expr::MLV_SubObjCPropertySetting:
7341 Diag = diag::error_no_subobject_property_setting;
7342 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007343 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007344
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007345 SourceRange Assign;
7346 if (Loc != OrigLoc)
7347 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007348 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007349 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007350 else
Mike Stump11289f42009-09-09 15:08:12 +00007351 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007352 return true;
7353}
7354
7355
7356
7357// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00007358QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
7359 SourceLocation Loc,
7360 QualType CompoundType) {
7361 // Verify that LHS is a modifiable lvalue, and emit error if not.
7362 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007363 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007364
7365 QualType LHSType = LHS->getType();
7366 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007367 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007368 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007369 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007370 // Simple assignment "x = y".
John McCall34376a62010-12-04 03:47:34 +00007371 if (LHS->getObjectKind() == OK_ObjCProperty)
7372 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007373 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007374 // Special case of NSObject attributes on c-style pointer types.
7375 if (ConvTy == IncompatiblePointer &&
7376 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007377 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007378 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007379 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007380 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007381
John McCall7decc9e2010-11-18 06:31:45 +00007382 if (ConvTy == Compatible &&
7383 getLangOptions().ObjCNonFragileABI &&
7384 LHSType->isObjCObjectType())
7385 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7386 << LHSType;
7387
Chris Lattnerea714382008-08-21 18:04:13 +00007388 // If the RHS is a unary plus or minus, check to see if they = and + are
7389 // right next to each other. If so, the user may have typo'd "x =+ 4"
7390 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00007391 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00007392 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7393 RHSCheck = ICE->getSubExpr();
7394 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007395 if ((UO->getOpcode() == UO_Plus ||
7396 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007397 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007398 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00007399 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7400 // And there is a space or other character before the subexpr of the
7401 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00007402 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7403 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007404 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007405 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007406 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007407 }
Chris Lattnerea714382008-08-21 18:04:13 +00007408 }
7409 } else {
7410 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007411 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007412 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007413
Chris Lattner326f7572008-11-18 01:30:42 +00007414 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007415 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007416 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007417
Chris Lattner39561062010-07-07 06:14:23 +00007418
7419 // Check to see if the destination operand is a dereferenced null pointer. If
7420 // so, and if not volatile-qualified, this is undefined behavior that the
7421 // optimizer will delete, so warn about it. People sometimes try to use this
7422 // to get a deterministic trap and are surprised by clang's behavior. This
7423 // only handles the pattern "*null = whatever", which is a very syntactic
7424 // check.
7425 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCalle3027922010-08-25 11:45:40 +00007426 if (UO->getOpcode() == UO_Deref &&
Chris Lattner39561062010-07-07 06:14:23 +00007427 UO->getSubExpr()->IgnoreParenCasts()->
7428 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7429 !UO->getType().isVolatileQualified()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007430 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7431 PDiag(diag::warn_indirection_through_null)
7432 << UO->getSubExpr()->getSourceRange());
7433 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7434 PDiag(diag::note_indirection_through_null));
Chris Lattner39561062010-07-07 06:14:23 +00007435 }
7436
Ted Kremenek64699be2011-02-16 01:57:07 +00007437 // Check for trivial buffer overflows.
7438 if (const ArraySubscriptExpr *ae
7439 = dyn_cast<ArraySubscriptExpr>(LHS->IgnoreParenCasts()))
7440 CheckArrayAccess(ae);
7441
Steve Naroff98cf3e92007-06-06 18:38:38 +00007442 // C99 6.5.16p3: The type of an assignment expression is the type of the
7443 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007444 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007445 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7446 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007447 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007448 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007449 return (getLangOptions().CPlusPlus
7450 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007451}
7452
Chris Lattner326f7572008-11-18 01:30:42 +00007453// C99 6.5.17
John McCall34376a62010-12-04 03:47:34 +00007454static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007455 SourceLocation Loc) {
7456 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007457
John McCall4bc41ae2010-11-18 19:01:18 +00007458 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007459 if (LHSResult.isInvalid())
7460 return QualType();
7461
John McCall4bc41ae2010-11-18 19:01:18 +00007462 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007463 if (RHSResult.isInvalid())
7464 return QualType();
7465 RHS = RHSResult.take();
7466
John McCall73d36182010-10-12 07:14:40 +00007467 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7468 // operands, but not unary promotions.
7469 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007470
John McCall34376a62010-12-04 03:47:34 +00007471 // So we treat the LHS as a ignored value, and in C++ we allow the
7472 // containing site to determine what should be done with the RHS.
7473 S.IgnoredValueConversions(LHS);
7474
7475 if (!S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007476 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCall73d36182010-10-12 07:14:40 +00007477 if (!RHS->getType()->isVoidType())
John McCall4bc41ae2010-11-18 19:01:18 +00007478 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007479 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007480
Chris Lattner326f7572008-11-18 01:30:42 +00007481 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007482}
7483
Steve Naroff7a5af782007-07-13 16:58:59 +00007484/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7485/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007486static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7487 ExprValueKind &VK,
7488 SourceLocation OpLoc,
7489 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007490 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007491 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007492
Chris Lattner6b0cf142008-11-21 07:05:48 +00007493 QualType ResType = Op->getType();
7494 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007495
John McCall4bc41ae2010-11-18 19:01:18 +00007496 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007497 // Decrement of bool is not allowed.
7498 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007499 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007500 return QualType();
7501 }
7502 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007503 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007504 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007505 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007506 } else if (ResType->isAnyPointerType()) {
7507 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007508
Chris Lattner6b0cf142008-11-21 07:05:48 +00007509 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00007510 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007511 if (S.getLangOptions().CPlusPlus) {
7512 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007513 << Op->getSourceRange();
7514 return QualType();
7515 }
7516
7517 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00007518 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007519 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007520 if (S.getLangOptions().CPlusPlus) {
7521 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007522 << Op->getType() << Op->getSourceRange();
7523 return QualType();
7524 }
7525
John McCall4bc41ae2010-11-18 19:01:18 +00007526 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007527 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007528 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7529 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00007530 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00007531 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00007532 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007533 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00007534 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7535 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007536 << PointeeTy << Op->getSourceRange();
7537 return QualType();
7538 }
Eli Friedman090addd2010-01-03 00:20:48 +00007539 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007540 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007541 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007542 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007543 } else if (ResType->isPlaceholderType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007544 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007545 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007546 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7547 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007548 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7549 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007550 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007551 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007552 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007553 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007554 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007555 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007556 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007557 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007558 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007559 // In C++, a prefix increment is the same type as the operand. Otherwise
7560 // (in C or with postfix), the increment is the unqualified type of the
7561 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007562 if (isPrefix && S.getLangOptions().CPlusPlus) {
7563 VK = VK_LValue;
7564 return ResType;
7565 } else {
7566 VK = VK_RValue;
7567 return ResType.getUnqualifiedType();
7568 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007569}
7570
John McCall34376a62010-12-04 03:47:34 +00007571void Sema::ConvertPropertyForRValue(Expr *&E) {
7572 assert(E->getValueKind() == VK_LValue &&
7573 E->getObjectKind() == OK_ObjCProperty);
7574 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7575
7576 ExprValueKind VK = VK_RValue;
7577 if (PRE->isImplicitProperty()) {
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007578 if (const ObjCMethodDecl *GetterMethod =
7579 PRE->getImplicitPropertyGetter()) {
7580 QualType Result = GetterMethod->getResultType();
7581 VK = Expr::getValueKindForType(Result);
7582 }
7583 else {
7584 Diag(PRE->getLocation(), diag::err_getter_not_found)
7585 << PRE->getBase()->getType();
7586 }
John McCall34376a62010-12-04 03:47:34 +00007587 }
7588
7589 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7590 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007591
7592 ExprResult Result = MaybeBindToTemporary(E);
7593 if (!Result.isInvalid())
7594 E = Result.take();
John McCall34376a62010-12-04 03:47:34 +00007595}
7596
7597void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7598 assert(LHS->getValueKind() == VK_LValue &&
7599 LHS->getObjectKind() == OK_ObjCProperty);
7600 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7601
7602 if (PRE->isImplicitProperty()) {
7603 // If using property-dot syntax notation for assignment, and there is a
7604 // setter, RHS expression is being passed to the setter argument. So,
7605 // type conversion (and comparison) is RHS to setter's argument type.
7606 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7607 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7608 LHSTy = (*P)->getType();
7609
7610 // Otherwise, if the getter returns an l-value, just call that.
7611 } else {
7612 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7613 ExprValueKind VK = Expr::getValueKindForType(Result);
7614 if (VK == VK_LValue) {
7615 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7616 CK_GetObjCProperty, LHS, 0, VK);
7617 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007618 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007619 }
John McCall34376a62010-12-04 03:47:34 +00007620 }
7621
7622 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007623 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007624 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007625 Expr *Arg = RHS;
7626 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7627 Owned(Arg));
7628 if (!ArgE.isInvalid())
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007629 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007630 }
7631}
7632
7633
Anders Carlsson806700f2008-02-01 07:15:58 +00007634/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007635/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007636/// where the declaration is needed for type checking. We only need to
7637/// handle cases when the expression references a function designator
7638/// or is an lvalue. Here are some examples:
7639/// - &(x) => x
7640/// - &*****f => f for f a function designator.
7641/// - &s.xx => s
7642/// - &s.zz[1].yy -> s, if zz is an array
7643/// - *(x + 1) -> x, if x is an array
7644/// - &"123"[2] -> 0
7645/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007646static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007647 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007648 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007649 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007650 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007651 // If this is an arrow operator, the address is an offset from
7652 // the base's value, so the object the base refers to is
7653 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007654 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007655 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007656 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007657 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007658 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007659 // FIXME: This code shouldn't be necessary! We should catch the implicit
7660 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007661 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7662 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7663 if (ICE->getSubExpr()->getType()->isArrayType())
7664 return getPrimaryDecl(ICE->getSubExpr());
7665 }
7666 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007667 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007668 case Stmt::UnaryOperatorClass: {
7669 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007670
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007671 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007672 case UO_Real:
7673 case UO_Imag:
7674 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007675 return getPrimaryDecl(UO->getSubExpr());
7676 default:
7677 return 0;
7678 }
7679 }
Steve Naroff47500512007-04-19 23:00:49 +00007680 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007681 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007682 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007683 // If the result of an implicit cast is an l-value, we care about
7684 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007685 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007686 default:
7687 return 0;
7688 }
7689}
7690
7691/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007692/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007693/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007694/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007695/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007696/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007697/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007698static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7699 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007700 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007701 return S.Context.DependentTy;
7702 if (OrigOp->getType() == S.Context.OverloadTy)
7703 return S.Context.OverloadTy;
John McCall8d08b9b2010-08-27 09:08:28 +00007704
John McCall4bc41ae2010-11-18 19:01:18 +00007705 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007706 if (PR.isInvalid()) return QualType();
7707 OrigOp = PR.take();
7708
John McCall8d08b9b2010-08-27 09:08:28 +00007709 // Make sure to ignore parentheses in subsequent checks
7710 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007711
John McCall4bc41ae2010-11-18 19:01:18 +00007712 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007713 // Implement C99-only parts of addressof rules.
7714 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007715 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007716 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7717 // (assuming the deref expression is valid).
7718 return uOp->getSubExpr()->getType();
7719 }
7720 // Technically, there should be a check for array subscript
7721 // expressions here, but the result of one is always an lvalue anyway.
7722 }
John McCallf3a88602011-02-03 08:15:49 +00007723 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007724 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007725
Chris Lattner9156f1b2010-07-05 19:17:26 +00007726 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007727 bool sfinae = S.isSFINAEContext();
7728 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7729 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007730 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007731 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007732 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007733 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007734 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007735 } else if (lval == Expr::LV_MemberFunction) {
7736 // If it's an instance method, make a member pointer.
7737 // The expression must have exactly the form &A::foo.
7738
7739 // If the underlying expression isn't a decl ref, give up.
7740 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007741 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007742 << OrigOp->getSourceRange();
7743 return QualType();
7744 }
7745 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7746 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7747
7748 // The id-expression was parenthesized.
7749 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007750 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007751 << OrigOp->getSourceRange();
7752
7753 // The method was named without a qualifier.
7754 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007755 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007756 << op->getSourceRange();
7757 }
7758
John McCall4bc41ae2010-11-18 19:01:18 +00007759 return S.Context.getMemberPointerType(op->getType(),
7760 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007761 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007762 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007763 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007764 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007765 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007766 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007767 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007768 return QualType();
7769 }
John McCall086a4642010-11-24 05:12:34 +00007770 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007771 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007772 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007773 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007774 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007775 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007776 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007777 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007778 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007779 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007780 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007781 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007782 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007783 << "property expression" << op->getSourceRange();
7784 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007785 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007786 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007787 // with the register storage-class specifier.
7788 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007789 // in C++ it is not error to take address of a register
7790 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007791 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007792 !S.getLangOptions().CPlusPlus) {
7793 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007794 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007795 return QualType();
7796 }
John McCalld14a8642009-11-21 08:51:07 +00007797 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007798 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007799 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007800 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007801 // Could be a pointer to member, though, if there is an explicit
7802 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007803 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007804 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007805 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007806 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007807 S.Diag(OpLoc,
7808 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007809 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007810 return QualType();
7811 }
Mike Stump11289f42009-09-09 15:08:12 +00007812
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007813 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7814 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007815 return S.Context.getMemberPointerType(op->getType(),
7816 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007817 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007818 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007819 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007820 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007821 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007822
Eli Friedmance7f9002009-05-16 23:27:50 +00007823 if (lval == Expr::LV_IncompleteVoidType) {
7824 // Taking the address of a void variable is technically illegal, but we
7825 // allow it in cases which are otherwise valid.
7826 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007827 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007828 }
7829
Steve Naroff47500512007-04-19 23:00:49 +00007830 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007831 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007832 return S.Context.getObjCObjectPointerType(op->getType());
7833 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007834}
7835
Chris Lattner9156f1b2010-07-05 19:17:26 +00007836/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007837static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7838 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007839 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007840 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007841
John McCall4bc41ae2010-11-18 19:01:18 +00007842 S.UsualUnaryConversions(Op);
Chris Lattner9156f1b2010-07-05 19:17:26 +00007843 QualType OpTy = Op->getType();
7844 QualType Result;
7845
7846 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7847 // is an incomplete type or void. It would be possible to warn about
7848 // dereferencing a void pointer, but it's completely well-defined, and such a
7849 // warning is unlikely to catch any mistakes.
7850 if (const PointerType *PT = OpTy->getAs<PointerType>())
7851 Result = PT->getPointeeType();
7852 else if (const ObjCObjectPointerType *OPT =
7853 OpTy->getAs<ObjCObjectPointerType>())
7854 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007855 else {
John McCall4bc41ae2010-11-18 19:01:18 +00007856 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007857 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007858 if (PR.take() != Op)
7859 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007860 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007861
Chris Lattner9156f1b2010-07-05 19:17:26 +00007862 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007863 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007864 << OpTy << Op->getSourceRange();
7865 return QualType();
7866 }
John McCall4bc41ae2010-11-18 19:01:18 +00007867
7868 // Dereferences are usually l-values...
7869 VK = VK_LValue;
7870
7871 // ...except that certain expressions are never l-values in C.
7872 if (!S.getLangOptions().CPlusPlus &&
7873 IsCForbiddenLValueType(S.Context, Result))
7874 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007875
7876 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007877}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007878
John McCalle3027922010-08-25 11:45:40 +00007879static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007880 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007881 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007882 switch (Kind) {
7883 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007884 case tok::periodstar: Opc = BO_PtrMemD; break;
7885 case tok::arrowstar: Opc = BO_PtrMemI; break;
7886 case tok::star: Opc = BO_Mul; break;
7887 case tok::slash: Opc = BO_Div; break;
7888 case tok::percent: Opc = BO_Rem; break;
7889 case tok::plus: Opc = BO_Add; break;
7890 case tok::minus: Opc = BO_Sub; break;
7891 case tok::lessless: Opc = BO_Shl; break;
7892 case tok::greatergreater: Opc = BO_Shr; break;
7893 case tok::lessequal: Opc = BO_LE; break;
7894 case tok::less: Opc = BO_LT; break;
7895 case tok::greaterequal: Opc = BO_GE; break;
7896 case tok::greater: Opc = BO_GT; break;
7897 case tok::exclaimequal: Opc = BO_NE; break;
7898 case tok::equalequal: Opc = BO_EQ; break;
7899 case tok::amp: Opc = BO_And; break;
7900 case tok::caret: Opc = BO_Xor; break;
7901 case tok::pipe: Opc = BO_Or; break;
7902 case tok::ampamp: Opc = BO_LAnd; break;
7903 case tok::pipepipe: Opc = BO_LOr; break;
7904 case tok::equal: Opc = BO_Assign; break;
7905 case tok::starequal: Opc = BO_MulAssign; break;
7906 case tok::slashequal: Opc = BO_DivAssign; break;
7907 case tok::percentequal: Opc = BO_RemAssign; break;
7908 case tok::plusequal: Opc = BO_AddAssign; break;
7909 case tok::minusequal: Opc = BO_SubAssign; break;
7910 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7911 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7912 case tok::ampequal: Opc = BO_AndAssign; break;
7913 case tok::caretequal: Opc = BO_XorAssign; break;
7914 case tok::pipeequal: Opc = BO_OrAssign; break;
7915 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007916 }
7917 return Opc;
7918}
7919
John McCalle3027922010-08-25 11:45:40 +00007920static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007921 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007922 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007923 switch (Kind) {
7924 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007925 case tok::plusplus: Opc = UO_PreInc; break;
7926 case tok::minusminus: Opc = UO_PreDec; break;
7927 case tok::amp: Opc = UO_AddrOf; break;
7928 case tok::star: Opc = UO_Deref; break;
7929 case tok::plus: Opc = UO_Plus; break;
7930 case tok::minus: Opc = UO_Minus; break;
7931 case tok::tilde: Opc = UO_Not; break;
7932 case tok::exclaim: Opc = UO_LNot; break;
7933 case tok::kw___real: Opc = UO_Real; break;
7934 case tok::kw___imag: Opc = UO_Imag; break;
7935 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007936 }
7937 return Opc;
7938}
7939
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007940/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7941/// This warning is only emitted for builtin assignment operations. It is also
7942/// suppressed in the event of macro expansions.
7943static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7944 SourceLocation OpLoc) {
7945 if (!S.ActiveTemplateInstantiations.empty())
7946 return;
7947 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7948 return;
7949 lhs = lhs->IgnoreParenImpCasts();
7950 rhs = rhs->IgnoreParenImpCasts();
7951 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7952 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7953 if (!LeftDeclRef || !RightDeclRef ||
7954 LeftDeclRef->getLocation().isMacroID() ||
7955 RightDeclRef->getLocation().isMacroID())
7956 return;
7957 const ValueDecl *LeftDecl =
7958 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7959 const ValueDecl *RightDecl =
7960 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7961 if (LeftDecl != RightDecl)
7962 return;
7963 if (LeftDecl->getType().isVolatileQualified())
7964 return;
7965 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7966 if (RefTy->getPointeeType().isVolatileQualified())
7967 return;
7968
7969 S.Diag(OpLoc, diag::warn_self_assignment)
7970 << LeftDeclRef->getType()
7971 << lhs->getSourceRange() << rhs->getSourceRange();
7972}
7973
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007974/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7975/// operator @p Opc at location @c TokLoc. This routine only supports
7976/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007977ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007978 BinaryOperatorKind Opc,
John McCalle3027922010-08-25 11:45:40 +00007979 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007980 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007981 // The following two variables are used for compound assignment operators
7982 QualType CompLHSTy; // Type of LHS after promotions for computation
7983 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007984 ExprValueKind VK = VK_RValue;
7985 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007986
7987 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007988 case BO_Assign:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007989 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007990 if (getLangOptions().CPlusPlus &&
7991 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall4bc41ae2010-11-18 19:01:18 +00007992 VK = lhs->getValueKind();
7993 OK = lhs->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007994 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007995 if (!ResultTy.isNull())
7996 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007997 break;
John McCalle3027922010-08-25 11:45:40 +00007998 case BO_PtrMemD:
7999 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00008000 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008001 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008002 break;
John McCalle3027922010-08-25 11:45:40 +00008003 case BO_Mul:
8004 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008005 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008006 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008007 break;
John McCalle3027922010-08-25 11:45:40 +00008008 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008009 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8010 break;
John McCalle3027922010-08-25 11:45:40 +00008011 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008012 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8013 break;
John McCalle3027922010-08-25 11:45:40 +00008014 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008015 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8016 break;
John McCalle3027922010-08-25 11:45:40 +00008017 case BO_Shl:
8018 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008019 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008020 break;
John McCalle3027922010-08-25 11:45:40 +00008021 case BO_LE:
8022 case BO_LT:
8023 case BO_GE:
8024 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008025 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008026 break;
John McCalle3027922010-08-25 11:45:40 +00008027 case BO_EQ:
8028 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008029 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008030 break;
John McCalle3027922010-08-25 11:45:40 +00008031 case BO_And:
8032 case BO_Xor:
8033 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008034 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8035 break;
John McCalle3027922010-08-25 11:45:40 +00008036 case BO_LAnd:
8037 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00008038 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008039 break;
John McCalle3027922010-08-25 11:45:40 +00008040 case BO_MulAssign:
8041 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008042 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008043 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008044 CompLHSTy = CompResultTy;
8045 if (!CompResultTy.isNull())
8046 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008047 break;
John McCalle3027922010-08-25 11:45:40 +00008048 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008049 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8050 CompLHSTy = CompResultTy;
8051 if (!CompResultTy.isNull())
8052 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008053 break;
John McCalle3027922010-08-25 11:45:40 +00008054 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008055 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8056 if (!CompResultTy.isNull())
8057 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008058 break;
John McCalle3027922010-08-25 11:45:40 +00008059 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008060 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8061 if (!CompResultTy.isNull())
8062 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008063 break;
John McCalle3027922010-08-25 11:45:40 +00008064 case BO_ShlAssign:
8065 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008066 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008067 CompLHSTy = CompResultTy;
8068 if (!CompResultTy.isNull())
8069 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008070 break;
John McCalle3027922010-08-25 11:45:40 +00008071 case BO_AndAssign:
8072 case BO_XorAssign:
8073 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008074 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8075 CompLHSTy = CompResultTy;
8076 if (!CompResultTy.isNull())
8077 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008078 break;
John McCalle3027922010-08-25 11:45:40 +00008079 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00008080 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCall7decc9e2010-11-18 06:31:45 +00008081 if (getLangOptions().CPlusPlus) {
8082 VK = rhs->getValueKind();
8083 OK = rhs->getObjectKind();
8084 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008085 break;
8086 }
8087 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008088 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008089 if (CompResultTy.isNull())
John McCall7decc9e2010-11-18 06:31:45 +00008090 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
8091 VK, OK, OpLoc));
8092
John McCall34376a62010-12-04 03:47:34 +00008093 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008094 VK = VK_LValue;
8095 OK = lhs->getObjectKind();
8096 }
8097 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
8098 VK, OK, CompLHSTy,
8099 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008100}
8101
Sebastian Redl44615072009-10-27 12:10:02 +00008102/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8103/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008104static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8105 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008106 const PartialDiagnostic &FirstNote,
8107 SourceRange FirstParenRange,
8108 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00008109 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008110 Self.Diag(Loc, PD);
8111
8112 if (!FirstNote.getDiagID())
8113 return;
8114
8115 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8116 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8117 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008118 return;
8119 }
8120
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008121 Self.Diag(Loc, FirstNote)
8122 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00008123 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008124
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008125 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008126 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008127
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008128 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8129 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8130 // We can't display the parentheses, so just dig the
8131 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008132 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008133 return;
8134 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008135
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008136 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00008137 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8138 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008139}
8140
Sebastian Redl44615072009-10-27 12:10:02 +00008141/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8142/// operators are mixed in a way that suggests that the programmer forgot that
8143/// comparison operators have higher precedence. The most typical example of
8144/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008145static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008146 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00008147 typedef BinaryOperator BinOp;
8148 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8149 rhsopc = static_cast<BinOp::Opcode>(-1);
8150 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008151 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00008152 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008153 rhsopc = BO->getOpcode();
8154
8155 // Subs are not binary operators.
8156 if (lhsopc == -1 && rhsopc == -1)
8157 return;
8158
8159 // Bitwise operations are sometimes used as eager logical ops.
8160 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00008161 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8162 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008163 return;
8164
Sebastian Redl44615072009-10-27 12:10:02 +00008165 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008166 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008167 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008168 << SourceRange(lhs->getLocStart(), OpLoc)
8169 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008170 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008171 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008172 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
8173 Self.PDiag(diag::note_precedence_bitwise_silence)
8174 << BinOp::getOpcodeStr(lhsopc),
8175 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00008176 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008177 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008178 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008179 << SourceRange(OpLoc, rhs->getLocEnd())
8180 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008181 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008182 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008183 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
8184 Self.PDiag(diag::note_precedence_bitwise_silence)
8185 << BinOp::getOpcodeStr(rhsopc),
8186 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00008187}
8188
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008189/// \brief It accepts a '&&' expr that is inside a '||' one.
8190/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8191/// in parentheses.
8192static void
8193EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8194 Expr *E) {
8195 assert(isa<BinaryOperator>(E) &&
8196 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
8197 SuggestParentheses(Self, OpLoc,
8198 Self.PDiag(diag::warn_logical_and_in_logical_or)
8199 << E->getSourceRange(),
8200 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8201 E->getSourceRange(),
8202 Self.PDiag(0), SourceRange());
8203}
8204
8205/// \brief Returns true if the given expression can be evaluated as a constant
8206/// 'true'.
8207static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8208 bool Res;
8209 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8210}
8211
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008212/// \brief Returns true if the given expression can be evaluated as a constant
8213/// 'false'.
8214static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8215 bool Res;
8216 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8217}
8218
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008219/// \brief Look for '&&' in the left hand of a '||' expr.
8220static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008221 Expr *OrLHS, Expr *OrRHS) {
8222 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008223 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008224 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8225 if (EvaluatesAsFalse(S, OrRHS))
8226 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008227 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8228 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8229 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8230 } else if (Bop->getOpcode() == BO_LOr) {
8231 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8232 // If it's "a || b && 1 || c" we didn't warn earlier for
8233 // "a || b && 1", but warn now.
8234 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8235 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8236 }
8237 }
8238 }
8239}
8240
8241/// \brief Look for '&&' in the right hand of a '||' expr.
8242static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008243 Expr *OrLHS, Expr *OrRHS) {
8244 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008245 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008246 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8247 if (EvaluatesAsFalse(S, OrLHS))
8248 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008249 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8250 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8251 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008252 }
8253 }
8254}
8255
Sebastian Redl43028242009-10-26 15:24:15 +00008256/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008257/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008258static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008259 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008260 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008261 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008262 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8263
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008264 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8265 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008266 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008267 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8268 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008269 }
Sebastian Redl43028242009-10-26 15:24:15 +00008270}
8271
Steve Naroff218bc2b2007-05-04 21:54:46 +00008272// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008273ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008274 tok::TokenKind Kind,
8275 Expr *lhs, Expr *rhs) {
8276 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00008277 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8278 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008279
Sebastian Redl43028242009-10-26 15:24:15 +00008280 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8281 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8282
Douglas Gregor5287f092009-11-05 00:51:44 +00008283 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8284}
8285
John McCalldadc5752010-08-24 06:29:42 +00008286ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008287 BinaryOperatorKind Opc,
8288 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00008289 if (getLangOptions().CPlusPlus) {
8290 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008291
John McCall622114c2010-12-06 05:26:58 +00008292 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8293 UseBuiltinOperator = false;
8294 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8295 UseBuiltinOperator = true;
8296 } else {
8297 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8298 !rhs->getType()->isOverloadableType();
8299 }
8300
8301 if (!UseBuiltinOperator) {
8302 // Find all of the overloaded operators visible from this
8303 // point. We perform both an operator-name lookup from the local
8304 // scope and an argument-dependent lookup based on the types of
8305 // the arguments.
8306 UnresolvedSet<16> Functions;
8307 OverloadedOperatorKind OverOp
8308 = BinaryOperator::getOverloadedOperator(Opc);
8309 if (S && OverOp != OO_None)
8310 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8311 Functions);
8312
8313 // Build the (potentially-overloaded, potentially-dependent)
8314 // binary operation.
8315 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8316 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008317 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008318
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008319 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00008320 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008321}
8322
John McCalldadc5752010-08-24 06:29:42 +00008323ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008324 UnaryOperatorKind Opc,
John McCall36226622010-10-12 02:09:17 +00008325 Expr *Input) {
John McCall7decc9e2010-11-18 06:31:45 +00008326 ExprValueKind VK = VK_RValue;
8327 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008328 QualType resultType;
8329 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008330 case UO_PreInc:
8331 case UO_PreDec:
8332 case UO_PostInc:
8333 case UO_PostDec:
John McCall4bc41ae2010-11-18 19:01:18 +00008334 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008335 Opc == UO_PreInc ||
8336 Opc == UO_PostInc,
8337 Opc == UO_PreInc ||
8338 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008339 break;
John McCalle3027922010-08-25 11:45:40 +00008340 case UO_AddrOf:
John McCall4bc41ae2010-11-18 19:01:18 +00008341 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008342 break;
John McCalle3027922010-08-25 11:45:40 +00008343 case UO_Deref:
Douglas Gregorb92a1562010-02-03 00:27:59 +00008344 DefaultFunctionArrayLvalueConversion(Input);
John McCall4bc41ae2010-11-18 19:01:18 +00008345 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008346 break;
John McCalle3027922010-08-25 11:45:40 +00008347 case UO_Plus:
8348 case UO_Minus:
Steve Naroff31090012007-07-16 21:54:35 +00008349 UsualUnaryConversions(Input);
8350 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008351 if (resultType->isDependentType())
8352 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008353 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8354 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008355 break;
8356 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8357 resultType->isEnumeralType())
8358 break;
8359 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008360 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008361 resultType->isPointerType())
8362 break;
John McCall36226622010-10-12 02:09:17 +00008363 else if (resultType->isPlaceholderType()) {
8364 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8365 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008366 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008367 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008368
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008369 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8370 << resultType << Input->getSourceRange());
John McCalle3027922010-08-25 11:45:40 +00008371 case UO_Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00008372 UsualUnaryConversions(Input);
8373 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008374 if (resultType->isDependentType())
8375 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008376 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8377 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8378 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008379 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008380 << resultType << Input->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008381 else if (resultType->hasIntegerRepresentation())
8382 break;
8383 else if (resultType->isPlaceholderType()) {
8384 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8385 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008386 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008387 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008388 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8389 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008390 }
Steve Naroff35d85152007-05-07 00:24:15 +00008391 break;
John McCalle3027922010-08-25 11:45:40 +00008392 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008393 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00008394 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00008395 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008396 if (resultType->isDependentType())
8397 break;
John McCall36226622010-10-12 02:09:17 +00008398 if (resultType->isScalarType()) { // C99 6.5.3.3p1
8399 // ok, fallthrough
8400 } else if (resultType->isPlaceholderType()) {
8401 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8402 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008403 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008404 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008405 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8406 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008407 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008408
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008409 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008410 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008411 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008412 break;
John McCalle3027922010-08-25 11:45:40 +00008413 case UO_Real:
8414 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008415 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008416 // _Real and _Imag map ordinary l-values into ordinary l-values.
8417 if (Input->getValueKind() != VK_RValue &&
8418 Input->getObjectKind() == OK_Ordinary)
8419 VK = Input->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008420 break;
John McCalle3027922010-08-25 11:45:40 +00008421 case UO_Extension:
Chris Lattner86554282007-06-08 22:32:33 +00008422 resultType = Input->getType();
John McCall7decc9e2010-11-18 06:31:45 +00008423 VK = Input->getValueKind();
8424 OK = Input->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008425 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008426 }
8427 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008428 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008429
John McCall7decc9e2010-11-18 06:31:45 +00008430 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
8431 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008432}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008433
John McCalldadc5752010-08-24 06:29:42 +00008434ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008435 UnaryOperatorKind Opc,
8436 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008437 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008438 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008439 // Find all of the overloaded operators visible from this
8440 // point. We perform both an operator-name lookup from the local
8441 // scope and an argument-dependent lookup based on the types of
8442 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008443 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008444 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008445 if (S && OverOp != OO_None)
8446 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8447 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008448
John McCallb268a282010-08-23 23:25:46 +00008449 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008450 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008451
John McCallb268a282010-08-23 23:25:46 +00008452 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008453}
8454
Douglas Gregor5287f092009-11-05 00:51:44 +00008455// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008456ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008457 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008458 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008459}
8460
Steve Naroff66356bd2007-09-16 14:56:35 +00008461/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008462ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008463 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008464 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008465 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008466 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008467 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008468}
8469
John McCalldadc5752010-08-24 06:29:42 +00008470ExprResult
John McCallb268a282010-08-23 23:25:46 +00008471Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008472 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008473 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8474 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8475
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008476 bool isFileScope
8477 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008478 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008479 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008480
Chris Lattner366727f2007-07-24 16:58:17 +00008481 // FIXME: there are a variety of strange constraints to enforce here, for
8482 // example, it is not possible to goto into a stmt expression apparently.
8483 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008484
Chris Lattner366727f2007-07-24 16:58:17 +00008485 // If there are sub stmts in the compound stmt, take the type of the last one
8486 // as the type of the stmtexpr.
8487 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008488 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008489 if (!Compound->body_empty()) {
8490 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008491 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008492 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008493 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8494 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008495 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008496 }
8497 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008498 // Do function/array conversion on the last expression, but not
8499 // lvalue-to-rvalue. However, initialize an unqualified type.
8500 DefaultFunctionArrayConversion(LastExpr);
8501 Ty = LastExpr->getType().getUnqualifiedType();
8502
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008503 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8504 ExprResult Res = PerformCopyInitialization(
8505 InitializedEntity::InitializeResult(LPLoc,
8506 Ty,
8507 false),
8508 SourceLocation(),
8509 Owned(LastExpr));
8510 if (Res.isInvalid())
8511 return ExprError();
8512 if ((LastExpr = Res.takeAs<Expr>())) {
8513 if (!LastLabelStmt)
8514 Compound->setLastStmt(LastExpr);
8515 else
8516 LastLabelStmt->setSubStmt(LastExpr);
8517 StmtExprMayBindToTemp = true;
8518 }
8519 }
8520 }
Chris Lattner944d3062008-07-26 19:51:01 +00008521 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008522
Eli Friedmanba961a92009-03-23 00:24:07 +00008523 // FIXME: Check that expression type is complete/non-abstract; statement
8524 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008525 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8526 if (StmtExprMayBindToTemp)
8527 return MaybeBindToTemporary(ResStmtExpr);
8528 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008529}
Steve Naroff78864672007-08-01 22:05:33 +00008530
John McCalldadc5752010-08-24 06:29:42 +00008531ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008532 TypeSourceInfo *TInfo,
8533 OffsetOfComponent *CompPtr,
8534 unsigned NumComponents,
8535 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008536 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008537 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008538 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008539
Chris Lattnerf17bd422007-08-30 17:45:32 +00008540 // We must have at least one component that refers to the type, and the first
8541 // one is known to be a field designator. Verify that the ArgTy represents
8542 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008543 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008544 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8545 << ArgTy << TypeRange);
8546
8547 // Type must be complete per C99 7.17p3 because a declaring a variable
8548 // with an incomplete type would be ill-formed.
8549 if (!Dependent
8550 && RequireCompleteType(BuiltinLoc, ArgTy,
8551 PDiag(diag::err_offsetof_incomplete_type)
8552 << TypeRange))
8553 return ExprError();
8554
Chris Lattner78502cf2007-08-31 21:49:13 +00008555 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8556 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008557 // FIXME: This diagnostic isn't actually visible because the location is in
8558 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008559 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008560 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8561 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008562
8563 bool DidWarnAboutNonPOD = false;
8564 QualType CurrentType = ArgTy;
8565 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8566 llvm::SmallVector<OffsetOfNode, 4> Comps;
8567 llvm::SmallVector<Expr*, 4> Exprs;
8568 for (unsigned i = 0; i != NumComponents; ++i) {
8569 const OffsetOfComponent &OC = CompPtr[i];
8570 if (OC.isBrackets) {
8571 // Offset of an array sub-field. TODO: Should we allow vector elements?
8572 if (!CurrentType->isDependentType()) {
8573 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8574 if(!AT)
8575 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8576 << CurrentType);
8577 CurrentType = AT->getElementType();
8578 } else
8579 CurrentType = Context.DependentTy;
8580
8581 // The expression must be an integral expression.
8582 // FIXME: An integral constant expression?
8583 Expr *Idx = static_cast<Expr*>(OC.U.E);
8584 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8585 !Idx->getType()->isIntegerType())
8586 return ExprError(Diag(Idx->getLocStart(),
8587 diag::err_typecheck_subscript_not_integer)
8588 << Idx->getSourceRange());
8589
8590 // Record this array index.
8591 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8592 Exprs.push_back(Idx);
8593 continue;
8594 }
8595
8596 // Offset of a field.
8597 if (CurrentType->isDependentType()) {
8598 // We have the offset of a field, but we can't look into the dependent
8599 // type. Just record the identifier of the field.
8600 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8601 CurrentType = Context.DependentTy;
8602 continue;
8603 }
8604
8605 // We need to have a complete type to look into.
8606 if (RequireCompleteType(OC.LocStart, CurrentType,
8607 diag::err_offsetof_incomplete_type))
8608 return ExprError();
8609
8610 // Look for the designated field.
8611 const RecordType *RC = CurrentType->getAs<RecordType>();
8612 if (!RC)
8613 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8614 << CurrentType);
8615 RecordDecl *RD = RC->getDecl();
8616
8617 // C++ [lib.support.types]p5:
8618 // The macro offsetof accepts a restricted set of type arguments in this
8619 // International Standard. type shall be a POD structure or a POD union
8620 // (clause 9).
8621 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8622 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008623 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008624 PDiag(diag::warn_offsetof_non_pod_type)
8625 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8626 << CurrentType))
8627 DidWarnAboutNonPOD = true;
8628 }
8629
8630 // Look for the field.
8631 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8632 LookupQualifiedName(R, RD);
8633 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008634 IndirectFieldDecl *IndirectMemberDecl = 0;
8635 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008636 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008637 MemberDecl = IndirectMemberDecl->getAnonField();
8638 }
8639
Douglas Gregor882211c2010-04-28 22:16:22 +00008640 if (!MemberDecl)
8641 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8642 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8643 OC.LocEnd));
8644
Douglas Gregor10982ea2010-04-28 22:36:06 +00008645 // C99 7.17p3:
8646 // (If the specified member is a bit-field, the behavior is undefined.)
8647 //
8648 // We diagnose this as an error.
8649 if (MemberDecl->getBitWidth()) {
8650 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8651 << MemberDecl->getDeclName()
8652 << SourceRange(BuiltinLoc, RParenLoc);
8653 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8654 return ExprError();
8655 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008656
8657 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008658 if (IndirectMemberDecl)
8659 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008660
Douglas Gregord1702062010-04-29 00:18:15 +00008661 // If the member was found in a base class, introduce OffsetOfNodes for
8662 // the base class indirections.
8663 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8664 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008665 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008666 CXXBasePath &Path = Paths.front();
8667 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8668 B != BEnd; ++B)
8669 Comps.push_back(OffsetOfNode(B->Base));
8670 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008671
Francois Pichet783dd6e2010-11-21 06:08:52 +00008672 if (IndirectMemberDecl) {
8673 for (IndirectFieldDecl::chain_iterator FI =
8674 IndirectMemberDecl->chain_begin(),
8675 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8676 assert(isa<FieldDecl>(*FI));
8677 Comps.push_back(OffsetOfNode(OC.LocStart,
8678 cast<FieldDecl>(*FI), OC.LocEnd));
8679 }
8680 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008681 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008682
Douglas Gregor882211c2010-04-28 22:16:22 +00008683 CurrentType = MemberDecl->getType().getNonReferenceType();
8684 }
8685
8686 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8687 TInfo, Comps.data(), Comps.size(),
8688 Exprs.data(), Exprs.size(), RParenLoc));
8689}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008690
John McCalldadc5752010-08-24 06:29:42 +00008691ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008692 SourceLocation BuiltinLoc,
8693 SourceLocation TypeLoc,
8694 ParsedType argty,
8695 OffsetOfComponent *CompPtr,
8696 unsigned NumComponents,
8697 SourceLocation RPLoc) {
8698
Douglas Gregor882211c2010-04-28 22:16:22 +00008699 TypeSourceInfo *ArgTInfo;
8700 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8701 if (ArgTy.isNull())
8702 return ExprError();
8703
Eli Friedman06dcfd92010-08-05 10:15:45 +00008704 if (!ArgTInfo)
8705 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8706
8707 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8708 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008709}
8710
8711
John McCalldadc5752010-08-24 06:29:42 +00008712ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008713 Expr *CondExpr,
8714 Expr *LHSExpr, Expr *RHSExpr,
8715 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008716 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8717
John McCall7decc9e2010-11-18 06:31:45 +00008718 ExprValueKind VK = VK_RValue;
8719 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008720 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008721 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008722 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008723 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008724 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008725 } else {
8726 // The conditional expression is required to be a constant expression.
8727 llvm::APSInt condEval(32);
8728 SourceLocation ExpLoc;
8729 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008730 return ExprError(Diag(ExpLoc,
8731 diag::err_typecheck_choose_expr_requires_constant)
8732 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008733
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008734 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008735 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8736
8737 resType = ActiveExpr->getType();
8738 ValueDependent = ActiveExpr->isValueDependent();
8739 VK = ActiveExpr->getValueKind();
8740 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008741 }
8742
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008743 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008744 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008745 resType->isDependentType(),
8746 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008747}
8748
Steve Naroffc540d662008-09-03 18:15:37 +00008749//===----------------------------------------------------------------------===//
8750// Clang Extensions.
8751//===----------------------------------------------------------------------===//
8752
8753/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008754void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008755 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8756 PushBlockScope(BlockScope, Block);
8757 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008758 if (BlockScope)
8759 PushDeclContext(BlockScope, Block);
8760 else
8761 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008762}
8763
Mike Stump82f071f2009-02-04 22:31:32 +00008764void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008765 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008766 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008767 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008768
John McCall8cb7bdf2010-06-04 23:28:52 +00008769 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008770 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008771
John McCall3882ace2011-01-05 12:14:39 +00008772 // GetTypeForDeclarator always produces a function type for a block
8773 // literal signature. Furthermore, it is always a FunctionProtoType
8774 // unless the function was written with a typedef.
8775 assert(T->isFunctionType() &&
8776 "GetTypeForDeclarator made a non-function block signature");
8777
8778 // Look for an explicit signature in that function type.
8779 FunctionProtoTypeLoc ExplicitSignature;
8780
8781 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8782 if (isa<FunctionProtoTypeLoc>(tmp)) {
8783 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8784
8785 // Check whether that explicit signature was synthesized by
8786 // GetTypeForDeclarator. If so, don't save that as part of the
8787 // written signature.
8788 if (ExplicitSignature.getLParenLoc() ==
8789 ExplicitSignature.getRParenLoc()) {
8790 // This would be much cheaper if we stored TypeLocs instead of
8791 // TypeSourceInfos.
8792 TypeLoc Result = ExplicitSignature.getResultLoc();
8793 unsigned Size = Result.getFullDataSize();
8794 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8795 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8796
8797 ExplicitSignature = FunctionProtoTypeLoc();
8798 }
John McCalla3ccba02010-06-04 11:21:44 +00008799 }
Mike Stump11289f42009-09-09 15:08:12 +00008800
John McCall3882ace2011-01-05 12:14:39 +00008801 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8802 CurBlock->FunctionType = T;
8803
8804 const FunctionType *Fn = T->getAs<FunctionType>();
8805 QualType RetTy = Fn->getResultType();
8806 bool isVariadic =
8807 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8808
John McCall8e346702010-06-04 19:02:56 +00008809 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008810
John McCalla3ccba02010-06-04 11:21:44 +00008811 // Don't allow returning a objc interface by value.
8812 if (RetTy->isObjCObjectType()) {
8813 Diag(ParamInfo.getSourceRange().getBegin(),
8814 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8815 return;
8816 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008817
John McCalla3ccba02010-06-04 11:21:44 +00008818 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008819 // return type. TODO: what should we do with declarators like:
8820 // ^ * { ... }
8821 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008822 if (RetTy != Context.DependentTy)
8823 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008824
John McCalla3ccba02010-06-04 11:21:44 +00008825 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00008826 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008827 if (ExplicitSignature) {
8828 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8829 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008830 if (Param->getIdentifier() == 0 &&
8831 !Param->isImplicit() &&
8832 !Param->isInvalidDecl() &&
8833 !getLangOptions().CPlusPlus)
8834 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008835 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008836 }
John McCalla3ccba02010-06-04 11:21:44 +00008837
8838 // Fake up parameter variables if we have a typedef, like
8839 // ^ fntype { ... }
8840 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8841 for (FunctionProtoType::arg_type_iterator
8842 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8843 ParmVarDecl *Param =
8844 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8845 ParamInfo.getSourceRange().getBegin(),
8846 *I);
John McCall8e346702010-06-04 19:02:56 +00008847 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008848 }
Steve Naroffc540d662008-09-03 18:15:37 +00008849 }
John McCalla3ccba02010-06-04 11:21:44 +00008850
John McCall8e346702010-06-04 19:02:56 +00008851 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008852 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008853 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008854 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8855 CurBlock->TheDecl->param_end(),
8856 /*CheckParameterNames=*/false);
8857 }
8858
John McCalla3ccba02010-06-04 11:21:44 +00008859 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008860 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008861
John McCall8e346702010-06-04 19:02:56 +00008862 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008863 Diag(ParamInfo.getAttributes()->getLoc(),
8864 diag::warn_attribute_sentinel_not_variadic) << 1;
8865 // FIXME: remove the attribute.
8866 }
8867
8868 // Put the parameter variables in scope. We can bail out immediately
8869 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008870 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008871 return;
8872
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008873 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008874 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8875 (*AI)->setOwningFunction(CurBlock->TheDecl);
8876
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008877 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008878 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008879 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008880
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008881 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008882 }
John McCallf7b2fb52010-01-22 00:28:27 +00008883 }
Steve Naroffc540d662008-09-03 18:15:37 +00008884}
8885
8886/// ActOnBlockError - If there is an error parsing a block, this callback
8887/// is invoked to pop the information about the block from the action impl.
8888void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008889 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008890 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008891 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008892}
8893
8894/// ActOnBlockStmtExpr - This is called when the body of a block statement
8895/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008896ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008897 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008898 // If blocks are disabled, emit an error.
8899 if (!LangOpts.Blocks)
8900 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008901
Douglas Gregor9a28e842010-03-01 23:15:13 +00008902 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008903
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008904 PopDeclContext();
8905
Steve Naroffc540d662008-09-03 18:15:37 +00008906 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008907 if (!BSI->ReturnType.isNull())
8908 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008909
Mike Stump3bf1ab42009-07-28 22:04:01 +00008910 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008911 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008912
John McCallc63de662011-02-02 13:00:07 +00008913 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008914 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8915 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008916
John McCall8e346702010-06-04 19:02:56 +00008917 // If the user wrote a function type in some form, try to use that.
8918 if (!BSI->FunctionType.isNull()) {
8919 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8920
8921 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8922 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8923
8924 // Turn protoless block types into nullary block types.
8925 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008926 FunctionProtoType::ExtProtoInfo EPI;
8927 EPI.ExtInfo = Ext;
8928 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008929
8930 // Otherwise, if we don't need to change anything about the function type,
8931 // preserve its sugar structure.
8932 } else if (FTy->getResultType() == RetTy &&
8933 (!NoReturn || FTy->getNoReturnAttr())) {
8934 BlockTy = BSI->FunctionType;
8935
8936 // Otherwise, make the minimal modifications to the function type.
8937 } else {
8938 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008939 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8940 EPI.TypeQuals = 0; // FIXME: silently?
8941 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008942 BlockTy = Context.getFunctionType(RetTy,
8943 FPT->arg_type_begin(),
8944 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008945 EPI);
John McCall8e346702010-06-04 19:02:56 +00008946 }
8947
8948 // If we don't have a function type, just build one from nothing.
8949 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008950 FunctionProtoType::ExtProtoInfo EPI;
8951 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
8952 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008953 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008954
John McCall8e346702010-06-04 19:02:56 +00008955 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8956 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008957 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008958
Chris Lattner45542ea2009-04-19 05:28:12 +00008959 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00008960 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008961 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008962
Chris Lattner60f84492011-02-17 23:58:47 +00008963 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008964
John McCallc63de662011-02-02 13:00:07 +00008965 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCall1d570a72010-08-25 05:56:39 +00008966
Ted Kremenek1767a272011-02-23 01:51:48 +00008967 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8968 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008969 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008970}
8971
John McCalldadc5752010-08-24 06:29:42 +00008972ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008973 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008974 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008975 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008976 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008977 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008978}
8979
John McCalldadc5752010-08-24 06:29:42 +00008980ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008981 Expr *E, TypeSourceInfo *TInfo,
8982 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008983 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008984
Eli Friedman121ba0c2008-08-09 23:32:40 +00008985 // Get the va_list type
8986 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008987 if (VaListType->isArrayType()) {
8988 // Deal with implicit array decay; for example, on x86-64,
8989 // va_list is an array, but it's supposed to decay to
8990 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008991 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008992 // Make sure the input expression also decays appropriately.
8993 UsualUnaryConversions(E);
8994 } else {
8995 // Otherwise, the va_list argument must be an l-value because
8996 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008997 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008998 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008999 return ExprError();
9000 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009001
Douglas Gregorad3150c2009-05-19 23:10:31 +00009002 if (!E->isTypeDependent() &&
9003 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009004 return ExprError(Diag(E->getLocStart(),
9005 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009006 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009007 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009008
Eli Friedmanba961a92009-03-23 00:24:07 +00009009 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009010 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009011
Abramo Bagnara27db2392010-08-10 10:06:15 +00009012 QualType T = TInfo->getType().getNonLValueExprType(Context);
9013 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009014}
9015
John McCalldadc5752010-08-24 06:29:42 +00009016ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009017 // The type of __null will be int or long, depending on the size of
9018 // pointers on the target.
9019 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009020 unsigned pw = Context.Target.getPointerWidth(0);
9021 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009022 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009023 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009024 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009025 else if (pw == Context.Target.getLongLongWidth())
9026 Ty = Context.LongLongTy;
9027 else {
9028 assert(!"I don't know size of pointer!");
9029 Ty = Context.IntTy;
9030 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009031
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009032 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009033}
9034
Alexis Huntc46382e2010-04-28 23:02:27 +00009035static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009036 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00009037 if (!SemaRef.getLangOptions().ObjC1)
9038 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009039
Anders Carlssonace5d072009-11-10 04:46:30 +00009040 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9041 if (!PT)
9042 return;
9043
9044 // Check if the destination is of type 'id'.
9045 if (!PT->isObjCIdType()) {
9046 // Check if the destination is the 'NSString' interface.
9047 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9048 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9049 return;
9050 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009051
Anders Carlssonace5d072009-11-10 04:46:30 +00009052 // Strip off any parens and casts.
9053 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9054 if (!SL || SL->isWide())
9055 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009056
Douglas Gregora771f462010-03-31 17:46:05 +00009057 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009058}
9059
Chris Lattner9bad62c2008-01-04 18:04:52 +00009060bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9061 SourceLocation Loc,
9062 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009063 Expr *SrcExpr, AssignmentAction Action,
9064 bool *Complained) {
9065 if (Complained)
9066 *Complained = false;
9067
Chris Lattner9bad62c2008-01-04 18:04:52 +00009068 // Decode the result (notice that AST's are still created for extensions).
9069 bool isInvalid = false;
9070 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00009071 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009072
Chris Lattner9bad62c2008-01-04 18:04:52 +00009073 switch (ConvTy) {
9074 default: assert(0 && "Unknown conversion type");
9075 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009076 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009077 DiagKind = diag::ext_typecheck_convert_pointer_int;
9078 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009079 case IntToPointer:
9080 DiagKind = diag::ext_typecheck_convert_int_pointer;
9081 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009082 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009083 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009084 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9085 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009086 case IncompatiblePointerSign:
9087 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9088 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009089 case FunctionVoidPointer:
9090 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9091 break;
John McCall4fff8f62011-02-01 00:10:29 +00009092 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009093 // Perform array-to-pointer decay if necessary.
9094 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9095
John McCall4fff8f62011-02-01 00:10:29 +00009096 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9097 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9098 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9099 DiagKind = diag::err_typecheck_incompatible_address_space;
9100 break;
9101 }
9102
9103 llvm_unreachable("unknown error case for discarding qualifiers!");
9104 // fallthrough
9105 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009106 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009107 // If the qualifiers lost were because we were applying the
9108 // (deprecated) C++ conversion from a string literal to a char*
9109 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9110 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009111 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009112 // bit of refactoring (so that the second argument is an
9113 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009114 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009115 // C++ semantics.
9116 if (getLangOptions().CPlusPlus &&
9117 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9118 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009119 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9120 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009121 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009122 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009123 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009124 case IntToBlockPointer:
9125 DiagKind = diag::err_int_to_block_pointer;
9126 break;
9127 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009128 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009129 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009130 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009131 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009132 // it can give a more specific diagnostic.
9133 DiagKind = diag::warn_incompatible_qualified_id;
9134 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009135 case IncompatibleVectors:
9136 DiagKind = diag::warn_incompatible_vectors;
9137 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009138 case Incompatible:
9139 DiagKind = diag::err_typecheck_convert_incompatible;
9140 isInvalid = true;
9141 break;
9142 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009143
Douglas Gregorc68e1402010-04-09 00:35:39 +00009144 QualType FirstType, SecondType;
9145 switch (Action) {
9146 case AA_Assigning:
9147 case AA_Initializing:
9148 // The destination type comes first.
9149 FirstType = DstType;
9150 SecondType = SrcType;
9151 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009152
Douglas Gregorc68e1402010-04-09 00:35:39 +00009153 case AA_Returning:
9154 case AA_Passing:
9155 case AA_Converting:
9156 case AA_Sending:
9157 case AA_Casting:
9158 // The source type comes first.
9159 FirstType = SrcType;
9160 SecondType = DstType;
9161 break;
9162 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009163
Douglas Gregorc68e1402010-04-09 00:35:39 +00009164 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00009165 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009166 if (Complained)
9167 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009168 return isInvalid;
9169}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009170
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009171bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009172 llvm::APSInt ICEResult;
9173 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9174 if (Result)
9175 *Result = ICEResult;
9176 return false;
9177 }
9178
Anders Carlssone54e8a12008-11-30 19:50:32 +00009179 Expr::EvalResult EvalResult;
9180
Mike Stump4e1f26a2009-02-19 03:04:26 +00009181 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009182 EvalResult.HasSideEffects) {
9183 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9184
9185 if (EvalResult.Diag) {
9186 // We only show the note if it's not the usual "invalid subexpression"
9187 // or if it's actually in a subexpression.
9188 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9189 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9190 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9191 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009192
Anders Carlssone54e8a12008-11-30 19:50:32 +00009193 return true;
9194 }
9195
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009196 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9197 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009198
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009199 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009200 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9201 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009202 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009203
Anders Carlssone54e8a12008-11-30 19:50:32 +00009204 if (Result)
9205 *Result = EvalResult.Val.getInt();
9206 return false;
9207}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009208
Douglas Gregorff790f12009-11-26 00:44:06 +00009209void
Mike Stump11289f42009-09-09 15:08:12 +00009210Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009211 ExprEvalContexts.push_back(
9212 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009213}
9214
Mike Stump11289f42009-09-09 15:08:12 +00009215void
Douglas Gregorff790f12009-11-26 00:44:06 +00009216Sema::PopExpressionEvaluationContext() {
9217 // Pop the current expression evaluation context off the stack.
9218 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9219 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009220
Douglas Gregorfab31f42009-12-12 07:57:52 +00009221 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9222 if (Rec.PotentiallyReferenced) {
9223 // Mark any remaining declarations in the current position of the stack
9224 // as "referenced". If they were not meant to be referenced, semantic
9225 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009226 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009227 I = Rec.PotentiallyReferenced->begin(),
9228 IEnd = Rec.PotentiallyReferenced->end();
9229 I != IEnd; ++I)
9230 MarkDeclarationReferenced(I->first, I->second);
9231 }
9232
9233 if (Rec.PotentiallyDiagnosed) {
9234 // Emit any pending diagnostics.
9235 for (PotentiallyEmittedDiagnostics::iterator
9236 I = Rec.PotentiallyDiagnosed->begin(),
9237 IEnd = Rec.PotentiallyDiagnosed->end();
9238 I != IEnd; ++I)
9239 Diag(I->first, I->second);
9240 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009241 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009242
9243 // When are coming out of an unevaluated context, clear out any
9244 // temporaries that we may have created as part of the evaluation of
9245 // the expression in that context: they aren't relevant because they
9246 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009247 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00009248 ExprTemporaries.size() > Rec.NumTemporaries)
9249 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9250 ExprTemporaries.end());
9251
9252 // Destroy the popped expression evaluation record.
9253 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009254}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009255
9256/// \brief Note that the given declaration was referenced in the source code.
9257///
9258/// This routine should be invoke whenever a given declaration is referenced
9259/// in the source code, and where that reference occurred. If this declaration
9260/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9261/// C99 6.9p3), then the declaration will be marked as used.
9262///
9263/// \param Loc the location where the declaration was referenced.
9264///
9265/// \param D the declaration that has been referenced by the source code.
9266void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9267 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009268
Douglas Gregorebada0772010-06-17 23:14:26 +00009269 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009270 return;
Mike Stump11289f42009-09-09 15:08:12 +00009271
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00009272 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9273 // template or not. The reason for this is that unevaluated expressions
9274 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9275 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009276 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009277 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009278 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009279 return;
9280 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009281
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009282 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9283 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009284
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009285 // Do not mark anything as "used" within a dependent context; wait for
9286 // an instantiation.
9287 if (CurContext->isDependentContext())
9288 return;
Mike Stump11289f42009-09-09 15:08:12 +00009289
Douglas Gregorff790f12009-11-26 00:44:06 +00009290 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009291 case Unevaluated:
9292 // We are in an expression that is not potentially evaluated; do nothing.
9293 return;
Mike Stump11289f42009-09-09 15:08:12 +00009294
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009295 case PotentiallyEvaluated:
9296 // We are in a potentially-evaluated expression, so this declaration is
9297 // "used"; handle this below.
9298 break;
Mike Stump11289f42009-09-09 15:08:12 +00009299
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009300 case PotentiallyPotentiallyEvaluated:
9301 // We are in an expression that may be potentially evaluated; queue this
9302 // declaration reference until we know whether the expression is
9303 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009304 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009305 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009306
9307 case PotentiallyEvaluatedIfUsed:
9308 // Referenced declarations will only be used if the construct in the
9309 // containing expression is used.
9310 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009311 }
Mike Stump11289f42009-09-09 15:08:12 +00009312
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009313 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009314 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009315 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00009316 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00009317 if (Constructor->getParent()->hasTrivialConstructor())
9318 return;
9319 if (!Constructor->isUsed(false))
9320 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00009321 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00009322 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009323 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009324 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9325 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009326
Douglas Gregor88d292c2010-05-13 16:44:06 +00009327 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009328 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009329 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009330 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009331 if (Destructor->isVirtual())
9332 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009333 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9334 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9335 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009336 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009337 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009338 } else if (MethodDecl->isVirtual())
9339 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009340 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009341 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009342 // Recursive functions should be marked when used from another function.
9343 if (CurContext == Function) return;
9344
Mike Stump11289f42009-09-09 15:08:12 +00009345 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009346 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009347 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009348 bool AlreadyInstantiated = false;
9349 if (FunctionTemplateSpecializationInfo *SpecInfo
9350 = Function->getTemplateSpecializationInfo()) {
9351 if (SpecInfo->getPointOfInstantiation().isInvalid())
9352 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009353 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009354 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009355 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009356 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009357 = Function->getMemberSpecializationInfo()) {
9358 if (MSInfo->getPointOfInstantiation().isInvalid())
9359 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009360 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009361 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009362 AlreadyInstantiated = true;
9363 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009364
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009365 if (!AlreadyInstantiated) {
9366 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9367 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9368 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9369 Loc));
9370 else
Chandler Carruth54080172010-08-25 08:44:16 +00009371 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009372 }
John McCall83779672011-02-19 02:53:41 +00009373 } else {
9374 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009375 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9376 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009377 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009378 MarkDeclarationReferenced(Loc, *i);
9379 }
John McCall83779672011-02-19 02:53:41 +00009380 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009381
John McCall83779672011-02-19 02:53:41 +00009382 // Keep track of used but undefined functions.
9383 if (!Function->isPure() && !Function->hasBody() &&
9384 Function->getLinkage() != ExternalLinkage) {
9385 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9386 if (old.isInvalid()) old = Loc;
9387 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009388
John McCall83779672011-02-19 02:53:41 +00009389 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009390 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009391 }
Mike Stump11289f42009-09-09 15:08:12 +00009392
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009393 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009394 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009395 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009396 Var->getInstantiatedFromStaticDataMember()) {
9397 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9398 assert(MSInfo && "Missing member specialization information?");
9399 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9400 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9401 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +00009402 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009403 }
9404 }
Mike Stump11289f42009-09-09 15:08:12 +00009405
John McCall15dd4042011-02-21 19:25:48 +00009406 // Keep track of used but undefined variables. We make a hole in
9407 // the warning for static const data members with in-line
9408 // initializers.
John McCall83779672011-02-19 02:53:41 +00009409 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009410 && Var->getLinkage() != ExternalLinkage
9411 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009412 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9413 if (old.isInvalid()) old = Loc;
9414 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009415
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009416 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009417 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009418 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009419}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009420
Douglas Gregor5597ab42010-05-07 23:12:07 +00009421namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009422 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009423 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009424 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009425 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9426 Sema &S;
9427 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009428
Douglas Gregor5597ab42010-05-07 23:12:07 +00009429 public:
9430 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009431
Douglas Gregor5597ab42010-05-07 23:12:07 +00009432 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009433
9434 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9435 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009436 };
9437}
9438
Chandler Carruthaf80f662010-06-09 08:17:30 +00009439bool MarkReferencedDecls::TraverseTemplateArgument(
9440 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009441 if (Arg.getKind() == TemplateArgument::Declaration) {
9442 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9443 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009444
9445 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009446}
9447
Chandler Carruthaf80f662010-06-09 08:17:30 +00009448bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009449 if (ClassTemplateSpecializationDecl *Spec
9450 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9451 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009452 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009453 }
9454
Chandler Carruthc65667c2010-06-10 10:31:57 +00009455 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009456}
9457
9458void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9459 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009460 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009461}
9462
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009463namespace {
9464 /// \brief Helper class that marks all of the declarations referenced by
9465 /// potentially-evaluated subexpressions as "referenced".
9466 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9467 Sema &S;
9468
9469 public:
9470 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9471
9472 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9473
9474 void VisitDeclRefExpr(DeclRefExpr *E) {
9475 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9476 }
9477
9478 void VisitMemberExpr(MemberExpr *E) {
9479 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009480 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009481 }
9482
9483 void VisitCXXNewExpr(CXXNewExpr *E) {
9484 if (E->getConstructor())
9485 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9486 if (E->getOperatorNew())
9487 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9488 if (E->getOperatorDelete())
9489 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009490 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009491 }
9492
9493 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9494 if (E->getOperatorDelete())
9495 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009496 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9497 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9498 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9499 S.MarkDeclarationReferenced(E->getLocStart(),
9500 S.LookupDestructor(Record));
9501 }
9502
Douglas Gregor32b3de52010-09-11 23:32:50 +00009503 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009504 }
9505
9506 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9507 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009508 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009509 }
9510
9511 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9512 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9513 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009514
9515 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9516 Visit(E->getExpr());
9517 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009518 };
9519}
9520
9521/// \brief Mark any declarations that appear within this expression or any
9522/// potentially-evaluated subexpressions as "referenced".
9523void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9524 EvaluatedExprMarker(*this).Visit(E);
9525}
9526
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009527/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9528/// of the program being compiled.
9529///
9530/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009531/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009532/// possibility that the code will actually be executable. Code in sizeof()
9533/// expressions, code used only during overload resolution, etc., are not
9534/// potentially evaluated. This routine will suppress such diagnostics or,
9535/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009536/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009537/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009538///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009539/// This routine should be used for all diagnostics that describe the run-time
9540/// behavior of a program, such as passing a non-POD value through an ellipsis.
9541/// Failure to do so will likely result in spurious diagnostics or failures
9542/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009543bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009544 const PartialDiagnostic &PD) {
9545 switch (ExprEvalContexts.back().Context ) {
9546 case Unevaluated:
9547 // The argument will never be evaluated, so don't complain.
9548 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009549
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009550 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009551 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009552 if (stmt && getCurFunctionOrMethodDecl()) {
9553 FunctionScopes.back()->PossiblyUnreachableDiags.
9554 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9555 }
9556 else
9557 Diag(Loc, PD);
9558
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009559 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009560
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009561 case PotentiallyPotentiallyEvaluated:
9562 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9563 break;
9564 }
9565
9566 return false;
9567}
9568
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009569bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9570 CallExpr *CE, FunctionDecl *FD) {
9571 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9572 return false;
9573
9574 PartialDiagnostic Note =
9575 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9576 << FD->getDeclName() : PDiag();
9577 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009578
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009579 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009580 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009581 PDiag(diag::err_call_function_incomplete_return)
9582 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009583 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009584 << CE->getSourceRange(),
9585 std::make_pair(NoteLoc, Note)))
9586 return true;
9587
9588 return false;
9589}
9590
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009591// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009592// will prevent this condition from triggering, which is what we want.
9593void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9594 SourceLocation Loc;
9595
John McCall0506e4a2009-11-11 02:41:58 +00009596 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009597 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009598
John McCalld5707ab2009-10-12 21:59:07 +00009599 if (isa<BinaryOperator>(E)) {
9600 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009601 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009602 return;
9603
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009604 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9605
John McCallb0e419e2009-11-12 00:06:05 +00009606 // Greylist some idioms by putting them into a warning subcategory.
9607 if (ObjCMessageExpr *ME
9608 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9609 Selector Sel = ME->getSelector();
9610
John McCallb0e419e2009-11-12 00:06:05 +00009611 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009612 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009613 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9614
9615 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009616 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009617 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9618 }
John McCall0506e4a2009-11-11 02:41:58 +00009619
John McCalld5707ab2009-10-12 21:59:07 +00009620 Loc = Op->getOperatorLoc();
9621 } else if (isa<CXXOperatorCallExpr>(E)) {
9622 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009623 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009624 return;
9625
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009626 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009627 Loc = Op->getOperatorLoc();
9628 } else {
9629 // Not an assignment.
9630 return;
9631 }
9632
John McCalld5707ab2009-10-12 21:59:07 +00009633 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00009634 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009635
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009636 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009637
9638 if (IsOrAssign)
9639 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9640 << FixItHint::CreateReplacement(Loc, "!=");
9641 else
9642 Diag(Loc, diag::note_condition_assign_to_comparison)
9643 << FixItHint::CreateReplacement(Loc, "==");
9644
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009645 Diag(Loc, diag::note_condition_assign_silence)
9646 << FixItHint::CreateInsertion(Open, "(")
9647 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +00009648}
9649
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009650/// \brief Redundant parentheses over an equality comparison can indicate
9651/// that the user intended an assignment used as condition.
9652void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009653 // Don't warn if the parens came from a macro.
9654 SourceLocation parenLoc = parenE->getLocStart();
9655 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9656 return;
9657
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009658 Expr *E = parenE->IgnoreParens();
9659
9660 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009661 if (opE->getOpcode() == BO_EQ &&
9662 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9663 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009664 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009665
Ted Kremenekae022092011-02-02 02:20:30 +00009666 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9667 Diag(Loc, diag::note_equality_comparison_to_assign)
9668 << FixItHint::CreateReplacement(Loc, "=");
9669 Diag(Loc, diag::note_equality_comparison_silence)
9670 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9671 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009672 }
9673}
9674
John McCalld5707ab2009-10-12 21:59:07 +00009675bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9676 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009677 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9678 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009679
9680 if (!E->isTypeDependent()) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009681 if (E->isBoundMemberFunction(Context))
9682 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9683 << E->getSourceRange();
9684
John McCall34376a62010-12-04 03:47:34 +00009685 if (getLangOptions().CPlusPlus)
9686 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9687
9688 DefaultFunctionArrayLvalueConversion(E);
John McCall29cb2fd2010-12-04 06:09:13 +00009689
9690 QualType T = E->getType();
John McCall34376a62010-12-04 03:47:34 +00009691 if (!T->isScalarType()) // C99 6.8.4.1p1
9692 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9693 << T << E->getSourceRange();
John McCalld5707ab2009-10-12 21:59:07 +00009694 }
9695
9696 return false;
9697}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009698
John McCalldadc5752010-08-24 06:29:42 +00009699ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9700 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009701 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009702 return ExprError();
9703
Douglas Gregorb412e172010-07-25 18:17:45 +00009704 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00009705 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00009706
9707 return Owned(Sub);
9708}
John McCall36e7fe32010-10-12 00:20:44 +00009709
9710/// Check for operands with placeholder types and complain if found.
9711/// Returns true if there was an error and no recovery was possible.
9712ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9713 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9714 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9715
9716 // If this is overload, check for a single overload.
Richard Smith30482bc2011-02-20 03:19:35 +00009717 assert(BT->getKind() == BuiltinType::Overload);
John McCall36e7fe32010-10-12 00:20:44 +00009718
Richard Smith30482bc2011-02-20 03:19:35 +00009719 if (FunctionDecl *Specialization
9720 = ResolveSingleFunctionTemplateSpecialization(E)) {
9721 // The access doesn't really matter in this case.
9722 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9723 Specialization->getAccess());
9724 E = FixOverloadedFunctionReference(E, Found, Specialization);
9725 if (!E) return ExprError();
9726 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +00009727 }
9728
Richard Smith30482bc2011-02-20 03:19:35 +00009729 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
John McCall36e7fe32010-10-12 00:20:44 +00009730 return ExprError();
9731}