blob: df49ad5c9a5f2ea22bcfa5a7707f8ed89cbe2c81 [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
Chris Lattner4bf74fd2009-02-15 22:43:40 +000078 // See if the decl is deprecated.
Benjamin Kramerbfac7dc2010-10-09 15:49:00 +000079 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>())
Peter Collingbourneed12ffb2011-01-02 19:53:12 +000080 EmitDeprecationWarning(D, DA->getMessage(), Loc, UnknownObjCClass);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000081
Chris Lattnera27dd592009-10-25 17:21:40 +000082 // See if the decl is unavailable
Fariborz Jahanianc74073c2010-10-06 23:12:32 +000083 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) {
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000084 if (UA->getMessage().empty()) {
Peter Collingbourneed12ffb2011-01-02 19:53:12 +000085 if (!UnknownObjCClass)
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000086 Diag(Loc, diag::err_unavailable) << D->getDeclName();
87 else
88 Diag(Loc, diag::warn_unavailable_fwdclass_message)
89 << D->getDeclName();
90 }
91 else
Fariborz Jahanianc74073c2010-10-06 23:12:32 +000092 Diag(Loc, diag::err_unavailable_message)
Benjamin Kramerbfac7dc2010-10-09 15:49:00 +000093 << D->getDeclName() << UA->getMessage();
Chris Lattnera27dd592009-10-25 17:21:40 +000094 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
95 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000096
Douglas Gregor171c45a2009-02-18 21:56:37 +000097 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000098 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000099 if (FD->isDeleted()) {
100 Diag(Loc, diag::err_deleted_function_use);
101 Diag(D->getLocation(), diag::note_unavailable_here) << true;
102 return true;
103 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000104 }
Douglas Gregor171c45a2009-02-18 21:56:37 +0000105
Anders Carlsson73067a02010-10-22 23:37:08 +0000106 // Warn if this is used but marked unused.
107 if (D->hasAttr<UnusedAttr>())
108 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
109
Douglas Gregor171c45a2009-02-18 21:56:37 +0000110 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000111}
112
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000113/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000114/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000115/// attribute. It warns if call does not have the sentinel argument.
116///
117void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000118 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000119 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000120 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000121 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000122
123 // FIXME: In C++0x, if any of the arguments are parameter pack
124 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000125 int sentinelPos = attr->getSentinel();
126 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000127
Mike Stump87c57ac2009-05-16 07:39:55 +0000128 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
129 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000130 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000131 bool warnNotEnoughArgs = false;
132 int isMethod = 0;
133 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
134 // skip over named parameters.
135 ObjCMethodDecl::param_iterator P, E = MD->param_end();
136 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
137 if (nullPos)
138 --nullPos;
139 else
140 ++i;
141 }
142 warnNotEnoughArgs = (P != E || i >= NumArgs);
143 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000144 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000145 // skip over named parameters.
146 ObjCMethodDecl::param_iterator P, E = FD->param_end();
147 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
148 if (nullPos)
149 --nullPos;
150 else
151 ++i;
152 }
153 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000154 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000155 // block or function pointer call.
156 QualType Ty = V->getType();
157 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000158 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000159 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
160 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000161 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
162 unsigned NumArgsInProto = Proto->getNumArgs();
163 unsigned k;
164 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
165 if (nullPos)
166 --nullPos;
167 else
168 ++i;
169 }
170 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
171 }
172 if (Ty->isBlockPointerType())
173 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000174 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000175 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000176 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000177 return;
178
179 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000180 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000181 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000182 return;
183 }
184 int sentinel = i;
185 while (sentinelPos > 0 && i < NumArgs-1) {
186 --sentinelPos;
187 ++i;
188 }
189 if (sentinelPos > 0) {
190 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000191 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000192 return;
193 }
194 while (i < NumArgs-1) {
195 ++i;
196 ++sentinel;
197 }
198 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000199 if (!sentinelExpr) return;
200 if (sentinelExpr->isTypeDependent()) return;
201 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000202
203 // nullptr_t is always treated as null.
204 if (sentinelExpr->getType()->isNullPtrType()) return;
205
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000206 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000207 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
208 Expr::NPC_ValueDependentIsNull))
209 return;
210
211 // Unfortunately, __null has type 'int'.
212 if (isa<GNUNullExpr>(sentinelExpr)) return;
213
214 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
215 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000216}
217
Douglas Gregor87f95b02009-02-26 21:00:50 +0000218SourceRange Sema::getExprRange(ExprTy *E) const {
219 Expr *Ex = (Expr *)E;
220 return Ex? Ex->getSourceRange() : SourceRange();
221}
222
Chris Lattner513165e2008-07-25 21:10:04 +0000223//===----------------------------------------------------------------------===//
224// Standard Promotions and Conversions
225//===----------------------------------------------------------------------===//
226
Chris Lattner513165e2008-07-25 21:10:04 +0000227/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
228void Sema::DefaultFunctionArrayConversion(Expr *&E) {
229 QualType Ty = E->getType();
230 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
231
Chris Lattner513165e2008-07-25 21:10:04 +0000232 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000233 ImpCastExprToType(E, Context.getPointerType(Ty),
John McCalle3027922010-08-25 11:45:40 +0000234 CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000235 else if (Ty->isArrayType()) {
236 // In C90 mode, arrays only promote to pointers if the array expression is
237 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
238 // type 'array of type' is converted to an expression that has type 'pointer
239 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
240 // that has type 'array of type' ...". The relevant change is "an lvalue"
241 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000242 //
243 // C++ 4.2p1:
244 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
245 // T" can be converted to an rvalue of type "pointer to T".
246 //
John McCall086a4642010-11-24 05:12:34 +0000247 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000248 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
John McCalle3027922010-08-25 11:45:40 +0000249 CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000250 }
Chris Lattner513165e2008-07-25 21:10:04 +0000251}
252
John McCall27584242010-12-06 20:48:59 +0000253void Sema::DefaultLvalueConversion(Expr *&E) {
John McCallf3735e02010-12-01 04:43:34 +0000254 // C++ [conv.lval]p1:
255 // A glvalue of a non-function, non-array type T can be
256 // converted to a prvalue.
John McCall27584242010-12-06 20:48:59 +0000257 if (!E->isGLValue()) return;
John McCall34376a62010-12-04 03:47:34 +0000258
John McCall27584242010-12-06 20:48:59 +0000259 QualType T = E->getType();
260 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000261
John McCall27584242010-12-06 20:48:59 +0000262 // Create a load out of an ObjCProperty l-value, if necessary.
263 if (E->getObjectKind() == OK_ObjCProperty) {
264 ConvertPropertyForRValue(E);
265 if (!E->isGLValue())
John McCall34376a62010-12-04 03:47:34 +0000266 return;
Douglas Gregorb92a1562010-02-03 00:27:59 +0000267 }
John McCall27584242010-12-06 20:48:59 +0000268
269 // We don't want to throw lvalue-to-rvalue casts on top of
270 // expressions of certain types in C++.
271 if (getLangOptions().CPlusPlus &&
272 (E->getType() == Context.OverloadTy ||
273 T->isDependentType() ||
274 T->isRecordType()))
275 return;
276
277 // The C standard is actually really unclear on this point, and
278 // DR106 tells us what the result should be but not why. It's
279 // generally best to say that void types just doesn't undergo
280 // lvalue-to-rvalue at all. Note that expressions of unqualified
281 // 'void' type are never l-values, but qualified void can be.
282 if (T->isVoidType())
283 return;
284
285 // C++ [conv.lval]p1:
286 // [...] If T is a non-class type, the type of the prvalue is the
287 // cv-unqualified version of T. Otherwise, the type of the
288 // rvalue is T.
289 //
290 // C99 6.3.2.1p2:
291 // If the lvalue has qualified type, the value has the unqualified
292 // version of the type of the lvalue; otherwise, the value has the
293 // type of the lvalue.
294 if (T.hasQualifiers())
295 T = T.getUnqualifiedType();
296
Ted Kremenek64699be2011-02-16 01:57:07 +0000297 if (const ArraySubscriptExpr *ae = dyn_cast<ArraySubscriptExpr>(E))
298 CheckArrayAccess(ae);
299
John McCall27584242010-12-06 20:48:59 +0000300 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
301 E, 0, VK_RValue);
302}
303
304void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
305 DefaultFunctionArrayConversion(E);
306 DefaultLvalueConversion(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000307}
308
309
Chris Lattner513165e2008-07-25 21:10:04 +0000310/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000311/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000312/// sometimes surpressed. For example, the array->pointer conversion doesn't
313/// apply if the array is an argument to the sizeof or address (&) operators.
314/// In these instances, this routine should *not* be called.
John McCallf3735e02010-12-01 04:43:34 +0000315Expr *Sema::UsualUnaryConversions(Expr *&E) {
316 // First, convert to an r-value.
317 DefaultFunctionArrayLvalueConversion(E);
318
319 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000320 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000321
322 // Try to perform integral promotions if the object has a theoretically
323 // promotable type.
324 if (Ty->isIntegralOrUnscopedEnumerationType()) {
325 // C99 6.3.1.1p2:
326 //
327 // The following may be used in an expression wherever an int or
328 // unsigned int may be used:
329 // - an object or expression with an integer type whose integer
330 // conversion rank is less than or equal to the rank of int
331 // and unsigned int.
332 // - A bit-field of type _Bool, int, signed int, or unsigned int.
333 //
334 // If an int can represent all values of the original type, the
335 // value is converted to an int; otherwise, it is converted to an
336 // unsigned int. These are called the integer promotions. All
337 // other types are unchanged by the integer promotions.
338
339 QualType PTy = Context.isPromotableBitField(E);
340 if (!PTy.isNull()) {
341 ImpCastExprToType(E, PTy, CK_IntegralCast);
342 return E;
343 }
344 if (Ty->isPromotableIntegerType()) {
345 QualType PT = Context.getPromotedIntegerType(Ty);
346 ImpCastExprToType(E, PT, CK_IntegralCast);
347 return E;
348 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000349 }
350
John McCallf3735e02010-12-01 04:43:34 +0000351 return E;
Chris Lattner513165e2008-07-25 21:10:04 +0000352}
353
Chris Lattner2ce500f2008-07-25 22:25:12 +0000354/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000355/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000356/// double. All other argument types are converted by UsualUnaryConversions().
357void Sema::DefaultArgumentPromotion(Expr *&Expr) {
358 QualType Ty = Expr->getType();
359 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000360
John McCall9bc26772010-12-06 18:36:11 +0000361 UsualUnaryConversions(Expr);
362
Chris Lattner2ce500f2008-07-25 22:25:12 +0000363 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000364 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John McCall9bc26772010-12-06 18:36:11 +0000365 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000366}
367
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000368/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
369/// will warn if the resulting type is not a POD type, and rejects ObjC
370/// interfaces passed by value. This returns true if the argument type is
371/// completely illegal.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000372bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
373 FunctionDecl *FDecl) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000374 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000375
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000376 // __builtin_va_start takes the second argument as a "varargs" argument, but
377 // it doesn't actually do anything with it. It doesn't need to be non-pod
378 // etc.
379 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
380 return false;
381
John McCall8b07ec22010-05-15 11:32:37 +0000382 if (Expr->getType()->isObjCObjectType() &&
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000383 DiagRuntimeBehavior(Expr->getLocStart(),
384 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
385 << Expr->getType() << CT))
386 return true;
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000387
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000388 if (!Expr->getType()->isPODType() &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000389 DiagRuntimeBehavior(Expr->getLocStart(),
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000390 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
391 << Expr->getType() << CT))
392 return true;
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000393
394 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000395}
396
Chris Lattner513165e2008-07-25 21:10:04 +0000397/// UsualArithmeticConversions - Performs various conversions that are common to
398/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000399/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000400/// responsible for emitting appropriate error diagnostics.
401/// FIXME: verify the conversion rules for "complex int" are consistent with
402/// GCC.
403QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
404 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000405 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000406 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000407
408 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000409
Mike Stump11289f42009-09-09 15:08:12 +0000410 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000411 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000412 QualType lhs =
413 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000414 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000415 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000416
417 // If both types are identical, no conversion is needed.
418 if (lhs == rhs)
419 return lhs;
420
421 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
422 // The caller can deal with this (e.g. pointer + int).
423 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
424 return lhs;
425
John McCalld005ac92010-11-13 08:17:45 +0000426 // Apply unary and bitfield promotions to the LHS's type.
427 QualType lhs_unpromoted = lhs;
428 if (lhs->isPromotableIntegerType())
429 lhs = Context.getPromotedIntegerType(lhs);
Eli Friedman629ffb92009-08-20 04:21:42 +0000430 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000431 if (!LHSBitfieldPromoteTy.isNull())
432 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000433 if (lhs != lhs_unpromoted && !isCompAssign)
434 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000435
John McCalld005ac92010-11-13 08:17:45 +0000436 // If both types are identical, no conversion is needed.
437 if (lhs == rhs)
438 return lhs;
439
440 // At this point, we have two different arithmetic types.
441
442 // Handle complex types first (C99 6.3.1.8p1).
443 bool LHSComplexFloat = lhs->isComplexType();
444 bool RHSComplexFloat = rhs->isComplexType();
445 if (LHSComplexFloat || RHSComplexFloat) {
446 // if we have an integer operand, the result is the complex type.
447
John McCallc5e62b42010-11-13 09:02:35 +0000448 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
449 if (rhs->isIntegerType()) {
450 QualType fp = cast<ComplexType>(lhs)->getElementType();
451 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
452 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
453 } else {
454 assert(rhs->isComplexIntegerType());
John McCalld7646252010-11-14 08:17:51 +0000455 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000456 }
John McCalld005ac92010-11-13 08:17:45 +0000457 return lhs;
458 }
459
John McCallc5e62b42010-11-13 09:02:35 +0000460 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
461 if (!isCompAssign) {
462 // int -> float -> _Complex float
463 if (lhs->isIntegerType()) {
464 QualType fp = cast<ComplexType>(rhs)->getElementType();
465 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
466 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
467 } else {
468 assert(lhs->isComplexIntegerType());
John McCalld7646252010-11-14 08:17:51 +0000469 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000470 }
471 }
John McCalld005ac92010-11-13 08:17:45 +0000472 return rhs;
473 }
474
475 // This handles complex/complex, complex/float, or float/complex.
476 // When both operands are complex, the shorter operand is converted to the
477 // type of the longer, and that is the type of the result. This corresponds
478 // to what is done when combining two real floating-point operands.
479 // The fun begins when size promotion occur across type domains.
480 // From H&S 6.3.4: When one operand is complex and the other is a real
481 // floating-point type, the less precise type is converted, within it's
482 // real or complex domain, to the precision of the other type. For example,
483 // when combining a "long double" with a "double _Complex", the
484 // "double _Complex" is promoted to "long double _Complex".
485 int order = Context.getFloatingTypeOrder(lhs, rhs);
486
487 // If both are complex, just cast to the more precise type.
488 if (LHSComplexFloat && RHSComplexFloat) {
489 if (order > 0) {
490 // _Complex float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000491 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000492 return lhs;
493
494 } else if (order < 0) {
495 // _Complex float -> _Complex double
496 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000497 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000498 return rhs;
499 }
500 return lhs;
501 }
502
503 // If just the LHS is complex, the RHS needs to be converted,
504 // and the LHS might need to be promoted.
505 if (LHSComplexFloat) {
506 if (order > 0) { // LHS is wider
507 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000508 QualType fp = cast<ComplexType>(lhs)->getElementType();
509 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
510 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000511 return lhs;
512 }
513
514 // RHS is at least as wide. Find its corresponding complex type.
515 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
516
517 // double -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000518 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000519
520 // _Complex float -> _Complex double
521 if (!isCompAssign && order < 0)
John McCallc5e62b42010-11-13 09:02:35 +0000522 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000523
524 return result;
525 }
526
527 // Just the RHS is complex, so the LHS needs to be converted
528 // and the RHS might need to be promoted.
529 assert(RHSComplexFloat);
530
531 if (order < 0) { // RHS is wider
532 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000533 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000534 QualType fp = cast<ComplexType>(rhs)->getElementType();
535 ImpCastExprToType(lhsExpr, fp, CK_FloatingCast);
John McCallc5e62b42010-11-13 09:02:35 +0000536 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
537 }
John McCalld005ac92010-11-13 08:17:45 +0000538 return rhs;
539 }
540
541 // LHS is at least as wide. Find its corresponding complex type.
542 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
543
544 // double -> _Complex double
545 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000546 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000547
548 // _Complex float -> _Complex double
549 if (order > 0)
John McCallc5e62b42010-11-13 09:02:35 +0000550 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000551
552 return result;
553 }
554
555 // Now handle "real" floating types (i.e. float, double, long double).
556 bool LHSFloat = lhs->isRealFloatingType();
557 bool RHSFloat = rhs->isRealFloatingType();
558 if (LHSFloat || RHSFloat) {
559 // If we have two real floating types, convert the smaller operand
560 // to the bigger result.
561 if (LHSFloat && RHSFloat) {
562 int order = Context.getFloatingTypeOrder(lhs, rhs);
563 if (order > 0) {
564 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
565 return lhs;
566 }
567
568 assert(order < 0 && "illegal float comparison");
569 if (!isCompAssign)
570 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
571 return rhs;
572 }
573
574 // If we have an integer operand, the result is the real floating type.
575 if (LHSFloat) {
576 if (rhs->isIntegerType()) {
577 // Convert rhs to the lhs floating point type.
578 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
579 return lhs;
580 }
581
582 // Convert both sides to the appropriate complex float.
583 assert(rhs->isComplexIntegerType());
584 QualType result = Context.getComplexType(lhs);
585
586 // _Complex int -> _Complex float
John McCalld7646252010-11-14 08:17:51 +0000587 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000588
589 // float -> _Complex float
590 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000591 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000592
593 return result;
594 }
595
596 assert(RHSFloat);
597 if (lhs->isIntegerType()) {
598 // Convert lhs to the rhs floating point type.
599 if (!isCompAssign)
600 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
601 return rhs;
602 }
603
604 // Convert both sides to the appropriate complex float.
605 assert(lhs->isComplexIntegerType());
606 QualType result = Context.getComplexType(rhs);
607
608 // _Complex int -> _Complex float
609 if (!isCompAssign)
John McCalld7646252010-11-14 08:17:51 +0000610 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000611
612 // float -> _Complex float
John McCallc5e62b42010-11-13 09:02:35 +0000613 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000614
615 return result;
616 }
617
618 // Handle GCC complex int extension.
619 // FIXME: if the operands are (int, _Complex long), we currently
620 // don't promote the complex. Also, signedness?
621 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
622 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
623 if (lhsComplexInt && rhsComplexInt) {
624 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
625 rhsComplexInt->getElementType());
626 assert(order && "inequal types with equal element ordering");
627 if (order > 0) {
628 // _Complex int -> _Complex long
John McCallc5e62b42010-11-13 09:02:35 +0000629 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000630 return lhs;
631 }
632
633 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000634 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000635 return rhs;
636 } else if (lhsComplexInt) {
637 // int -> _Complex int
John McCallc5e62b42010-11-13 09:02:35 +0000638 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000639 return lhs;
640 } else if (rhsComplexInt) {
641 // int -> _Complex int
642 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000643 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000644 return rhs;
645 }
646
647 // Finally, we have two differing integer types.
648 // The rules for this case are in C99 6.3.1.8
649 int compare = Context.getIntegerTypeOrder(lhs, rhs);
650 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
651 rhsSigned = rhs->hasSignedIntegerRepresentation();
652 if (lhsSigned == rhsSigned) {
653 // Same signedness; use the higher-ranked type
654 if (compare >= 0) {
655 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
656 return lhs;
657 } else if (!isCompAssign)
658 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
659 return rhs;
660 } else if (compare != (lhsSigned ? 1 : -1)) {
661 // The unsigned type has greater than or equal rank to the
662 // signed type, so use the unsigned type
663 if (rhsSigned) {
664 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
665 return lhs;
666 } else if (!isCompAssign)
667 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
668 return rhs;
669 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
670 // The two types are different widths; if we are here, that
671 // means the signed type is larger than the unsigned type, so
672 // use the signed type.
673 if (lhsSigned) {
674 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
675 return lhs;
676 } else if (!isCompAssign)
677 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
678 return rhs;
679 } else {
680 // The signed type is higher-ranked than the unsigned type,
681 // but isn't actually any bigger (like unsigned int and long
682 // on most 32-bit systems). Use the unsigned type corresponding
683 // to the signed type.
684 QualType result =
685 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
686 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
687 if (!isCompAssign)
688 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
689 return result;
690 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000691}
692
Chris Lattner513165e2008-07-25 21:10:04 +0000693//===----------------------------------------------------------------------===//
694// Semantic Analysis for various Expression Types
695//===----------------------------------------------------------------------===//
696
697
Steve Naroff83895f72007-09-16 03:34:24 +0000698/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000699/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
700/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
701/// multiple tokens. However, the common case is that StringToks points to one
702/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000703///
John McCalldadc5752010-08-24 06:29:42 +0000704ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000705Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000706 assert(NumStringToks && "Must have at least one string!");
707
Chris Lattner8a24e582009-01-16 18:51:42 +0000708 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000709 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000710 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000711
Chris Lattner23b7eb62007-06-15 23:05:46 +0000712 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000713 for (unsigned i = 0; i != NumStringToks; ++i)
714 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000715
Chris Lattner36fc8792008-02-11 00:02:17 +0000716 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000717 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000718 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000719
720 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000721 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000722 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000723
Chris Lattner36fc8792008-02-11 00:02:17 +0000724 // Get an array type for the string, according to C99 6.4.5. This includes
725 // the nul terminator character as well as the string length for pascal
726 // strings.
727 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000728 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000729 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000730
Chris Lattner5b183d82006-11-10 05:03:26 +0000731 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000732 return Owned(StringLiteral::Create(Context, Literal.GetString(),
733 Literal.GetStringLength(),
734 Literal.AnyWide, StrTy,
735 &StringTokLocs[0],
736 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000737}
738
John McCallc63de662011-02-02 13:00:07 +0000739enum CaptureResult {
740 /// No capture is required.
741 CR_NoCapture,
742
743 /// A capture is required.
744 CR_Capture,
745
John McCall351762c2011-02-07 10:33:21 +0000746 /// A by-ref capture is required.
747 CR_CaptureByRef,
748
John McCallc63de662011-02-02 13:00:07 +0000749 /// An error occurred when trying to capture the given variable.
750 CR_Error
751};
752
753/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +0000754///
John McCallc63de662011-02-02 13:00:07 +0000755/// \param var - the variable referenced
756/// \param DC - the context which we couldn't capture through
757static CaptureResult
John McCall351762c2011-02-07 10:33:21 +0000758diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000759 VarDecl *var, DeclContext *DC) {
760 switch (S.ExprEvalContexts.back().Context) {
761 case Sema::Unevaluated:
762 // The argument will never be evaluated, so don't complain.
763 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +0000764
John McCallc63de662011-02-02 13:00:07 +0000765 case Sema::PotentiallyEvaluated:
766 case Sema::PotentiallyEvaluatedIfUsed:
767 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +0000768
John McCallc63de662011-02-02 13:00:07 +0000769 case Sema::PotentiallyPotentiallyEvaluated:
770 // FIXME: delay these!
771 break;
Chris Lattner497d7b02009-04-21 22:26:47 +0000772 }
Mike Stump11289f42009-09-09 15:08:12 +0000773
John McCallc63de662011-02-02 13:00:07 +0000774 // Don't diagnose about capture if we're not actually in code right
775 // now; in general, there are more appropriate places that will
776 // diagnose this.
777 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
778
779 // This particular madness can happen in ill-formed default
780 // arguments; claim it's okay and let downstream code handle it.
781 if (isa<ParmVarDecl>(var) &&
782 S.CurContext == var->getDeclContext()->getParent())
783 return CR_NoCapture;
784
785 DeclarationName functionName;
786 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
787 functionName = fn->getDeclName();
788 // FIXME: variable from enclosing block that we couldn't capture from!
789
790 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
791 << var->getIdentifier() << functionName;
792 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
793 << var->getIdentifier();
794
795 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +0000796}
797
John McCall351762c2011-02-07 10:33:21 +0000798/// There is a well-formed capture at a particular scope level;
799/// propagate it through all the nested blocks.
800static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
801 const BlockDecl::Capture &capture) {
802 VarDecl *var = capture.getVariable();
803
804 // Update all the inner blocks with the capture information.
805 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
806 i != e; ++i) {
807 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
808 innerBlock->Captures.push_back(
809 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
810 /*nested*/ true, capture.getCopyExpr()));
811 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
812 }
813
814 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
815}
816
817/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +0000818/// given value in the current context requires a variable capture.
819///
820/// This also keeps the captures set in the BlockScopeInfo records
821/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +0000822static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000823 ValueDecl *value) {
824 // Only variables ever require capture.
825 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +0000826 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +0000827
828 // Fast path: variables from the current context never require capture.
829 DeclContext *DC = S.CurContext;
830 if (var->getDeclContext() == DC) return CR_NoCapture;
831
832 // Only variables with local storage require capture.
833 // FIXME: What about 'const' variables in C++?
834 if (!var->hasLocalStorage()) return CR_NoCapture;
835
836 // Otherwise, we need to capture.
837
838 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +0000839 do {
840 // Only blocks (and eventually C++0x closures) can capture; other
841 // scopes don't work.
842 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +0000843 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +0000844
845 BlockScopeInfo *blockScope =
846 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
847 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
848
John McCall351762c2011-02-07 10:33:21 +0000849 // Check whether we've already captured it in this block. If so,
850 // we're done.
851 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
852 return propagateCapture(S, functionScopesIndex,
853 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +0000854
855 functionScopesIndex--;
856 DC = cast<BlockDecl>(DC)->getDeclContext();
857 } while (var->getDeclContext() != DC);
858
John McCall351762c2011-02-07 10:33:21 +0000859 // Okay, we descended all the way to the block that defines the variable.
860 // Actually try to capture it.
861 QualType type = var->getType();
862
863 // Prohibit variably-modified types.
864 if (type->isVariablyModifiedType()) {
865 S.Diag(loc, diag::err_ref_vm_type);
866 S.Diag(var->getLocation(), diag::note_declared_at);
867 return CR_Error;
868 }
869
870 // Prohibit arrays, even in __block variables, but not references to
871 // them.
872 if (type->isArrayType()) {
873 S.Diag(loc, diag::err_ref_array_type);
874 S.Diag(var->getLocation(), diag::note_declared_at);
875 return CR_Error;
876 }
877
878 S.MarkDeclarationReferenced(loc, var);
879
880 // The BlocksAttr indicates the variable is bound by-reference.
881 bool byRef = var->hasAttr<BlocksAttr>();
882
883 // Build a copy expression.
884 Expr *copyExpr = 0;
885 if (!byRef && S.getLangOptions().CPlusPlus &&
886 !type->isDependentType() && type->isStructureOrClassType()) {
887 // According to the blocks spec, the capture of a variable from
888 // the stack requires a const copy constructor. This is not true
889 // of the copy/move done to move a __block variable to the heap.
890 type.addConst();
891
892 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
893 ExprResult result =
894 S.PerformCopyInitialization(
895 InitializedEntity::InitializeBlock(var->getLocation(),
896 type, false),
897 loc, S.Owned(declRef));
898
899 // Build a full-expression copy expression if initialization
900 // succeeded and used a non-trivial constructor. Recover from
901 // errors by pretending that the copy isn't necessary.
902 if (!result.isInvalid() &&
903 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
904 result = S.MaybeCreateExprWithCleanups(result);
905 copyExpr = result.take();
906 }
907 }
908
909 // We're currently at the declarer; go back to the closure.
910 functionScopesIndex++;
911 BlockScopeInfo *blockScope =
912 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
913
914 // Build a valid capture in this scope.
915 blockScope->Captures.push_back(
916 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
917 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
918
919 // Propagate that to inner captures if necessary.
920 return propagateCapture(S, functionScopesIndex,
921 blockScope->Captures.back());
922}
923
924static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
925 const DeclarationNameInfo &NameInfo,
926 bool byRef) {
927 assert(isa<VarDecl>(vd) && "capturing non-variable");
928
929 VarDecl *var = cast<VarDecl>(vd);
930 assert(var->hasLocalStorage() && "capturing non-local");
931 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
932
933 QualType exprType = var->getType().getNonReferenceType();
934
935 BlockDeclRefExpr *BDRE;
936 if (!byRef) {
937 // The variable will be bound by copy; make it const within the
938 // closure, but record that this was done in the expression.
939 bool constAdded = !exprType.isConstQualified();
940 exprType.addConst();
941
942 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
943 NameInfo.getLoc(), false,
944 constAdded);
945 } else {
946 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
947 NameInfo.getLoc(), true);
948 }
949
950 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +0000951}
Chris Lattner2a9d9892008-10-20 05:16:36 +0000952
John McCalldadc5752010-08-24 06:29:42 +0000953ExprResult
John McCall7decc9e2010-11-18 06:31:45 +0000954Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +0000955 SourceLocation Loc,
956 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000957 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +0000958 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000959}
960
John McCallf4cd4f92011-02-09 01:13:10 +0000961/// BuildDeclRefExpr - Build an expression that references a
962/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +0000963ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +0000964Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000965 const DeclarationNameInfo &NameInfo,
966 const CXXScopeSpec *SS) {
John McCallf4cd4f92011-02-09 01:13:10 +0000967 if (Ty == Context.UndeducedAutoTy) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000968 Diag(NameInfo.getLoc(),
Mike Stump11289f42009-09-09 15:08:12 +0000969 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000970 << D->getDeclName();
971 return ExprError();
972 }
Mike Stump11289f42009-09-09 15:08:12 +0000973
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);
1353 CXXDependentScopeMemberExpr *DepExpr =
1354 CXXDependentScopeMemberExpr::Create(
1355 Context, DepThis, DepThisType, true, SourceLocation(),
1356 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
1357 R.getLookupNameInfo(), &TList);
1358 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001359 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001360 // FIXME: we should be able to handle this case too. It is correct
1361 // to add this-> here. This is a workaround for PR7947.
1362 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001363 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001364 } else {
John McCalld681c392009-12-16 08:11:27 +00001365 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001366 }
John McCalld681c392009-12-16 08:11:27 +00001367
1368 // Do we really want to note all of these?
1369 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1370 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1371
1372 // Tell the callee to try to recover.
1373 return false;
1374 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001375
1376 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001377 }
1378 }
1379
Douglas Gregor598b08f2009-12-31 05:20:13 +00001380 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001381 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001382 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001383 if (!R.empty()) {
1384 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1385 if (SS.isEmpty())
1386 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1387 << FixItHint::CreateReplacement(R.getNameLoc(),
1388 R.getLookupName().getAsString());
1389 else
1390 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1391 << Name << computeDeclContext(SS, false) << R.getLookupName()
1392 << SS.getRange()
1393 << FixItHint::CreateReplacement(R.getNameLoc(),
1394 R.getLookupName().getAsString());
1395 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1396 Diag(ND->getLocation(), diag::note_previous_decl)
1397 << ND->getDeclName();
1398
1399 // Tell the callee to try to recover.
1400 return false;
1401 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001402
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001403 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1404 // FIXME: If we ended up with a typo for a type name or
1405 // Objective-C class name, we're in trouble because the parser
1406 // is in the wrong place to recover. Suggest the typo
1407 // correction, but don't make it a fix-it since we're not going
1408 // to recover well anyway.
1409 if (SS.isEmpty())
1410 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1411 else
1412 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1413 << Name << computeDeclContext(SS, false) << R.getLookupName()
1414 << SS.getRange();
1415
1416 // Don't try to recover; it won't work.
1417 return true;
1418 }
1419 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001420 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001421 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001422 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001423 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001424 else
Douglas Gregor25363982010-01-01 00:15:04 +00001425 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001426 << Name << computeDeclContext(SS, false) << Corrected
1427 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001428 return true;
1429 }
Douglas Gregor25363982010-01-01 00:15:04 +00001430 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001431 }
1432
1433 // Emit a special diagnostic for failed member lookups.
1434 // FIXME: computing the declaration context might fail here (?)
1435 if (!SS.isEmpty()) {
1436 Diag(R.getNameLoc(), diag::err_no_member)
1437 << Name << computeDeclContext(SS, false)
1438 << SS.getRange();
1439 return true;
1440 }
1441
John McCalld681c392009-12-16 08:11:27 +00001442 // Give up, we can't recover.
1443 Diag(R.getNameLoc(), diagnostic) << Name;
1444 return true;
1445}
1446
Douglas Gregor05fcf842010-11-02 20:36:02 +00001447ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1448 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001449 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1450 if (!IDecl)
1451 return 0;
1452 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1453 if (!ClassImpDecl)
1454 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001455 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001456 if (!property)
1457 return 0;
1458 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001459 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1460 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001461 return 0;
1462 return property;
1463}
1464
Douglas Gregor05fcf842010-11-02 20:36:02 +00001465bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1466 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1467 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1468 if (!IDecl)
1469 return false;
1470 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1471 if (!ClassImpDecl)
1472 return false;
1473 if (ObjCPropertyImplDecl *PIDecl
1474 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1475 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1476 PIDecl->getPropertyIvarDecl())
1477 return false;
1478
1479 return true;
1480}
1481
Fariborz Jahanian18722982010-07-17 00:59:30 +00001482static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001483 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001484 IdentifierInfo *II,
1485 SourceLocation NameLoc) {
1486 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001487 bool LookForIvars;
1488 if (Lookup.empty())
1489 LookForIvars = true;
1490 else if (CurMeth->isClassMethod())
1491 LookForIvars = false;
1492 else
1493 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001494 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1495 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001496 if (!LookForIvars)
1497 return 0;
1498
Fariborz Jahanian18722982010-07-17 00:59:30 +00001499 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1500 if (!IDecl)
1501 return 0;
1502 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001503 if (!ClassImpDecl)
1504 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001505 bool DynamicImplSeen = false;
1506 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1507 if (!property)
1508 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001509 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001510 DynamicImplSeen =
1511 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001512 // property implementation has a designated ivar. No need to assume a new
1513 // one.
1514 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1515 return 0;
1516 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001517 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001518 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1519 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001520 NameLoc,
1521 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001522 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001523 (Expr *)0, true);
1524 ClassImpDecl->addDecl(Ivar);
1525 IDecl->makeDeclVisibleInContext(Ivar, false);
1526 property->setPropertyIvarDecl(Ivar);
1527 return Ivar;
1528 }
1529 return 0;
1530}
1531
John McCalldadc5752010-08-24 06:29:42 +00001532ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001533 CXXScopeSpec &SS,
1534 UnqualifiedId &Id,
1535 bool HasTrailingLParen,
1536 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001537 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1538 "cannot be direct & operand and have a trailing lparen");
1539
1540 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001541 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001542
John McCall10eae182009-11-30 22:42:35 +00001543 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001544
1545 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001546 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001547 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001548 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001549
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001550 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001551 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001552 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001553
John McCalle66edc12009-11-24 19:00:30 +00001554 // C++ [temp.dep.expr]p3:
1555 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001556 // -- an identifier that was declared with a dependent type,
1557 // (note: handled after lookup)
1558 // -- a template-id that is dependent,
1559 // (note: handled in BuildTemplateIdExpr)
1560 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001561 // -- a nested-name-specifier that contains a class-name that
1562 // names a dependent type.
1563 // Determine whether this is a member of an unknown specialization;
1564 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001565 bool DependentID = false;
1566 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1567 Name.getCXXNameType()->isDependentType()) {
1568 DependentID = true;
1569 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001570 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001571 if (RequireCompleteDeclContext(SS, DC))
1572 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001573 } else {
1574 DependentID = true;
1575 }
1576 }
1577
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001578 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001579 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001580 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001581
Fariborz Jahanian86151342010-07-22 23:33:21 +00001582 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001583 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001584 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001585 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001586 // Lookup the template name again to correctly establish the context in
1587 // which it was found. This is really unfortunate as we already did the
1588 // lookup to determine that it was a template name in the first place. If
1589 // this becomes a performance hit, we can work harder to preserve those
1590 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001591 bool MemberOfUnknownSpecialization;
1592 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1593 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001594
1595 if (MemberOfUnknownSpecialization ||
1596 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1597 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1598 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001599 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001600 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001601 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001602
Douglas Gregora5226932011-02-04 13:35:07 +00001603 // If the result might be in a dependent base class, this is a dependent
1604 // id-expression.
1605 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1606 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1607 TemplateArgs);
1608
John McCalle66edc12009-11-24 19:00:30 +00001609 // If this reference is in an Objective-C method, then we need to do
1610 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001611 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001612 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001613 if (E.isInvalid())
1614 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001615
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001616 if (Expr *Ex = E.takeAs<Expr>())
1617 return Owned(Ex);
1618
1619 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001620 if (getLangOptions().ObjCDefaultSynthProperties &&
1621 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001622 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1623 if (const ObjCPropertyDecl *Property =
1624 canSynthesizeProvisionalIvar(II)) {
1625 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1626 Diag(Property->getLocation(), diag::note_property_declare);
1627 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001628 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1629 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001630 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001631 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001632 // for further use, this must be set to false if in class method.
1633 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001634 }
Chris Lattner59a25942008-03-31 00:36:02 +00001635 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001636
John McCalle66edc12009-11-24 19:00:30 +00001637 if (R.isAmbiguous())
1638 return ExprError();
1639
Douglas Gregor171c45a2009-02-18 21:56:37 +00001640 // Determine whether this name might be a candidate for
1641 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001642 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001643
John McCalle66edc12009-11-24 19:00:30 +00001644 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001645 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001646 // in C90, extension in C99, forbidden in C++).
1647 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1648 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1649 if (D) R.addDecl(D);
1650 }
1651
1652 // If this name wasn't predeclared and if this is not a function
1653 // call, diagnose the problem.
1654 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001655 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001656 return ExprError();
1657
1658 assert(!R.empty() &&
1659 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001660
1661 // If we found an Objective-C instance variable, let
1662 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001663 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001664 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1665 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001666 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001667 assert(E.isInvalid() || E.get());
1668 return move(E);
1669 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001670 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001671 }
Mike Stump11289f42009-09-09 15:08:12 +00001672
John McCalle66edc12009-11-24 19:00:30 +00001673 // This is guaranteed from this point on.
1674 assert(!R.empty() || ADL);
1675
1676 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001677 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001678 !(getLangOptions().ObjCDefaultSynthProperties &&
1679 getLangOptions().ObjCNonFragileABI2) &&
Fariborz Jahanianc15dfd82010-07-29 16:53:53 +00001680 Var->isFileVarDecl()) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001681 ObjCPropertyDecl *Property = canSynthesizeProvisionalIvar(II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001682 if (Property) {
1683 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1684 Diag(Property->getLocation(), diag::note_property_declare);
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001685 Diag(Var->getLocation(), diag::note_global_declared_at);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001686 }
1687 }
Douglas Gregor3256d042009-06-30 15:47:41 +00001688 }
Mike Stump11289f42009-09-09 15:08:12 +00001689
John McCall2d74de92009-12-01 22:10:20 +00001690 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001691 // C++ [class.mfct.non-static]p3:
1692 // When an id-expression that is not part of a class member access
1693 // syntax and not used to form a pointer to member is used in the
1694 // body of a non-static member function of class X, if name lookup
1695 // resolves the name in the id-expression to a non-static non-type
1696 // member of some class C, the id-expression is transformed into a
1697 // class member access expression using (*this) as the
1698 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001699 //
1700 // But we don't actually need to do this for '&' operands if R
1701 // resolved to a function or overloaded function set, because the
1702 // expression is ill-formed if it actually works out to be a
1703 // non-static member function:
1704 //
1705 // C++ [expr.ref]p4:
1706 // Otherwise, if E1.E2 refers to a non-static member function. . .
1707 // [t]he expression can be used only as the left-hand operand of a
1708 // member function call.
1709 //
1710 // There are other safeguards against such uses, but it's important
1711 // to get this right here so that we don't end up making a
1712 // spuriously dependent expression if we're inside a dependent
1713 // instance method.
John McCall57500772009-12-16 12:17:52 +00001714 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001715 bool MightBeImplicitMember;
1716 if (!isAddressOfOperand)
1717 MightBeImplicitMember = true;
1718 else if (!SS.isEmpty())
1719 MightBeImplicitMember = false;
1720 else if (R.isOverloadedResult())
1721 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001722 else if (R.isUnresolvableResult())
1723 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001724 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001725 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1726 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001727
1728 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001729 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001730 }
1731
John McCalle66edc12009-11-24 19:00:30 +00001732 if (TemplateArgs)
1733 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001734
John McCalle66edc12009-11-24 19:00:30 +00001735 return BuildDeclarationNameExpr(SS, R, ADL);
1736}
1737
John McCall57500772009-12-16 12:17:52 +00001738/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001739ExprResult
John McCall57500772009-12-16 12:17:52 +00001740Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1741 LookupResult &R,
1742 const TemplateArgumentListInfo *TemplateArgs) {
1743 switch (ClassifyImplicitMemberAccess(*this, R)) {
1744 case IMA_Instance:
1745 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1746
John McCall57500772009-12-16 12:17:52 +00001747 case IMA_Mixed:
1748 case IMA_Mixed_Unrelated:
1749 case IMA_Unresolved:
1750 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1751
1752 case IMA_Static:
1753 case IMA_Mixed_StaticContext:
1754 case IMA_Unresolved_StaticContext:
1755 if (TemplateArgs)
1756 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1757 return BuildDeclarationNameExpr(SS, R, false);
1758
1759 case IMA_Error_StaticContext:
1760 case IMA_Error_Unrelated:
John McCallf3a88602011-02-03 08:15:49 +00001761 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1762 R.getLookupNameInfo());
John McCall57500772009-12-16 12:17:52 +00001763 return ExprError();
1764 }
1765
1766 llvm_unreachable("unexpected instance member access kind");
1767 return ExprError();
1768}
1769
John McCall10eae182009-11-30 22:42:35 +00001770/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1771/// declaration name, generally during template instantiation.
1772/// There's a large number of things which don't need to be done along
1773/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001774ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001775Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001776 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001777 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001778 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001779 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001780
John McCall0b66eb32010-05-01 00:40:08 +00001781 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001782 return ExprError();
1783
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001784 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001785 LookupQualifiedName(R, DC);
1786
1787 if (R.isAmbiguous())
1788 return ExprError();
1789
1790 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001791 Diag(NameInfo.getLoc(), diag::err_no_member)
1792 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001793 return ExprError();
1794 }
1795
1796 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1797}
1798
1799/// LookupInObjCMethod - The parser has read a name in, and Sema has
1800/// detected that we're currently inside an ObjC method. Perform some
1801/// additional lookup.
1802///
1803/// Ideally, most of this would be done by lookup, but there's
1804/// actually quite a lot of extra work involved.
1805///
1806/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001807ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001808Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001809 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001810 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001811 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001812
John McCalle66edc12009-11-24 19:00:30 +00001813 // There are two cases to handle here. 1) scoped lookup could have failed,
1814 // in which case we should look for an ivar. 2) scoped lookup could have
1815 // found a decl, but that decl is outside the current instance method (i.e.
1816 // a global variable). In these two cases, we do a lookup for an ivar with
1817 // this name, if the lookup sucedes, we replace it our current decl.
1818
1819 // If we're in a class method, we don't normally want to look for
1820 // ivars. But if we don't find anything else, and there's an
1821 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001822 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001823
1824 bool LookForIvars;
1825 if (Lookup.empty())
1826 LookForIvars = true;
1827 else if (IsClassMethod)
1828 LookForIvars = false;
1829 else
1830 LookForIvars = (Lookup.isSingleResult() &&
1831 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001832 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001833 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001834 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001835 ObjCInterfaceDecl *ClassDeclared;
1836 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1837 // Diagnose using an ivar in a class method.
1838 if (IsClassMethod)
1839 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1840 << IV->getDeclName());
1841
1842 // If we're referencing an invalid decl, just return this as a silent
1843 // error node. The error diagnostic was already emitted on the decl.
1844 if (IV->isInvalidDecl())
1845 return ExprError();
1846
1847 // Check if referencing a field with __attribute__((deprecated)).
1848 if (DiagnoseUseOfDecl(IV, Loc))
1849 return ExprError();
1850
1851 // Diagnose the use of an ivar outside of the declaring class.
1852 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1853 ClassDeclared != IFace)
1854 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1855
1856 // FIXME: This should use a new expr for a direct reference, don't
1857 // turn this into Self->ivar, just return a BareIVarExpr or something.
1858 IdentifierInfo &II = Context.Idents.get("self");
1859 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001860 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001861 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001862 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001863 SelfName, false, false);
1864 if (SelfExpr.isInvalid())
1865 return ExprError();
1866
John McCall27584242010-12-06 20:48:59 +00001867 Expr *SelfE = SelfExpr.take();
1868 DefaultLvalueConversion(SelfE);
1869
John McCalle66edc12009-11-24 19:00:30 +00001870 MarkDeclarationReferenced(Loc, IV);
1871 return Owned(new (Context)
1872 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall27584242010-12-06 20:48:59 +00001873 SelfE, true, true));
John McCalle66edc12009-11-24 19:00:30 +00001874 }
Chris Lattner87313662010-04-12 05:10:17 +00001875 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001876 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001877 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001878 ObjCInterfaceDecl *ClassDeclared;
1879 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1880 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1881 IFace == ClassDeclared)
1882 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1883 }
1884 }
1885
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001886 if (Lookup.empty() && II && AllowBuiltinCreation) {
1887 // FIXME. Consolidate this with similar code in LookupName.
1888 if (unsigned BuiltinID = II->getBuiltinID()) {
1889 if (!(getLangOptions().CPlusPlus &&
1890 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1891 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1892 S, Lookup.isForRedeclaration(),
1893 Lookup.getNameLoc());
1894 if (D) Lookup.addDecl(D);
1895 }
1896 }
1897 }
John McCalle66edc12009-11-24 19:00:30 +00001898 // Sentinel value saying that we didn't do anything special.
1899 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001900}
John McCalld14a8642009-11-21 08:51:07 +00001901
John McCall16df1e52010-03-30 21:47:33 +00001902/// \brief Cast a base object to a member's actual type.
1903///
1904/// Logically this happens in three phases:
1905///
1906/// * First we cast from the base type to the naming class.
1907/// The naming class is the class into which we were looking
1908/// when we found the member; it's the qualifier type if a
1909/// qualifier was provided, and otherwise it's the base type.
1910///
1911/// * Next we cast from the naming class to the declaring class.
1912/// If the member we found was brought into a class's scope by
1913/// a using declaration, this is that class; otherwise it's
1914/// the class declaring the member.
1915///
1916/// * Finally we cast from the declaring class to the "true"
1917/// declaring class of the member. This conversion does not
1918/// obey access control.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001919bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001920Sema::PerformObjectMemberConversion(Expr *&From,
1921 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001922 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001923 NamedDecl *Member) {
1924 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1925 if (!RD)
1926 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001927
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001928 QualType DestRecordType;
1929 QualType DestType;
1930 QualType FromRecordType;
1931 QualType FromType = From->getType();
1932 bool PointerConversions = false;
1933 if (isa<FieldDecl>(Member)) {
1934 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001935
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001936 if (FromType->getAs<PointerType>()) {
1937 DestType = Context.getPointerType(DestRecordType);
1938 FromRecordType = FromType->getPointeeType();
1939 PointerConversions = true;
1940 } else {
1941 DestType = DestRecordType;
1942 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001943 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001944 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1945 if (Method->isStatic())
1946 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001947
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001948 DestType = Method->getThisType(Context);
1949 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001950
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001951 if (FromType->getAs<PointerType>()) {
1952 FromRecordType = FromType->getPointeeType();
1953 PointerConversions = true;
1954 } else {
1955 FromRecordType = FromType;
1956 DestType = DestRecordType;
1957 }
1958 } else {
1959 // No conversion necessary.
1960 return false;
1961 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001962
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001963 if (DestType->isDependentType() || FromType->isDependentType())
1964 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001965
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001966 // If the unqualified types are the same, no conversion is necessary.
1967 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1968 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001969
John McCall16df1e52010-03-30 21:47:33 +00001970 SourceRange FromRange = From->getSourceRange();
1971 SourceLocation FromLoc = FromRange.getBegin();
1972
John McCall2536c6d2010-08-25 10:28:54 +00001973 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001974
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001975 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001976 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001977 // class name.
1978 //
1979 // If the member was a qualified name and the qualified referred to a
1980 // specific base subobject type, we'll cast to that intermediate type
1981 // first and then to the object in which the member is declared. That allows
1982 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1983 //
1984 // class Base { public: int x; };
1985 // class Derived1 : public Base { };
1986 // class Derived2 : public Base { };
1987 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1988 //
1989 // void VeryDerived::f() {
1990 // x = 17; // error: ambiguous base subobjects
1991 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1992 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001993 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001994 QualType QType = QualType(Qualifier->getAsType(), 0);
1995 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1996 assert(QType->isRecordType() && "lookup done with non-record type");
1997
1998 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1999
2000 // In C++98, the qualifier type doesn't actually have to be a base
2001 // type of the object type, in which case we just ignore it.
2002 // Otherwise build the appropriate casts.
2003 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002004 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002005 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002006 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00002007 return true;
2008
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002009 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002010 QType = Context.getPointerType(QType);
John McCall2536c6d2010-08-25 10:28:54 +00002011 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2012 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00002013
2014 FromType = QType;
2015 FromRecordType = QRecordType;
2016
2017 // If the qualifier type was the same as the destination type,
2018 // we're done.
2019 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2020 return false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002021 }
2022 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002023
John McCall16df1e52010-03-30 21:47:33 +00002024 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002025
John McCall16df1e52010-03-30 21:47:33 +00002026 // If we actually found the member through a using declaration, cast
2027 // down to the using declaration's type.
2028 //
2029 // Pointer equality is fine here because only one declaration of a
2030 // class ever has member declarations.
2031 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2032 assert(isa<UsingShadowDecl>(FoundDecl));
2033 QualType URecordType = Context.getTypeDeclType(
2034 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2035
2036 // We only need to do this if the naming-class to declaring-class
2037 // conversion is non-trivial.
2038 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2039 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002040 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002041 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002042 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00002043 return true;
Alexis Huntc46382e2010-04-28 23:02:27 +00002044
John McCall16df1e52010-03-30 21:47:33 +00002045 QualType UType = URecordType;
2046 if (PointerConversions)
2047 UType = Context.getPointerType(UType);
John McCalle3027922010-08-25 11:45:40 +00002048 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00002049 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00002050 FromType = UType;
2051 FromRecordType = URecordType;
2052 }
2053
2054 // We don't do access control for the conversion from the
2055 // declaring class to the true declaring class.
2056 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002057 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002058
John McCallcf142162010-08-07 06:22:56 +00002059 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002060 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2061 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002062 IgnoreAccess))
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002063 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002064
John McCalle3027922010-08-25 11:45:40 +00002065 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00002066 VK, &BasePath);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00002067 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002068}
Douglas Gregor3256d042009-06-30 15:47:41 +00002069
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002070/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00002071static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00002072 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00002073 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002074 const DeclarationNameInfo &MemberNameInfo,
2075 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00002076 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00002077 const TemplateArgumentListInfo *TemplateArgs = 0) {
2078 NestedNameSpecifier *Qualifier = 0;
2079 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00002080 if (SS.isSet()) {
2081 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
2082 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002083 }
Mike Stump11289f42009-09-09 15:08:12 +00002084
John McCalle66edc12009-11-24 19:00:30 +00002085 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002086 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002087 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00002088}
2089
John McCallfeb624a2010-11-23 20:48:44 +00002090static ExprResult
2091BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2092 const CXXScopeSpec &SS, FieldDecl *Field,
2093 DeclAccessPair FoundDecl,
2094 const DeclarationNameInfo &MemberNameInfo) {
2095 // x.a is an l-value if 'a' has a reference type. Otherwise:
2096 // x.a is an l-value/x-value/pr-value if the base is (and note
2097 // that *x is always an l-value), except that if the base isn't
2098 // an ordinary object then we must have an rvalue.
2099 ExprValueKind VK = VK_LValue;
2100 ExprObjectKind OK = OK_Ordinary;
2101 if (!IsArrow) {
2102 if (BaseExpr->getObjectKind() == OK_Ordinary)
2103 VK = BaseExpr->getValueKind();
2104 else
2105 VK = VK_RValue;
2106 }
2107 if (VK != VK_RValue && Field->isBitField())
2108 OK = OK_BitField;
2109
2110 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2111 QualType MemberType = Field->getType();
2112 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2113 MemberType = Ref->getPointeeType();
2114 VK = VK_LValue;
2115 } else {
2116 QualType BaseType = BaseExpr->getType();
2117 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2118
2119 Qualifiers BaseQuals = BaseType.getQualifiers();
2120
2121 // GC attributes are never picked up by members.
2122 BaseQuals.removeObjCGCAttr();
2123
2124 // CVR attributes from the base are picked up by members,
2125 // except that 'mutable' members don't pick up 'const'.
2126 if (Field->isMutable()) BaseQuals.removeConst();
2127
2128 Qualifiers MemberQuals
2129 = S.Context.getCanonicalType(MemberType).getQualifiers();
2130
2131 // TR 18037 does not allow fields to be declared with address spaces.
2132 assert(!MemberQuals.hasAddressSpace());
2133
2134 Qualifiers Combined = BaseQuals + MemberQuals;
2135 if (Combined != MemberQuals)
2136 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2137 }
2138
2139 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2140 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2141 FoundDecl, Field))
2142 return ExprError();
2143 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2144 Field, FoundDecl, MemberNameInfo,
2145 MemberType, VK, OK));
2146}
2147
John McCall2d74de92009-12-01 22:10:20 +00002148/// Builds an implicit member access expression. The current context
2149/// is known to be an instance method, and the given unqualified lookup
2150/// set is known to contain only instance members, at least one of which
2151/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002152ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002153Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2154 LookupResult &R,
2155 const TemplateArgumentListInfo *TemplateArgs,
2156 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002157 assert(!R.empty() && !R.isAmbiguous());
2158
John McCallf3a88602011-02-03 08:15:49 +00002159 SourceLocation loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002160
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002161 // We may have found a field within an anonymous union or struct
2162 // (C++ [class.union]).
John McCalle66edc12009-11-24 19:00:30 +00002163 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002164 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCallf3a88602011-02-03 08:15:49 +00002165 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002166
John McCallf3a88602011-02-03 08:15:49 +00002167 // If this is known to be an instance access, go ahead and build an
2168 // implicit 'this' expression now.
John McCall2d74de92009-12-01 22:10:20 +00002169 // 'this' expression now.
John McCallf3a88602011-02-03 08:15:49 +00002170 CXXMethodDecl *method = tryCaptureCXXThis();
2171 assert(method && "didn't correctly pre-flight capture of 'this'");
2172
2173 QualType thisType = method->getThisType(Context);
2174 Expr *baseExpr = 0; // null signifies implicit access
John McCall2d74de92009-12-01 22:10:20 +00002175 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002176 SourceLocation Loc = R.getNameLoc();
2177 if (SS.getRange().isValid())
2178 Loc = SS.getRange().getBegin();
John McCallf3a88602011-02-03 08:15:49 +00002179 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002180 }
2181
John McCallf3a88602011-02-03 08:15:49 +00002182 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCall2d74de92009-12-01 22:10:20 +00002183 /*OpLoc*/ SourceLocation(),
2184 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002185 SS,
2186 /*FirstQualifierInScope*/ 0,
2187 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002188}
2189
John McCalle66edc12009-11-24 19:00:30 +00002190bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002191 const LookupResult &R,
2192 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002193 // Only when used directly as the postfix-expression of a call.
2194 if (!HasTrailingLParen)
2195 return false;
2196
2197 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002198 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002199 return false;
2200
2201 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002202 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002203 return false;
2204
2205 // Turn off ADL when we find certain kinds of declarations during
2206 // normal lookup:
2207 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2208 NamedDecl *D = *I;
2209
2210 // C++0x [basic.lookup.argdep]p3:
2211 // -- a declaration of a class member
2212 // Since using decls preserve this property, we check this on the
2213 // original decl.
John McCall57500772009-12-16 12:17:52 +00002214 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002215 return false;
2216
2217 // C++0x [basic.lookup.argdep]p3:
2218 // -- a block-scope function declaration that is not a
2219 // using-declaration
2220 // NOTE: we also trigger this for function templates (in fact, we
2221 // don't check the decl type at all, since all other decl types
2222 // turn off ADL anyway).
2223 if (isa<UsingShadowDecl>(D))
2224 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2225 else if (D->getDeclContext()->isFunctionOrMethod())
2226 return false;
2227
2228 // C++0x [basic.lookup.argdep]p3:
2229 // -- a declaration that is neither a function or a function
2230 // template
2231 // And also for builtin functions.
2232 if (isa<FunctionDecl>(D)) {
2233 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2234
2235 // But also builtin functions.
2236 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2237 return false;
2238 } else if (!isa<FunctionTemplateDecl>(D))
2239 return false;
2240 }
2241
2242 return true;
2243}
2244
2245
John McCalld14a8642009-11-21 08:51:07 +00002246/// Diagnoses obvious problems with the use of the given declaration
2247/// as an expression. This is only actually called for lookups that
2248/// were not overloaded, and it doesn't promise that the declaration
2249/// will in fact be used.
2250static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2251 if (isa<TypedefDecl>(D)) {
2252 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2253 return true;
2254 }
2255
2256 if (isa<ObjCInterfaceDecl>(D)) {
2257 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2258 return true;
2259 }
2260
2261 if (isa<NamespaceDecl>(D)) {
2262 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2263 return true;
2264 }
2265
2266 return false;
2267}
2268
John McCalldadc5752010-08-24 06:29:42 +00002269ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002270Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002271 LookupResult &R,
2272 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002273 // If this is a single, fully-resolved result and we don't need ADL,
2274 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002275 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002276 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2277 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002278
2279 // We only need to check the declaration if there's exactly one
2280 // result, because in the overloaded case the results can only be
2281 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002282 if (R.isSingleResult() &&
2283 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002284 return ExprError();
2285
John McCall58cc69d2010-01-27 01:50:18 +00002286 // Otherwise, just build an unresolved lookup expression. Suppress
2287 // any lookup-related diagnostics; we'll hash these out later, when
2288 // we've picked a target.
2289 R.suppressDiagnostics();
2290
John McCalld14a8642009-11-21 08:51:07 +00002291 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002292 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00002293 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002294 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002295 NeedsADL, R.isOverloadedResult(),
2296 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002297
2298 return Owned(ULE);
2299}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002300
John McCalld14a8642009-11-21 08:51:07 +00002301/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002302ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002303Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002304 const DeclarationNameInfo &NameInfo,
2305 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002306 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002307 assert(!isa<FunctionTemplateDecl>(D) &&
2308 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002309
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002310 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002311 if (CheckDeclInExpr(*this, Loc, D))
2312 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002313
Douglas Gregore7488b92009-12-01 16:58:18 +00002314 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2315 // Specifically diagnose references to class templates that are missing
2316 // a template argument list.
2317 Diag(Loc, diag::err_template_decl_ref)
2318 << Template << SS.getRange();
2319 Diag(Template->getLocation(), diag::note_template_decl_here);
2320 return ExprError();
2321 }
2322
2323 // Make sure that we're referring to a value.
2324 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2325 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002326 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002327 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002328 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002329 return ExprError();
2330 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002331
Douglas Gregor171c45a2009-02-18 21:56:37 +00002332 // Check whether this declaration can be used. Note that we suppress
2333 // this check when we're going to perform argument-dependent lookup
2334 // on this function name, because this might not be the function
2335 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002336 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002337 return ExprError();
2338
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002339 // Only create DeclRefExpr's for valid Decl's.
2340 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002341 return ExprError();
2342
John McCallf3a88602011-02-03 08:15:49 +00002343 // Handle members of anonymous structs and unions. If we got here,
2344 // and the reference is to a class member indirect field, then this
2345 // must be the subject of a pointer-to-member expression.
2346 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2347 if (!indirectField->isCXXClassMember())
2348 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2349 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002350
Chris Lattner2a9d9892008-10-20 05:16:36 +00002351 // If the identifier reference is inside a block, and it refers to a value
2352 // that is outside the block, create a BlockDeclRefExpr instead of a
2353 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2354 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002355 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002356 // We do not do this for things like enum constants, global variables, etc,
2357 // as they do not get snapshotted.
2358 //
John McCall351762c2011-02-07 10:33:21 +00002359 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002360 case CR_Error:
2361 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002362
John McCallc63de662011-02-02 13:00:07 +00002363 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002364 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2365 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2366
2367 case CR_CaptureByRef:
2368 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2369 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002370
2371 case CR_NoCapture: {
2372 // If this reference is not in a block or if the referenced
2373 // variable is within the block, create a normal DeclRefExpr.
2374
2375 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002376 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002377
2378 switch (D->getKind()) {
2379 // Ignore all the non-ValueDecl kinds.
2380#define ABSTRACT_DECL(kind)
2381#define VALUE(type, base)
2382#define DECL(type, base) \
2383 case Decl::type:
2384#include "clang/AST/DeclNodes.inc"
2385 llvm_unreachable("invalid value decl kind");
2386 return ExprError();
2387
2388 // These shouldn't make it here.
2389 case Decl::ObjCAtDefsField:
2390 case Decl::ObjCIvar:
2391 llvm_unreachable("forming non-member reference to ivar?");
2392 return ExprError();
2393
2394 // Enum constants are always r-values and never references.
2395 // Unresolved using declarations are dependent.
2396 case Decl::EnumConstant:
2397 case Decl::UnresolvedUsingValue:
2398 valueKind = VK_RValue;
2399 break;
2400
2401 // Fields and indirect fields that got here must be for
2402 // pointer-to-member expressions; we just call them l-values for
2403 // internal consistency, because this subexpression doesn't really
2404 // exist in the high-level semantics.
2405 case Decl::Field:
2406 case Decl::IndirectField:
2407 assert(getLangOptions().CPlusPlus &&
2408 "building reference to field in C?");
2409
2410 // These can't have reference type in well-formed programs, but
2411 // for internal consistency we do this anyway.
2412 type = type.getNonReferenceType();
2413 valueKind = VK_LValue;
2414 break;
2415
2416 // Non-type template parameters are either l-values or r-values
2417 // depending on the type.
2418 case Decl::NonTypeTemplateParm: {
2419 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2420 type = reftype->getPointeeType();
2421 valueKind = VK_LValue; // even if the parameter is an r-value reference
2422 break;
2423 }
2424
2425 // For non-references, we need to strip qualifiers just in case
2426 // the template parameter was declared as 'const int' or whatever.
2427 valueKind = VK_RValue;
2428 type = type.getUnqualifiedType();
2429 break;
2430 }
2431
2432 case Decl::Var:
2433 // In C, "extern void blah;" is valid and is an r-value.
2434 if (!getLangOptions().CPlusPlus &&
2435 !type.hasQualifiers() &&
2436 type->isVoidType()) {
2437 valueKind = VK_RValue;
2438 break;
2439 }
2440 // fallthrough
2441
2442 case Decl::ImplicitParam:
2443 case Decl::ParmVar:
2444 // These are always l-values.
2445 valueKind = VK_LValue;
2446 type = type.getNonReferenceType();
2447 break;
2448
2449 case Decl::Function: {
2450 // Functions are l-values in C++.
2451 if (getLangOptions().CPlusPlus) {
2452 valueKind = VK_LValue;
2453 break;
2454 }
2455
2456 // C99 DR 316 says that, if a function type comes from a
2457 // function definition (without a prototype), that type is only
2458 // used for checking compatibility. Therefore, when referencing
2459 // the function, we pretend that we don't have the full function
2460 // type.
2461 if (!cast<FunctionDecl>(VD)->hasPrototype())
2462 if (const FunctionProtoType *proto = type->getAs<FunctionProtoType>())
2463 type = Context.getFunctionNoProtoType(proto->getResultType(),
2464 proto->getExtInfo());
2465
2466 // Functions are r-values in C.
2467 valueKind = VK_RValue;
2468 break;
2469 }
2470
2471 case Decl::CXXMethod:
2472 // C++ methods are l-values if static, r-values if non-static.
2473 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2474 valueKind = VK_LValue;
2475 break;
2476 }
2477 // fallthrough
2478
2479 case Decl::CXXConversion:
2480 case Decl::CXXDestructor:
2481 case Decl::CXXConstructor:
2482 valueKind = VK_RValue;
2483 break;
2484 }
2485
2486 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2487 }
2488
John McCallc63de662011-02-02 13:00:07 +00002489 }
John McCall7decc9e2010-11-18 06:31:45 +00002490
John McCall351762c2011-02-07 10:33:21 +00002491 llvm_unreachable("unknown capture result");
2492 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002493}
Chris Lattnere168f762006-11-10 05:29:30 +00002494
John McCalldadc5752010-08-24 06:29:42 +00002495ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlffbcf962009-01-18 18:53:16 +00002496 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002497 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002498
Chris Lattnere168f762006-11-10 05:29:30 +00002499 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002500 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002501 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2502 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2503 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002504 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002505
Chris Lattnera81a0272008-01-12 08:14:25 +00002506 // Pre-defined identifiers are of type char[x], where x is the length of the
2507 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002508
Anders Carlsson2fb08242009-09-08 18:24:21 +00002509 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002510 if (!currentDecl && getCurBlock())
2511 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002512 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002513 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002514 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002515 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002516
Anders Carlsson0b209a82009-09-11 01:22:35 +00002517 QualType ResTy;
2518 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2519 ResTy = Context.DependentTy;
2520 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002521 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002522
Anders Carlsson0b209a82009-09-11 01:22:35 +00002523 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002524 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002525 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2526 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002527 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002528}
2529
John McCalldadc5752010-08-24 06:29:42 +00002530ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002531 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002532 bool Invalid = false;
2533 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2534 if (Invalid)
2535 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002536
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002537 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2538 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002539 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002540 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002541
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002542 QualType Ty;
2543 if (!getLangOptions().CPlusPlus)
2544 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2545 else if (Literal.isWide())
2546 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002547 else if (Literal.isMultiChar())
2548 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002549 else
2550 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002551
Sebastian Redl20614a72009-01-20 22:23:13 +00002552 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2553 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002554 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002555}
2556
John McCalldadc5752010-08-24 06:29:42 +00002557ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002558 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002559 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2560 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002561 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002562 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002563 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002564 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002565 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002566
Chris Lattner23b7eb62007-06-15 23:05:46 +00002567 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002568 // Add padding so that NumericLiteralParser can overread by one character.
2569 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002570 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002571
Chris Lattner67ca9252007-05-21 01:08:44 +00002572 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002573 bool Invalid = false;
2574 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2575 if (Invalid)
2576 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002577
Mike Stump11289f42009-09-09 15:08:12 +00002578 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002579 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002580 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002581 return ExprError();
2582
Chris Lattner1c20a172007-08-26 03:42:43 +00002583 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002584
Chris Lattner1c20a172007-08-26 03:42:43 +00002585 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002586 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002587 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002588 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002589 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002590 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002591 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002592 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002593
2594 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2595
John McCall53b93a02009-12-24 09:08:04 +00002596 using llvm::APFloat;
2597 APFloat Val(Format);
2598
2599 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002600
2601 // Overflow is always an error, but underflow is only an error if
2602 // we underflowed to zero (APFloat reports denormals as underflow).
2603 if ((result & APFloat::opOverflow) ||
2604 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002605 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002606 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002607 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002608 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002609 APFloat::getLargest(Format).toString(buffer);
2610 } else {
John McCall62abc942010-02-26 23:35:57 +00002611 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002612 APFloat::getSmallest(Format).toString(buffer);
2613 }
2614
2615 Diag(Tok.getLocation(), diagnostic)
2616 << Ty
2617 << llvm::StringRef(buffer.data(), buffer.size());
2618 }
2619
2620 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002621 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002622
Peter Collingbourne0b69e1a2010-12-04 01:50:56 +00002623 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2624 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2625
Chris Lattner1c20a172007-08-26 03:42:43 +00002626 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002627 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002628 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002629 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002630
Neil Boothac582c52007-08-29 22:00:19 +00002631 // long long is a C99 feature.
2632 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002633 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002634 Diag(Tok.getLocation(), diag::ext_longlong);
2635
Chris Lattner67ca9252007-05-21 01:08:44 +00002636 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002637 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002638
Chris Lattner67ca9252007-05-21 01:08:44 +00002639 if (Literal.GetIntegerValue(ResultVal)) {
2640 // If this value didn't fit into uintmax_t, warn and force to ull.
2641 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002642 Ty = Context.UnsignedLongLongTy;
2643 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002644 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002645 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002646 // If this value fits into a ULL, try to figure out what else it fits into
2647 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002648
Chris Lattner67ca9252007-05-21 01:08:44 +00002649 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2650 // be an unsigned int.
2651 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2652
2653 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002654 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002655 if (!Literal.isLong && !Literal.isLongLong) {
2656 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002657 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002658
Chris Lattner67ca9252007-05-21 01:08:44 +00002659 // Does it fit in a unsigned int?
2660 if (ResultVal.isIntN(IntSize)) {
2661 // Does it fit in a signed int?
2662 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002663 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002664 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002665 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002666 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002667 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002668 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002669
Chris Lattner67ca9252007-05-21 01:08:44 +00002670 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002671 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002672 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002673
Chris Lattner67ca9252007-05-21 01:08:44 +00002674 // Does it fit in a unsigned long?
2675 if (ResultVal.isIntN(LongSize)) {
2676 // Does it fit in a signed long?
2677 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002678 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002679 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002680 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002681 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002682 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002683 }
2684
Chris Lattner67ca9252007-05-21 01:08:44 +00002685 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002686 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002687 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002688
Chris Lattner67ca9252007-05-21 01:08:44 +00002689 // Does it fit in a unsigned long long?
2690 if (ResultVal.isIntN(LongLongSize)) {
2691 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002692 // To be compatible with MSVC, hex integer literals ending with the
2693 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002694 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2695 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002696 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002697 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002698 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002699 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002700 }
2701 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002702
Chris Lattner67ca9252007-05-21 01:08:44 +00002703 // If we still couldn't decide a type, we probably have something that
2704 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002705 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002706 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002707 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002708 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002709 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002710
Chris Lattner55258cf2008-05-09 05:59:00 +00002711 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002712 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002713 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002714 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002715 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002716
Chris Lattner1c20a172007-08-26 03:42:43 +00002717 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2718 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002719 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002720 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002721
2722 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002723}
2724
John McCalldadc5752010-08-24 06:29:42 +00002725ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002726 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002727 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002728 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002729}
2730
Steve Naroff71b59a92007-06-04 22:22:31 +00002731/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002732/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002733bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00002734 SourceLocation OpLoc,
John McCall36e7fe32010-10-12 00:20:44 +00002735 SourceRange ExprRange,
Sebastian Redl6f282892008-11-11 17:56:53 +00002736 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002737 if (exprType->isDependentType())
2738 return false;
2739
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002740 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2741 // the result is the size of the referenced type."
2742 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2743 // result shall be the alignment of the referenced type."
2744 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2745 exprType = Ref->getPointeeType();
2746
Steve Naroff043d45d2007-05-15 02:32:35 +00002747 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002748 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002749 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002750 if (isSizeof)
2751 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2752 return false;
2753 }
Mike Stump11289f42009-09-09 15:08:12 +00002754
Chris Lattner62975a72009-04-24 00:30:45 +00002755 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002756 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002757 Diag(OpLoc, diag::ext_sizeof_void_type)
2758 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002759 return false;
2760 }
Mike Stump11289f42009-09-09 15:08:12 +00002761
Chris Lattner62975a72009-04-24 00:30:45 +00002762 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002763 PDiag(diag::err_sizeof_alignof_incomplete_type)
2764 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002765 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002766
Chris Lattner62975a72009-04-24 00:30:45 +00002767 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002768 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002769 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002770 << exprType << isSizeof << ExprRange;
2771 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002772 }
Mike Stump11289f42009-09-09 15:08:12 +00002773
Chris Lattner62975a72009-04-24 00:30:45 +00002774 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002775}
2776
John McCall36e7fe32010-10-12 00:20:44 +00002777static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2778 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002779 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002780
Mike Stump11289f42009-09-09 15:08:12 +00002781 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002782 if (isa<DeclRefExpr>(E))
2783 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002784
2785 // Cannot know anything else if the expression is dependent.
2786 if (E->isTypeDependent())
2787 return false;
2788
Douglas Gregor71235ec2009-05-02 02:18:30 +00002789 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00002790 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00002791 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002792 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002793
2794 // Alignment of a field access is always okay, so long as it isn't a
2795 // bit-field.
2796 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002797 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002798 return false;
2799
John McCall36e7fe32010-10-12 00:20:44 +00002800 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
Chris Lattner8dff0172009-01-24 20:17:12 +00002801}
2802
Douglas Gregor0950e412009-03-13 21:01:28 +00002803/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002804ExprResult
John McCallbcd03502009-12-07 02:54:59 +00002805Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00002806 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002807 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002808 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002809 return ExprError();
2810
John McCallbcd03502009-12-07 02:54:59 +00002811 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002812
Douglas Gregor0950e412009-03-13 21:01:28 +00002813 if (!T->isDependentType() &&
2814 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2815 return ExprError();
2816
2817 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00002818 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00002819 Context.getSizeType(), OpLoc,
2820 R.getEnd()));
2821}
2822
2823/// \brief Build a sizeof or alignof expression given an expression
2824/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002825ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00002826Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002827 bool isSizeOf, SourceRange R) {
2828 // Verify that the operand is valid.
2829 bool isInvalid = false;
2830 if (E->isTypeDependent()) {
2831 // Delay type-checking for type-dependent expressions.
2832 } else if (!isSizeOf) {
John McCall36e7fe32010-10-12 00:20:44 +00002833 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002834 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002835 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2836 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00002837 } else if (E->getType()->isPlaceholderType()) {
2838 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2839 if (PE.isInvalid()) return ExprError();
2840 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00002841 } else {
2842 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2843 }
2844
2845 if (isInvalid)
2846 return ExprError();
2847
2848 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2849 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2850 Context.getSizeType(), OpLoc,
2851 R.getEnd()));
2852}
2853
Sebastian Redl6f282892008-11-11 17:56:53 +00002854/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2855/// the same for @c alignof and @c __alignof
2856/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002857ExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00002858Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2859 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002860 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002861 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002862
Sebastian Redl6f282892008-11-11 17:56:53 +00002863 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002864 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002865 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
John McCallbcd03502009-12-07 02:54:59 +00002866 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002867 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002868
Douglas Gregor0950e412009-03-13 21:01:28 +00002869 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00002870 ExprResult Result
Douglas Gregor0950e412009-03-13 21:01:28 +00002871 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2872
Douglas Gregor0950e412009-03-13 21:01:28 +00002873 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002874}
2875
John McCall4bc41ae2010-11-18 19:01:18 +00002876static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2877 bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002878 if (V->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002879 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002880
John McCall34376a62010-12-04 03:47:34 +00002881 // _Real and _Imag are only l-values for normal l-values.
2882 if (V->getObjectKind() != OK_Ordinary)
John McCall27584242010-12-06 20:48:59 +00002883 S.DefaultLvalueConversion(V);
John McCall34376a62010-12-04 03:47:34 +00002884
Chris Lattnere267f5d2007-08-26 05:39:26 +00002885 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00002886 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002887 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002888
Chris Lattnere267f5d2007-08-26 05:39:26 +00002889 // Otherwise they pass through real integer and floating point types here.
2890 if (V->getType()->isArithmeticType())
2891 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002892
John McCall36226622010-10-12 02:09:17 +00002893 // Test for placeholders.
John McCall4bc41ae2010-11-18 19:01:18 +00002894 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall36226622010-10-12 02:09:17 +00002895 if (PR.isInvalid()) return QualType();
2896 if (PR.take() != V) {
2897 V = PR.take();
John McCall4bc41ae2010-11-18 19:01:18 +00002898 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002899 }
2900
Chris Lattnere267f5d2007-08-26 05:39:26 +00002901 // Reject anything else.
John McCall4bc41ae2010-11-18 19:01:18 +00002902 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002903 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002904 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002905}
2906
2907
Chris Lattnere168f762006-11-10 05:29:30 +00002908
John McCalldadc5752010-08-24 06:29:42 +00002909ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002910Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002911 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002912 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002913 switch (Kind) {
2914 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002915 case tok::plusplus: Opc = UO_PostInc; break;
2916 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002917 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002918
John McCallb268a282010-08-23 23:25:46 +00002919 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002920}
2921
John McCall4bc41ae2010-11-18 19:01:18 +00002922/// Expressions of certain arbitrary types are forbidden by C from
2923/// having l-value type. These are:
2924/// - 'void', but not qualified void
2925/// - function types
2926///
2927/// The exact rule here is C99 6.3.2.1:
2928/// An lvalue is an expression with an object type or an incomplete
2929/// type other than void.
2930static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2931 return ((T->isVoidType() && !T.hasQualifiers()) ||
2932 T->isFunctionType());
2933}
2934
John McCalldadc5752010-08-24 06:29:42 +00002935ExprResult
John McCallb268a282010-08-23 23:25:46 +00002936Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2937 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002938 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002939 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002940 if (Result.isInvalid()) return ExprError();
2941 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002942
John McCallb268a282010-08-23 23:25:46 +00002943 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002944
Douglas Gregor40412ac2008-11-19 17:17:41 +00002945 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002946 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002947 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002948 Context.DependentTy,
2949 VK_LValue, OK_Ordinary,
2950 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002951 }
2952
Mike Stump11289f42009-09-09 15:08:12 +00002953 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002954 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002955 LHSExp->getType()->isEnumeralType() ||
2956 RHSExp->getType()->isRecordType() ||
2957 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002958 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002959 }
2960
John McCallb268a282010-08-23 23:25:46 +00002961 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002962}
2963
2964
John McCalldadc5752010-08-24 06:29:42 +00002965ExprResult
John McCallb268a282010-08-23 23:25:46 +00002966Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2967 Expr *Idx, SourceLocation RLoc) {
2968 Expr *LHSExp = Base;
2969 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002970
Chris Lattner36d572b2007-07-16 00:14:47 +00002971 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002972 if (!LHSExp->getType()->getAs<VectorType>())
2973 DefaultFunctionArrayLvalueConversion(LHSExp);
2974 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002975
Chris Lattner36d572b2007-07-16 00:14:47 +00002976 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00002977 ExprValueKind VK = VK_LValue;
2978 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00002979
Steve Naroffc1aadb12007-03-28 21:49:40 +00002980 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002981 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002982 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002983 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002984 Expr *BaseExpr, *IndexExpr;
2985 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002986 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2987 BaseExpr = LHSExp;
2988 IndexExpr = RHSExp;
2989 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002990 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002991 BaseExpr = LHSExp;
2992 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002993 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002994 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002995 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002996 BaseExpr = RHSExp;
2997 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002998 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002999 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003000 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003001 BaseExpr = LHSExp;
3002 IndexExpr = RHSExp;
3003 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003004 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003005 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003006 // Handle the uncommon case of "123[Ptr]".
3007 BaseExpr = RHSExp;
3008 IndexExpr = LHSExp;
3009 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003010 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003011 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003012 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003013 VK = LHSExp->getValueKind();
3014 if (VK != VK_RValue)
3015 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003016
Chris Lattner36d572b2007-07-16 00:14:47 +00003017 // FIXME: need to deal with const...
3018 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003019 } else if (LHSTy->isArrayType()) {
3020 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003021 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003022 // wasn't promoted because of the C90 rule that doesn't
3023 // allow promoting non-lvalue arrays. Warn, then
3024 // force the promotion here.
3025 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3026 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003027 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCalle3027922010-08-25 11:45:40 +00003028 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00003029 LHSTy = LHSExp->getType();
3030
3031 BaseExpr = LHSExp;
3032 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003033 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003034 } else if (RHSTy->isArrayType()) {
3035 // Same as previous, except for 123[f().a] case
3036 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3037 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003038 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCalle3027922010-08-25 11:45:40 +00003039 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00003040 RHSTy = RHSExp->getType();
3041
3042 BaseExpr = RHSExp;
3043 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003044 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003045 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003046 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3047 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003048 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003049 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003050 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003051 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3052 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003053
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003054 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003055 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3056 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003057 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3058
Douglas Gregorac1fb652009-03-24 19:52:54 +00003059 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003060 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3061 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003062 // incomplete types are not object types.
3063 if (ResultType->isFunctionType()) {
3064 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3065 << ResultType << BaseExpr->getSourceRange();
3066 return ExprError();
3067 }
Mike Stump11289f42009-09-09 15:08:12 +00003068
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003069 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3070 // GNU extension: subscripting on pointer to void
3071 Diag(LLoc, diag::ext_gnu_void_ptr)
3072 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003073
3074 // C forbids expressions of unqualified void type from being l-values.
3075 // See IsCForbiddenLValueType.
3076 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003077 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003078 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003079 PDiag(diag::err_subscript_incomplete_type)
3080 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003081 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003082
Chris Lattner62975a72009-04-24 00:30:45 +00003083 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003084 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003085 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3086 << ResultType << BaseExpr->getSourceRange();
3087 return ExprError();
3088 }
Mike Stump11289f42009-09-09 15:08:12 +00003089
John McCall4bc41ae2010-11-18 19:01:18 +00003090 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3091 !IsCForbiddenLValueType(Context, ResultType));
3092
Mike Stump4e1f26a2009-02-19 03:04:26 +00003093 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003094 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003095}
3096
John McCall4bc41ae2010-11-18 19:01:18 +00003097/// Check an ext-vector component access expression.
3098///
3099/// VK should be set in advance to the value kind of the base
3100/// expression.
3101static QualType
3102CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3103 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00003104 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00003105 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3106 // see FIXME there.
3107 //
3108 // FIXME: This logic can be greatly simplified by splitting it along
3109 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00003110 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00003111
Steve Narofff8fd09e2007-07-27 22:15:19 +00003112 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003113 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003114
Mike Stump4e1f26a2009-02-19 03:04:26 +00003115 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00003116 // special names that indicate a subset of exactly half the elements are
3117 // to be selected.
3118 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003119
Nate Begemanbb70bf62009-01-18 01:47:54 +00003120 // This flag determines whether or not CompName has an 's' char prefix,
3121 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00003122 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00003123
John McCall4bc41ae2010-11-18 19:01:18 +00003124 bool HasRepeated = false;
3125 bool HasIndex[16] = {};
3126
3127 int Idx;
3128
Nate Begemanf322eab2008-05-09 06:41:27 +00003129 // Check that we've found one of the special components, or that the component
3130 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003131 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00003132 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3133 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00003134 } else if (!HexSwizzle &&
3135 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3136 do {
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 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3141 } else {
3142 if (HexSwizzle) compStr++;
3143 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3144 if (HasIndex[Idx]) HasRepeated = true;
3145 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003146 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003147 }
Chris Lattner7e152db2007-08-02 22:33:49 +00003148 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00003149
Mike Stump4e1f26a2009-02-19 03:04:26 +00003150 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00003151 // We didn't get to the end of the string. This means the component names
3152 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00003153 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003154 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00003155 return QualType();
3156 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003157
Nate Begemanbb70bf62009-01-18 01:47:54 +00003158 // Ensure no component accessor exceeds the width of the vector type it
3159 // operates on.
3160 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003161 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003162
3163 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00003164 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00003165
3166 while (*compStr) {
3167 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00003168 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00003169 << baseType << SourceRange(CompLoc);
3170 return QualType();
3171 }
3172 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00003173 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003174
Steve Narofff8fd09e2007-07-27 22:15:19 +00003175 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003176 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00003177 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00003178 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00003179 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00003180 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00003181 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003182 if (HexSwizzle)
3183 CompSize--;
3184
Steve Narofff8fd09e2007-07-27 22:15:19 +00003185 if (CompSize == 1)
3186 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003187
John McCall4bc41ae2010-11-18 19:01:18 +00003188 if (HasRepeated) VK = VK_RValue;
3189
3190 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003191 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003192 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003193 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3194 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3195 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003196 }
3197 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003198}
3199
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003200static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003201 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003202 const Selector &Sel,
3203 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003204 if (Member)
3205 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3206 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003207 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003208 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003209
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003210 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3211 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003212 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3213 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003214 return D;
3215 }
3216 return 0;
3217}
3218
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003219static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3220 IdentifierInfo *Member,
3221 const Selector &Sel,
3222 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003223 // Check protocols on qualified interfaces.
3224 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003225 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003226 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003227 if (Member)
3228 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3229 GDecl = PD;
3230 break;
3231 }
3232 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003233 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003234 GDecl = OMD;
3235 break;
3236 }
3237 }
3238 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003239 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003240 E = QIdTy->qual_end(); I != E; ++I) {
3241 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003242 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3243 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003244 if (GDecl)
3245 return GDecl;
3246 }
3247 }
3248 return GDecl;
3249}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003250
John McCalldadc5752010-08-24 06:29:42 +00003251ExprResult
John McCallb268a282010-08-23 23:25:46 +00003252Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003253 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003254 const CXXScopeSpec &SS,
3255 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003256 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003257 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003258 // Even in dependent contexts, try to diagnose base expressions with
3259 // obviously wrong types, e.g.:
3260 //
3261 // T* t;
3262 // t.f;
3263 //
3264 // In Obj-C++, however, the above expression is valid, since it could be
3265 // accessing the 'f' property if T is an Obj-C interface. The extra check
3266 // allows this, while still reporting an error if T is a struct pointer.
3267 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003268 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003269 if (PT && (!getLangOptions().ObjC1 ||
3270 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003271 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003272 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003273 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003274 return ExprError();
3275 }
3276 }
3277
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003278 assert(BaseType->isDependentType() ||
3279 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003280 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003281
3282 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3283 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003284 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003285 IsArrow, OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003286 SS.getScopeRep(),
John McCall10eae182009-11-30 22:42:35 +00003287 SS.getRange(),
3288 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003289 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003290}
3291
3292/// We know that the given qualified member reference points only to
3293/// declarations which do not belong to the static type of the base
3294/// expression. Diagnose the problem.
3295static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3296 Expr *BaseExpr,
3297 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003298 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00003299 NamedDecl *rep,
3300 const DeclarationNameInfo &nameInfo) {
John McCallcd4b4772009-12-02 03:53:29 +00003301 // If this is an implicit member access, use a different set of
3302 // diagnostics.
3303 if (!BaseExpr)
John McCallf3a88602011-02-03 08:15:49 +00003304 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall10eae182009-11-30 22:42:35 +00003305
John McCallf3a88602011-02-03 08:15:49 +00003306 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3307 << SS.getRange() << rep << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003308}
3309
3310// Check whether the declarations we found through a nested-name
3311// specifier in a member expression are actually members of the base
3312// type. The restriction here is:
3313//
3314// C++ [expr.ref]p2:
3315// ... In these cases, the id-expression shall name a
3316// member of the class or of one of its base classes.
3317//
3318// So it's perfectly legitimate for the nested-name specifier to name
3319// an unrelated class, and for us to find an overload set including
3320// decls from classes which are not superclasses, as long as the decl
3321// we actually pick through overload resolution is from a superclass.
3322bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3323 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003324 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003325 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003326 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3327 if (!BaseRT) {
3328 // We can't check this yet because the base type is still
3329 // dependent.
3330 assert(BaseType->isDependentType());
3331 return false;
3332 }
3333 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003334
3335 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003336 // If this is an implicit member reference and we find a
3337 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003338 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003339 return false;
John McCall10eae182009-11-30 22:42:35 +00003340
John McCall2d74de92009-12-01 22:10:20 +00003341 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003342 DeclContext *DC = (*I)->getDeclContext();
3343 while (DC->isTransparentContext())
3344 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003345
Douglas Gregora9c3e822010-07-28 22:27:52 +00003346 if (!DC->isRecord())
3347 continue;
3348
John McCall2d74de92009-12-01 22:10:20 +00003349 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003350 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003351
3352 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3353 return false;
3354 }
3355
John McCallf3a88602011-02-03 08:15:49 +00003356 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3357 R.getRepresentativeDecl(),
3358 R.getLookupNameInfo());
John McCall2d74de92009-12-01 22:10:20 +00003359 return true;
3360}
3361
3362static bool
3363LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3364 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003365 SourceLocation OpLoc, CXXScopeSpec &SS,
3366 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003367 RecordDecl *RDecl = RTy->getDecl();
3368 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003369 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003370 << BaseRange))
3371 return true;
3372
John McCalle9cccd82010-06-16 08:42:20 +00003373 if (HasTemplateArgs) {
3374 // LookupTemplateName doesn't expect these both to exist simultaneously.
3375 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3376
3377 bool MOUS;
3378 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3379 return false;
3380 }
3381
John McCall2d74de92009-12-01 22:10:20 +00003382 DeclContext *DC = RDecl;
3383 if (SS.isSet()) {
3384 // If the member name was a qualified-id, look into the
3385 // nested-name-specifier.
3386 DC = SemaRef.computeDeclContext(SS, false);
3387
John McCall0b66eb32010-05-01 00:40:08 +00003388 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003389 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3390 << SS.getRange() << DC;
3391 return true;
3392 }
3393
John McCall2d74de92009-12-01 22:10:20 +00003394 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003395
John McCall2d74de92009-12-01 22:10:20 +00003396 if (!isa<TypeDecl>(DC)) {
3397 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3398 << DC << SS.getRange();
3399 return true;
John McCall10eae182009-11-30 22:42:35 +00003400 }
3401 }
3402
John McCall2d74de92009-12-01 22:10:20 +00003403 // The record definition is complete, now look up the member.
3404 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003405
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003406 if (!R.empty())
3407 return false;
3408
3409 // We didn't find anything with the given name, so try to correct
3410 // for typos.
3411 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003412 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003413 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003414 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3415 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3416 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003417 << FixItHint::CreateReplacement(R.getNameLoc(),
3418 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003419 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3420 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3421 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003422 return false;
3423 } else {
3424 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003425 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003426 }
3427
John McCall10eae182009-11-30 22:42:35 +00003428 return false;
3429}
3430
John McCalldadc5752010-08-24 06:29:42 +00003431ExprResult
John McCallb268a282010-08-23 23:25:46 +00003432Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003433 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003434 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003435 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003436 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003437 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003438 if (BaseType->isDependentType() ||
3439 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003440 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003441 IsArrow, OpLoc,
3442 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003443 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003444
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003445 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003446
John McCall2d74de92009-12-01 22:10:20 +00003447 // Implicit member accesses.
3448 if (!Base) {
3449 QualType RecordTy = BaseType;
3450 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3451 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3452 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003453 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003454 return ExprError();
3455
3456 // Explicit member accesses.
3457 } else {
John McCalldadc5752010-08-24 06:29:42 +00003458 ExprResult Result =
John McCall2d74de92009-12-01 22:10:20 +00003459 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003460 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003461
3462 if (Result.isInvalid()) {
3463 Owned(Base);
3464 return ExprError();
3465 }
3466
3467 if (Result.get())
3468 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003469
3470 // LookupMemberExpr can modify Base, and thus change BaseType
3471 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003472 }
3473
John McCallb268a282010-08-23 23:25:46 +00003474 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003475 OpLoc, IsArrow, SS, FirstQualifierInScope,
3476 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003477}
3478
John McCalldadc5752010-08-24 06:29:42 +00003479ExprResult
John McCallb268a282010-08-23 23:25:46 +00003480Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003481 SourceLocation OpLoc, bool IsArrow,
3482 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003483 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003484 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003485 const TemplateArgumentListInfo *TemplateArgs,
3486 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003487 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003488 if (IsArrow) {
3489 assert(BaseType->isPointerType());
3490 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3491 }
John McCalla8ae2222010-04-06 21:38:20 +00003492 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003493
John McCallb268a282010-08-23 23:25:46 +00003494 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003495 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3496 DeclarationName MemberName = MemberNameInfo.getName();
3497 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003498
3499 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003500 return ExprError();
3501
John McCall10eae182009-11-30 22:42:35 +00003502 if (R.empty()) {
3503 // Rederive where we looked up.
3504 DeclContext *DC = (SS.isSet()
3505 ? computeDeclContext(SS, false)
3506 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003507
John McCall10eae182009-11-30 22:42:35 +00003508 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003509 << MemberName << DC
3510 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003511 return ExprError();
3512 }
3513
John McCall38836f02010-01-15 08:34:02 +00003514 // Diagnose lookups that find only declarations from a non-base
3515 // type. This is possible for either qualified lookups (which may
3516 // have been qualified with an unrelated type) or implicit member
3517 // expressions (which were found with unqualified lookup and thus
3518 // may have come from an enclosing scope). Note that it's okay for
3519 // lookup to find declarations from a non-base type as long as those
3520 // aren't the ones picked by overload resolution.
3521 if ((SS.isSet() || !BaseExpr ||
3522 (isa<CXXThisExpr>(BaseExpr) &&
3523 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003524 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003525 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003526 return ExprError();
3527
3528 // Construct an unresolved result if we in fact got an unresolved
3529 // result.
3530 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003531 // Suppress any lookup-related diagnostics; we'll do these when we
3532 // pick a member.
3533 R.suppressDiagnostics();
3534
John McCall10eae182009-11-30 22:42:35 +00003535 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003536 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003537 BaseExpr, BaseExprType,
3538 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003539 Qualifier, SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003540 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003541 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003542
3543 return Owned(MemExpr);
3544 }
3545
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003546 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003547 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003548 NamedDecl *MemberDecl = R.getFoundDecl();
3549
3550 // FIXME: diagnose the presence of template arguments now.
3551
3552 // If the decl being referenced had an error, return an error for this
3553 // sub-expr without emitting another error, in order to avoid cascading
3554 // error cases.
3555 if (MemberDecl->isInvalidDecl())
3556 return ExprError();
3557
John McCall2d74de92009-12-01 22:10:20 +00003558 // Handle the implicit-member-access case.
3559 if (!BaseExpr) {
3560 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003561 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003562 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003563
Douglas Gregorb15af892010-01-07 23:12:05 +00003564 SourceLocation Loc = R.getNameLoc();
3565 if (SS.getRange().isValid())
3566 Loc = SS.getRange().getBegin();
3567 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003568 }
3569
John McCall10eae182009-11-30 22:42:35 +00003570 bool ShouldCheckUse = true;
3571 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3572 // Don't diagnose the use of a virtual member function unless it's
3573 // explicitly qualified.
3574 if (MD->isVirtual() && !SS.isSet())
3575 ShouldCheckUse = false;
3576 }
3577
3578 // Check the use of this member.
3579 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3580 Owned(BaseExpr);
3581 return ExprError();
3582 }
3583
John McCall34376a62010-12-04 03:47:34 +00003584 // Perform a property load on the base regardless of whether we
3585 // actually need it for the declaration.
3586 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3587 ConvertPropertyForRValue(BaseExpr);
3588
John McCallfeb624a2010-11-23 20:48:44 +00003589 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3590 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3591 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003592
Francois Pichet783dd6e2010-11-21 06:08:52 +00003593 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3594 // We may have found a field within an anonymous union or struct
3595 // (C++ [class.union]).
John McCallf3a88602011-02-03 08:15:49 +00003596 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00003597 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003598
John McCall10eae182009-11-30 22:42:35 +00003599 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3600 MarkDeclarationReferenced(MemberLoc, Var);
3601 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003602 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003603 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003604 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003605 }
3606
John McCall7decc9e2010-11-18 06:31:45 +00003607 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall10eae182009-11-30 22:42:35 +00003608 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3609 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003610 MemberFn, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003611 MemberFn->getType(),
3612 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3613 OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003614 }
John McCall7decc9e2010-11-18 06:31:45 +00003615 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003616
3617 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3618 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3619 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003620 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003621 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003622 }
3623
3624 Owned(BaseExpr);
3625
Douglas Gregor861eb802010-04-25 20:55:08 +00003626 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003627 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003628 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003629 << MemberName << BaseType << int(IsArrow);
3630 else
3631 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3632 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003633
Douglas Gregor861eb802010-04-25 20:55:08 +00003634 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3635 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003636 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003637 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003638}
3639
John McCall68fc88ec2010-12-15 16:46:44 +00003640/// Given that normal member access failed on the given expression,
3641/// and given that the expression's type involves builtin-id or
3642/// builtin-Class, decide whether substituting in the redefinition
3643/// types would be profitable. The redefinition type is whatever
3644/// this translation unit tried to typedef to id/Class; we store
3645/// it to the side and then re-use it in places like this.
3646static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3647 const ObjCObjectPointerType *opty
3648 = base->getType()->getAs<ObjCObjectPointerType>();
3649 if (!opty) return false;
3650
3651 const ObjCObjectType *ty = opty->getObjectType();
3652
3653 QualType redef;
3654 if (ty->isObjCId()) {
3655 redef = S.Context.ObjCIdRedefinitionType;
3656 } else if (ty->isObjCClass()) {
3657 redef = S.Context.ObjCClassRedefinitionType;
3658 } else {
3659 return false;
3660 }
3661
3662 // Do the substitution as long as the redefinition type isn't just a
3663 // possibly-qualified pointer to builtin-id or builtin-Class again.
3664 opty = redef->getAs<ObjCObjectPointerType>();
3665 if (opty && !opty->getObjectType()->getInterface() != 0)
3666 return false;
3667
3668 S.ImpCastExprToType(base, redef, CK_BitCast);
3669 return true;
3670}
3671
John McCall10eae182009-11-30 22:42:35 +00003672/// Look up the given member of the given non-type-dependent
3673/// expression. This can return in one of two ways:
3674/// * If it returns a sentinel null-but-valid result, the caller will
3675/// assume that lookup was performed and the results written into
3676/// the provided structure. It will take over from there.
3677/// * Otherwise, the returned expression will be produced in place of
3678/// an ordinary member expression.
3679///
3680/// The ObjCImpDecl bit is a gross hack that will need to be properly
3681/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00003682ExprResult
John McCall10eae182009-11-30 22:42:35 +00003683Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00003684 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003685 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00003686 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003687 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00003688
Steve Naroffeaaae462007-12-16 21:42:28 +00003689 // Perform default conversions.
3690 DefaultFunctionArrayConversion(BaseExpr);
John McCall15317a22010-12-15 04:42:30 +00003691 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003692
Steve Naroff185616f2007-07-26 03:11:44 +00003693 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00003694 assert(!BaseType->isDependentType());
3695
3696 DeclarationName MemberName = R.getLookupName();
3697 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00003698
John McCall68fc88ec2010-12-15 16:46:44 +00003699 // For later type-checking purposes, turn arrow accesses into dot
3700 // accesses. The only access type we support that doesn't follow
3701 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3702 // and those never use arrows, so this is unaffected.
3703 if (IsArrow) {
3704 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3705 BaseType = Ptr->getPointeeType();
3706 else if (const ObjCObjectPointerType *Ptr
3707 = BaseType->getAs<ObjCObjectPointerType>())
3708 BaseType = Ptr->getPointeeType();
3709 else if (BaseType->isRecordType()) {
3710 // Recover from arrow accesses to records, e.g.:
3711 // struct MyRecord foo;
3712 // foo->bar
3713 // This is actually well-formed in C++ if MyRecord has an
3714 // overloaded operator->, but that should have been dealt with
3715 // by now.
3716 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3717 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3718 << FixItHint::CreateReplacement(OpLoc, ".");
3719 IsArrow = false;
3720 } else {
3721 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3722 << BaseType << BaseExpr->getSourceRange();
3723 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00003724 }
3725 }
3726
John McCall68fc88ec2010-12-15 16:46:44 +00003727 // Handle field access to simple records.
3728 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3729 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3730 RTy, OpLoc, SS, HasTemplateArgs))
3731 return ExprError();
3732
3733 // Returning valid-but-null is how we indicate to the caller that
3734 // the lookup result was filled in.
3735 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00003736 }
John McCall10eae182009-11-30 22:42:35 +00003737
John McCall68fc88ec2010-12-15 16:46:44 +00003738 // Handle ivar access to Objective-C objects.
3739 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003740 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00003741
3742 // There are three cases for the base type:
3743 // - builtin id (qualified or unqualified)
3744 // - builtin Class (qualified or unqualified)
3745 // - an interface
3746 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3747 if (!IDecl) {
3748 // There's an implicit 'isa' ivar on all objects.
3749 // But we only actually find it this way on objects of type 'id',
3750 // apparently.
3751 if (OTy->isObjCId() && Member->isStr("isa"))
3752 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3753 Context.getObjCClassType()));
3754
3755 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3756 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3757 ObjCImpDecl, HasTemplateArgs);
3758 goto fail;
3759 }
3760
3761 ObjCInterfaceDecl *ClassDeclared;
3762 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3763
3764 if (!IV) {
3765 // Attempt to correct for typos in ivar names.
3766 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3767 LookupMemberName);
3768 if (CorrectTypo(Res, 0, 0, IDecl, false,
3769 IsArrow ? CTC_ObjCIvarLookup
3770 : CTC_ObjCPropertyLookup) &&
3771 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3772 Diag(R.getNameLoc(),
3773 diag::err_typecheck_member_reference_ivar_suggest)
3774 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3775 << FixItHint::CreateReplacement(R.getNameLoc(),
3776 IV->getNameAsString());
3777 Diag(IV->getLocation(), diag::note_previous_decl)
3778 << IV->getDeclName();
3779 } else {
3780 Res.clear();
3781 Res.setLookupName(Member);
3782
3783 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3784 << IDecl->getDeclName() << MemberName
3785 << BaseExpr->getSourceRange();
3786 return ExprError();
3787 }
3788 }
3789
3790 // If the decl being referenced had an error, return an error for this
3791 // sub-expr without emitting another error, in order to avoid cascading
3792 // error cases.
3793 if (IV->isInvalidDecl())
3794 return ExprError();
3795
3796 // Check whether we can reference this field.
3797 if (DiagnoseUseOfDecl(IV, MemberLoc))
3798 return ExprError();
3799 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3800 IV->getAccessControl() != ObjCIvarDecl::Package) {
3801 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3802 if (ObjCMethodDecl *MD = getCurMethodDecl())
3803 ClassOfMethodDecl = MD->getClassInterface();
3804 else if (ObjCImpDecl && getCurFunctionDecl()) {
3805 // Case of a c-function declared inside an objc implementation.
3806 // FIXME: For a c-style function nested inside an objc implementation
3807 // class, there is no implementation context available, so we pass
3808 // down the context as argument to this routine. Ideally, this context
3809 // need be passed down in the AST node and somehow calculated from the
3810 // AST for a function decl.
3811 if (ObjCImplementationDecl *IMPD =
3812 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3813 ClassOfMethodDecl = IMPD->getClassInterface();
3814 else if (ObjCCategoryImplDecl* CatImplClass =
3815 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3816 ClassOfMethodDecl = CatImplClass->getClassInterface();
3817 }
3818
3819 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3820 if (ClassDeclared != IDecl ||
3821 ClassOfMethodDecl != ClassDeclared)
3822 Diag(MemberLoc, diag::error_private_ivar_access)
3823 << IV->getDeclName();
3824 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3825 // @protected
3826 Diag(MemberLoc, diag::error_protected_ivar_access)
3827 << IV->getDeclName();
3828 }
3829
3830 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3831 MemberLoc, BaseExpr,
3832 IsArrow));
3833 }
3834
3835 // Objective-C property access.
3836 const ObjCObjectPointerType *OPT;
3837 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3838 // This actually uses the base as an r-value.
3839 DefaultLvalueConversion(BaseExpr);
3840 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3841
3842 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3843
3844 const ObjCObjectType *OT = OPT->getObjectType();
3845
3846 // id, with and without qualifiers.
3847 if (OT->isObjCId()) {
3848 // Check protocols on qualified interfaces.
3849 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3850 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3851 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3852 // Check the use of this declaration
3853 if (DiagnoseUseOfDecl(PD, MemberLoc))
3854 return ExprError();
3855
3856 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3857 VK_LValue,
3858 OK_ObjCProperty,
3859 MemberLoc,
3860 BaseExpr));
3861 }
3862
3863 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3864 // Check the use of this method.
3865 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3866 return ExprError();
3867 Selector SetterSel =
3868 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3869 PP.getSelectorTable(), Member);
3870 ObjCMethodDecl *SMD = 0;
3871 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3872 SetterSel, Context))
3873 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3874 QualType PType = OMD->getSendResultType();
3875
3876 ExprValueKind VK = VK_LValue;
3877 if (!getLangOptions().CPlusPlus &&
3878 IsCForbiddenLValueType(Context, PType))
3879 VK = VK_RValue;
3880 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3881
3882 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3883 VK, OK,
3884 MemberLoc, BaseExpr));
3885 }
3886 }
3887
3888 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3889 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3890 ObjCImpDecl, HasTemplateArgs);
3891
3892 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3893 << MemberName << BaseType);
3894 }
3895
3896 // 'Class', unqualified only.
3897 if (OT->isObjCClass()) {
3898 // Only works in a method declaration (??!).
3899 ObjCMethodDecl *MD = getCurMethodDecl();
3900 if (!MD) {
3901 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3902 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3903 ObjCImpDecl, HasTemplateArgs);
3904
3905 goto fail;
3906 }
3907
3908 // Also must look for a getter name which uses property syntax.
3909 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003910 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3911 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003912 if ((Getter = IFace->lookupClassMethod(Sel))) {
3913 // Check the use of this method.
3914 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3915 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00003916 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003917 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003918 // If we found a getter then this may be a valid dot-reference, we
3919 // will look for the matching setter, in case it is needed.
3920 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00003921 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3922 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003923 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3924 if (!Setter) {
3925 // If this reference is in an @implementation, also check for 'private'
3926 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003927 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003928 }
3929 // Look through local category implementations associated with the class.
3930 if (!Setter)
3931 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003932
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003933 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3934 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003935
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003936 if (Getter || Setter) {
3937 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003938
John McCall4bc41ae2010-11-18 19:01:18 +00003939 ExprValueKind VK = VK_LValue;
3940 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00003941 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00003942 if (!getLangOptions().CPlusPlus &&
3943 IsCForbiddenLValueType(Context, PType))
3944 VK = VK_RValue;
3945 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003946 // Get the expression type from Setter's incoming parameter.
3947 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00003948 }
3949 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3950
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003951 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00003952 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3953 PType, VK, OK,
3954 MemberLoc, BaseExpr));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003955 }
John McCall68fc88ec2010-12-15 16:46:44 +00003956
3957 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3958 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3959 ObjCImpDecl, HasTemplateArgs);
3960
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003961 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00003962 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003963 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003964
John McCall68fc88ec2010-12-15 16:46:44 +00003965 // Normal property access.
3966 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3967 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003968 }
Alexis Huntc46382e2010-04-28 23:02:27 +00003969
Chris Lattnerb63a7452008-07-21 04:28:12 +00003970 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003971 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00003972 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00003973 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall15317a22010-12-15 04:42:30 +00003974 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00003975 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3976 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00003977 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003978 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00003979
3980 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3981 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003982 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003983
John McCall68fc88ec2010-12-15 16:46:44 +00003984 // Adjust builtin-sel to the appropriate redefinition type if that's
3985 // not just a pointer to builtin-sel again.
3986 if (IsArrow &&
3987 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
3988 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
3989 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
3990 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3991 ObjCImpDecl, HasTemplateArgs);
3992 }
3993
3994 // Failure cases.
3995 fail:
3996
3997 // There's a possible road to recovery for function types.
3998 const FunctionType *Fun = 0;
Matt Beaumont-Gay956fc1c2011-02-17 02:54:17 +00003999 SourceLocation ParenInsertionLoc =
4000 PP.getLocForEndOfToken(BaseExpr->getLocEnd());
John McCall68fc88ec2010-12-15 16:46:44 +00004001
4002 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4003 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4004 // fall out, handled below.
4005
4006 // Recover from dot accesses to pointers, e.g.:
4007 // type *foo;
4008 // foo.bar
4009 // This is actually well-formed in two cases:
4010 // - 'type' is an Objective C type
4011 // - 'bar' is a pseudo-destructor name which happens to refer to
4012 // the appropriate pointer type
Argyrios Kyrtzidiscd81fe02011-01-25 23:16:36 +00004013 } else if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
John McCall68fc88ec2010-12-15 16:46:44 +00004014 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
4015 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4016 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
4017 << FixItHint::CreateReplacement(OpLoc, "->");
4018
4019 // Recurse as an -> access.
4020 IsArrow = true;
4021 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4022 ObjCImpDecl, HasTemplateArgs);
4023 }
4024 } else {
4025 Fun = BaseType->getAs<FunctionType>();
4026 }
4027
4028 // If the user is trying to apply -> or . to a function pointer
4029 // type, it's probably because they forgot parentheses to call that
4030 // function. Suggest the addition of those parentheses, build the
4031 // call, and continue on.
4032 if (Fun || BaseType == Context.OverloadTy) {
4033 bool TryCall;
4034 if (BaseType == Context.OverloadTy) {
Matt Beaumont-Gay956fc1c2011-02-17 02:54:17 +00004035 // Plunder the overload set for something that would make the member
4036 // expression valid.
4037 const OverloadExpr *Overloads = cast<OverloadExpr>(BaseExpr);
4038 UnresolvedSet<4> CandidateOverloads;
4039 bool HasZeroArgCandidateOverload = false;
4040 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
4041 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
4042 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*it);
4043 QualType ResultTy = OverloadDecl->getResultType();
4044 if ((!IsArrow && ResultTy->isRecordType()) ||
4045 (IsArrow && ResultTy->isPointerType() &&
4046 ResultTy->getPointeeType()->isRecordType())) {
4047 CandidateOverloads.addDecl(*it);
4048 if (OverloadDecl->getNumParams() == 0) {
4049 HasZeroArgCandidateOverload = true;
4050 }
4051 }
4052 }
4053 if (HasZeroArgCandidateOverload && CandidateOverloads.size() == 1) {
4054 // We have one reasonable overload, and there's only one way to call it,
4055 // so emit a fixit and try to recover
4056 Diag(ParenInsertionLoc, diag::err_member_reference_needs_call)
4057 << 1
4058 << BaseExpr->getSourceRange()
4059 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4060 TryCall = true;
4061 } else {
4062 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
4063 << 0
4064 << BaseExpr->getSourceRange();
4065 int CandidateOverloadCount = CandidateOverloads.size();
4066 int I;
4067 for (I = 0; I < CandidateOverloadCount; ++I) {
4068 // FIXME: Magic number for max shown overloads stolen from
4069 // OverloadCandidateSet::NoteCandidates.
4070 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4071 break;
4072 }
4073 Diag(CandidateOverloads[I].getDecl()->getSourceRange().getBegin(),
4074 diag::note_member_ref_possible_intended_overload);
4075 }
4076 if (I != CandidateOverloadCount) {
4077 Diag(BaseExpr->getExprLoc(), diag::note_ovl_too_many_candidates)
4078 << int(CandidateOverloadCount - I);
4079 }
4080 return ExprError();
4081 }
John McCall68fc88ec2010-12-15 16:46:44 +00004082 } else {
4083 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4084 TryCall = (FPT->getNumArgs() == 0);
4085 } else {
4086 TryCall = true;
4087 }
4088
4089 if (TryCall) {
4090 QualType ResultTy = Fun->getResultType();
4091 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4092 (IsArrow && ResultTy->isPointerType() &&
4093 ResultTy->getAs<PointerType>()->getPointeeType()->isRecordType());
4094 }
4095 }
4096
4097
4098 if (TryCall) {
Matt Beaumont-Gay956fc1c2011-02-17 02:54:17 +00004099 if (Fun) {
4100 Diag(BaseExpr->getExprLoc(),
4101 diag::err_member_reference_needs_call_zero_arg)
4102 << QualType(Fun, 0)
4103 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4104 }
John McCall68fc88ec2010-12-15 16:46:44 +00004105
4106 ExprResult NewBase
Matt Beaumont-Gay956fc1c2011-02-17 02:54:17 +00004107 = ActOnCallExpr(0, BaseExpr, ParenInsertionLoc,
4108 MultiExprArg(*this, 0, 0), ParenInsertionLoc);
John McCall68fc88ec2010-12-15 16:46:44 +00004109 if (NewBase.isInvalid())
4110 return ExprError();
4111 BaseExpr = NewBase.takeAs<Expr>();
4112
4113
4114 DefaultFunctionArrayConversion(BaseExpr);
4115 BaseType = BaseExpr->getType();
4116
4117 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4118 ObjCImpDecl, HasTemplateArgs);
4119 }
4120 }
4121
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004122 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
4123 << BaseType << BaseExpr->getSourceRange();
4124
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004125 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00004126}
4127
John McCall10eae182009-11-30 22:42:35 +00004128/// The main callback when the parser finds something like
4129/// expression . [nested-name-specifier] identifier
4130/// expression -> [nested-name-specifier] identifier
4131/// where 'identifier' encompasses a fairly broad spectrum of
4132/// possibilities, including destructor and operator references.
4133///
4134/// \param OpKind either tok::arrow or tok::period
4135/// \param HasTrailingLParen whether the next token is '(', which
4136/// is used to diagnose mis-uses of special members that can
4137/// only be called
4138/// \param ObjCImpDecl the current ObjC @implementation decl;
4139/// this is an ugly hack around the fact that ObjC @implementations
4140/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00004141ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00004142 SourceLocation OpLoc,
4143 tok::TokenKind OpKind,
4144 CXXScopeSpec &SS,
4145 UnqualifiedId &Id,
4146 Decl *ObjCImpDecl,
4147 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00004148 if (SS.isSet() && SS.isInvalid())
4149 return ExprError();
4150
Francois Pichet64225792011-01-18 05:04:39 +00004151 // Warn about the explicit constructor calls Microsoft extension.
4152 if (getLangOptions().Microsoft &&
4153 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4154 Diag(Id.getSourceRange().getBegin(),
4155 diag::ext_ms_explicit_constructor_call);
4156
John McCall10eae182009-11-30 22:42:35 +00004157 TemplateArgumentListInfo TemplateArgsBuffer;
4158
4159 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004160 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00004161 const TemplateArgumentListInfo *TemplateArgs;
4162 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004163 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004164
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004165 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00004166 bool IsArrow = (OpKind == tok::arrow);
4167
4168 NamedDecl *FirstQualifierInScope
4169 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4170 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4171
4172 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004173 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004174 if (Result.isInvalid()) return ExprError();
4175 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00004176
Douglas Gregor41f90302010-04-12 20:54:26 +00004177 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4178 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00004179 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00004180 IsArrow, OpLoc,
4181 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004182 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004183 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004184 LookupResult R(*this, NameInfo, LookupMemberName);
John McCalle9cccd82010-06-16 08:42:20 +00004185 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
4186 SS, ObjCImpDecl, TemplateArgs != 0);
Alexis Huntc46382e2010-04-28 23:02:27 +00004187
John McCalle9cccd82010-06-16 08:42:20 +00004188 if (Result.isInvalid()) {
4189 Owned(Base);
4190 return ExprError();
4191 }
John McCall10eae182009-11-30 22:42:35 +00004192
John McCalle9cccd82010-06-16 08:42:20 +00004193 if (Result.get()) {
4194 // The only way a reference to a destructor can be used is to
4195 // immediately call it, which falls into this case. If the
4196 // next token is not a '(', produce a diagnostic and build the
4197 // call now.
4198 if (!HasTrailingLParen &&
4199 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00004200 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00004201
John McCalle9cccd82010-06-16 08:42:20 +00004202 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00004203 }
4204
John McCallb268a282010-08-23 23:25:46 +00004205 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00004206 OpLoc, IsArrow, SS, FirstQualifierInScope,
4207 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004208 }
4209
4210 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00004211}
4212
John McCalldadc5752010-08-24 06:29:42 +00004213ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004214 FunctionDecl *FD,
4215 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004216 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004217 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004218 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004219 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004220 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004221 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004222 return ExprError();
4223 }
4224
4225 if (Param->hasUninstantiatedDefaultArg()) {
4226 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004227
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004228 // Instantiate the expression.
4229 MultiLevelTemplateArgumentList ArgList
4230 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004231
Nico Weber44887f62010-11-29 18:19:25 +00004232 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004233 = ArgList.getInnermost();
4234 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4235 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00004236
Nico Weber44887f62010-11-29 18:19:25 +00004237 ExprResult Result;
4238 {
4239 // C++ [dcl.fct.default]p5:
4240 // The names in the [default argument] expression are bound, and
4241 // the semantic constraints are checked, at the point where the
4242 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004243 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004244 Result = SubstExpr(UninstExpr, ArgList);
4245 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004246 if (Result.isInvalid())
4247 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004248
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004249 // Check the expression as an initializer for the parameter.
4250 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004251 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004252 InitializationKind Kind
4253 = InitializationKind::CreateCopy(Param->getLocation(),
4254 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4255 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004256
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004257 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4258 Result = InitSeq.Perform(*this, Entity, Kind,
4259 MultiExprArg(*this, &ResultE, 1));
4260 if (Result.isInvalid())
4261 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004262
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004263 // Build the default argument expression.
4264 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4265 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004266 }
4267
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004268 // If the default expression creates temporaries, we need to
4269 // push them to the current stack of expression temporaries so they'll
4270 // be properly destroyed.
4271 // FIXME: We should really be rebuilding the default argument with new
4272 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004273 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4274 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4275 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4276 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4277 ExprTemporaries.push_back(Temporary);
4278 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004279
4280 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004281 // Just mark all of the declarations in this potentially-evaluated expression
4282 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004283 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004284 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004285}
4286
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004287/// ConvertArgumentsForCall - Converts the arguments specified in
4288/// Args/NumArgs to the parameter types of the function FDecl with
4289/// function prototype Proto. Call is the call expression itself, and
4290/// Fn is the function expression. For a C++ member function, this
4291/// routine does not attempt to convert the object argument. Returns
4292/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004293bool
4294Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004295 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004296 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004297 Expr **Args, unsigned NumArgs,
4298 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004299 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004300 // assignment, to the types of the corresponding parameter, ...
4301 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004302 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004303
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004304 // If too few arguments are available (and we don't have default
4305 // arguments for the remaining parameters), don't make the call.
4306 if (NumArgs < NumArgsInProto) {
4307 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4308 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004309 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004310 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004311 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004312 }
4313
4314 // If too many are passed and not variadic, error on the extras and drop
4315 // them.
4316 if (NumArgs > NumArgsInProto) {
4317 if (!Proto->isVariadic()) {
4318 Diag(Args[NumArgsInProto]->getLocStart(),
4319 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004320 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004321 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004322 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4323 Args[NumArgs-1]->getLocEnd());
4324 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004325 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004326 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004327 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004328 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004329 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004330 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004331 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4332 if (Fn->getType()->isBlockPointerType())
4333 CallType = VariadicBlock; // Block
4334 else if (isa<MemberExpr>(Fn))
4335 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004336 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004337 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004338 if (Invalid)
4339 return true;
4340 unsigned TotalNumArgs = AllArgs.size();
4341 for (unsigned i = 0; i < TotalNumArgs; ++i)
4342 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004343
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004344 return false;
4345}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004346
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004347bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4348 FunctionDecl *FDecl,
4349 const FunctionProtoType *Proto,
4350 unsigned FirstProtoArg,
4351 Expr **Args, unsigned NumArgs,
4352 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004353 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004354 unsigned NumArgsInProto = Proto->getNumArgs();
4355 unsigned NumArgsToCheck = NumArgs;
4356 bool Invalid = false;
4357 if (NumArgs != NumArgsInProto)
4358 // Use default arguments for missing arguments
4359 NumArgsToCheck = NumArgsInProto;
4360 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004361 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004362 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004363 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004364
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004365 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004366 if (ArgIx < NumArgs) {
4367 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004368
Eli Friedman3164fb12009-03-22 22:00:50 +00004369 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4370 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004371 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004372 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004373 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004374
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004375 // Pass the argument
4376 ParmVarDecl *Param = 0;
4377 if (FDecl && i < FDecl->getNumParams())
4378 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004379
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004380 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004381 Param? InitializedEntity::InitializeParameter(Context, Param)
4382 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004383 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004384 SourceLocation(),
4385 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004386 if (ArgE.isInvalid())
4387 return true;
4388
4389 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004390 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004391 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004392
John McCalldadc5752010-08-24 06:29:42 +00004393 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004394 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004395 if (ArgExpr.isInvalid())
4396 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004397
Anders Carlsson355933d2009-08-25 03:49:14 +00004398 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004399 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004400 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004401 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004402
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004403 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004404 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004405 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004406 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004407 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004408 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004409 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004410 }
4411 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004412 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004413}
4414
Steve Naroff83895f72007-09-16 03:34:24 +00004415/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004416/// This provides the location of the left/right parens and a list of comma
4417/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004418ExprResult
John McCallb268a282010-08-23 23:25:46 +00004419Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004420 MultiExprArg args, SourceLocation RParenLoc,
4421 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004422 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004423
4424 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004425 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004426 if (Result.isInvalid()) return ExprError();
4427 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004428
John McCallb268a282010-08-23 23:25:46 +00004429 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004430
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004431 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004432 // If this is a pseudo-destructor expression, build the call immediately.
4433 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4434 if (NumArgs > 0) {
4435 // Pseudo-destructor calls should not have any arguments.
4436 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004437 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004438 SourceRange(Args[0]->getLocStart(),
4439 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004440
Douglas Gregorad8a3362009-09-04 17:36:40 +00004441 NumArgs = 0;
4442 }
Mike Stump11289f42009-09-09 15:08:12 +00004443
Douglas Gregorad8a3362009-09-04 17:36:40 +00004444 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004445 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004446 }
Mike Stump11289f42009-09-09 15:08:12 +00004447
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004448 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004449 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004450 // FIXME: Will need to cache the results of name lookup (including ADL) in
4451 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004452 bool Dependent = false;
4453 if (Fn->isTypeDependent())
4454 Dependent = true;
4455 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4456 Dependent = true;
4457
Peter Collingbourne41f85462011-02-09 21:07:24 +00004458 if (Dependent) {
4459 if (ExecConfig) {
4460 return Owned(new (Context) CUDAKernelCallExpr(
4461 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4462 Context.DependentTy, VK_RValue, RParenLoc));
4463 } else {
4464 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4465 Context.DependentTy, VK_RValue,
4466 RParenLoc));
4467 }
4468 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004469
4470 // Determine whether this is a call to an object (C++ [over.call.object]).
4471 if (Fn->getType()->isRecordType())
4472 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004473 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004474
John McCall10eae182009-11-30 22:42:35 +00004475 Expr *NakedFn = Fn->IgnoreParens();
4476
4477 // Determine whether this is a call to an unresolved member function.
4478 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4479 // If lookup was unresolved but not dependent (i.e. didn't find
4480 // an unresolved using declaration), it has to be an overloaded
4481 // function set, which means it must contain either multiple
4482 // declarations (all methods or method templates) or a single
4483 // method template.
4484 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00004485 isa<FunctionTemplateDecl>(
4486 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00004487 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00004488
John McCall2d74de92009-12-01 22:10:20 +00004489 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004490 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004491 }
4492
Douglas Gregore254f902009-02-04 00:32:51 +00004493 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00004494 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004495 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00004496 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00004497 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004498 RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004499 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004500
Anders Carlsson61914b52009-10-03 17:40:22 +00004501 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00004502 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCalle3027922010-08-25 11:45:40 +00004503 if (BO->getOpcode() == BO_PtrMemD ||
4504 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00004505 if (const FunctionProtoType *FPT
4506 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004507 QualType ResultTy = FPT->getCallResultType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004508 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004509
Douglas Gregor125fa402011-02-04 12:57:49 +00004510 // Check that the object type isn't more qualified than the
4511 // member function we're calling.
4512 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4513 Qualifiers ObjectQuals
4514 = BO->getOpcode() == BO_PtrMemD
4515 ? BO->getLHS()->getType().getQualifiers()
4516 : BO->getLHS()->getType()->getAs<PointerType>()
4517 ->getPointeeType().getQualifiers();
4518
4519 Qualifiers Difference = ObjectQuals - FuncQuals;
4520 Difference.removeObjCGCAttr();
4521 Difference.removeAddressSpace();
4522 if (Difference) {
4523 std::string QualsString = Difference.getAsString();
4524 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4525 << BO->getType().getUnqualifiedType()
4526 << QualsString
4527 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4528 }
4529
John McCallb268a282010-08-23 23:25:46 +00004530 CXXMemberCallExpr *TheCall
Abramo Bagnara21e9d862010-12-03 21:39:42 +00004531 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCall7decc9e2010-11-18 06:31:45 +00004532 NumArgs, ResultTy, VK,
John McCallb268a282010-08-23 23:25:46 +00004533 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004534
4535 if (CheckCallReturnType(FPT->getResultType(),
4536 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00004537 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004538 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00004539
John McCallb268a282010-08-23 23:25:46 +00004540 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004541 RParenLoc))
4542 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00004543
John McCallb268a282010-08-23 23:25:46 +00004544 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004545 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004546 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004547 diag::err_typecheck_call_not_function)
4548 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00004549 }
4550 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004551 }
4552
Douglas Gregore254f902009-02-04 00:32:51 +00004553 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004554 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00004555 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004556
Eli Friedmane14b1992009-12-26 03:35:45 +00004557 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004558 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4559 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4560 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004561 RParenLoc, ExecConfig);
Douglas Gregor928479e2010-11-09 20:03:54 +00004562 }
4563
John McCall57500772009-12-16 12:17:52 +00004564 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004565 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4566 if (UnOp->getOpcode() == UO_AddrOf)
4567 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4568
John McCall57500772009-12-16 12:17:52 +00004569 if (isa<DeclRefExpr>(NakedFn))
4570 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4571
Peter Collingbourne41f85462011-02-09 21:07:24 +00004572 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4573 ExecConfig);
4574}
4575
4576ExprResult
4577Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4578 MultiExprArg execConfig, SourceLocation GGGLoc) {
4579 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4580 if (!ConfigDecl)
4581 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4582 << "cudaConfigureCall");
4583 QualType ConfigQTy = ConfigDecl->getType();
4584
4585 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4586 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4587
4588 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00004589}
4590
John McCall57500772009-12-16 12:17:52 +00004591/// BuildResolvedCallExpr - Build a call to a resolved expression,
4592/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004593/// unary-convert to an expression of function-pointer or
4594/// block-pointer type.
4595///
4596/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004597ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004598Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4599 SourceLocation LParenLoc,
4600 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004601 SourceLocation RParenLoc,
4602 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00004603 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4604
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004605 // Promote the function operand.
4606 UsualUnaryConversions(Fn);
4607
Chris Lattner08464942007-12-28 05:29:59 +00004608 // Make the call expr early, before semantic checks. This guarantees cleanup
4609 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00004610 CallExpr *TheCall;
4611 if (Config) {
4612 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4613 cast<CallExpr>(Config),
4614 Args, NumArgs,
4615 Context.BoolTy,
4616 VK_RValue,
4617 RParenLoc);
4618 } else {
4619 TheCall = new (Context) CallExpr(Context, Fn,
4620 Args, NumArgs,
4621 Context.BoolTy,
4622 VK_RValue,
4623 RParenLoc);
4624 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004625
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004626 const FunctionType *FuncT;
4627 if (!Fn->getType()->isBlockPointerType()) {
4628 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4629 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004630 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004631 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004632 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4633 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00004634 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004635 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004636 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00004637 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004638 }
Chris Lattner08464942007-12-28 05:29:59 +00004639 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004640 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4641 << Fn->getType() << Fn->getSourceRange());
4642
Eli Friedman3164fb12009-03-22 22:00:50 +00004643 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004644 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00004645 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004646 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004647 return ExprError();
4648
Chris Lattner08464942007-12-28 05:29:59 +00004649 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004650 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004651 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004652
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004653 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00004654 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004655 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004656 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004657 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004658 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004659
Douglas Gregord8e97de2009-04-02 15:37:10 +00004660 if (FDecl) {
4661 // Check if we have too few/too many template arguments, based
4662 // on our knowledge of the function definition.
4663 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004664 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004665 const FunctionProtoType *Proto
4666 = Def->getType()->getAs<FunctionProtoType>();
4667 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004668 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4669 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004670 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004671
4672 // If the function we're calling isn't a function prototype, but we have
4673 // a function prototype from a prior declaratiom, use that prototype.
4674 if (!FDecl->hasPrototype())
4675 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004676 }
4677
Steve Naroff0b661582007-08-28 23:30:39 +00004678 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004679 for (unsigned i = 0; i != NumArgs; i++) {
4680 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004681
4682 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004683 InitializedEntity Entity
4684 = InitializedEntity::InitializeParameter(Context,
4685 Proto->getArgType(i));
4686 ExprResult ArgE = PerformCopyInitialization(Entity,
4687 SourceLocation(),
4688 Owned(Arg));
4689 if (ArgE.isInvalid())
4690 return true;
4691
4692 Arg = ArgE.takeAs<Expr>();
4693
4694 } else {
4695 DefaultArgumentPromotion(Arg);
Douglas Gregor8e09a722010-10-25 20:39:23 +00004696 }
4697
Douglas Gregor83025412010-10-26 05:45:40 +00004698 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4699 Arg->getType(),
4700 PDiag(diag::err_call_incomplete_argument)
4701 << Arg->getSourceRange()))
4702 return ExprError();
4703
Chris Lattner08464942007-12-28 05:29:59 +00004704 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004705 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004706 }
Chris Lattner08464942007-12-28 05:29:59 +00004707
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004708 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4709 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004710 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4711 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004712
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004713 // Check for sentinels
4714 if (NDecl)
4715 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004716
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004717 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004718 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00004719 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004720 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004721
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004722 if (unsigned BuiltinID = FDecl->getBuiltinID())
4723 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004724 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00004725 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004726 return ExprError();
4727 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004728
John McCallb268a282010-08-23 23:25:46 +00004729 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004730}
4731
John McCalldadc5752010-08-24 06:29:42 +00004732ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004733Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004734 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004735 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004736 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004737 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004738
4739 TypeSourceInfo *TInfo;
4740 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4741 if (!TInfo)
4742 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4743
John McCallb268a282010-08-23 23:25:46 +00004744 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004745}
4746
John McCalldadc5752010-08-24 06:29:42 +00004747ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004748Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00004749 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004750 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004751
Eli Friedman37a186d2008-05-20 05:22:08 +00004752 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004753 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4754 PDiag(diag::err_illegal_decl_array_incomplete_type)
4755 << SourceRange(LParenLoc,
4756 literalExpr->getSourceRange().getEnd())))
4757 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004758 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004759 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4760 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004761 } else if (!literalType->isDependentType() &&
4762 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00004763 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00004764 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00004765 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004766 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004767
Douglas Gregor85dabae2009-12-16 01:38:02 +00004768 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004769 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004770 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004771 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004772 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004773 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004774 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004775 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004776 &literalType);
4777 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004778 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004779 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004780
Chris Lattner79413952008-12-04 23:50:19 +00004781 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004782 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00004783 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004784 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004785 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004786
John McCall7decc9e2010-11-18 06:31:45 +00004787 // In C, compound literals are l-values for some reason.
4788 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4789
John McCall5d7aa7f2010-01-19 22:33:45 +00004790 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00004791 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004792}
4793
John McCalldadc5752010-08-24 06:29:42 +00004794ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00004795Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004796 SourceLocation RBraceLoc) {
4797 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00004798 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004799
Steve Naroff30d242c2007-09-15 18:49:24 +00004800 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004801 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004802
Ted Kremenekac034612010-04-13 23:39:13 +00004803 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4804 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004805 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004806 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004807}
4808
John McCalld7646252010-11-14 08:17:51 +00004809/// Prepares for a scalar cast, performing all the necessary stages
4810/// except the final cast and returning the kind required.
4811static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4812 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4813 // Also, callers should have filtered out the invalid cases with
4814 // pointers. Everything else should be possible.
4815
Abramo Bagnaraba854972011-01-04 09:50:03 +00004816 QualType SrcTy = Src->getType();
John McCalld7646252010-11-14 08:17:51 +00004817 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004818 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004819
John McCall8cb679e2010-11-15 09:13:47 +00004820 switch (SrcTy->getScalarTypeKind()) {
4821 case Type::STK_MemberPointer:
4822 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004823
John McCall8cb679e2010-11-15 09:13:47 +00004824 case Type::STK_Pointer:
4825 switch (DestTy->getScalarTypeKind()) {
4826 case Type::STK_Pointer:
4827 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00004828 CK_AnyPointerToObjCPointerCast :
4829 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00004830 case Type::STK_Bool:
4831 return CK_PointerToBoolean;
4832 case Type::STK_Integral:
4833 return CK_PointerToIntegral;
4834 case Type::STK_Floating:
4835 case Type::STK_FloatingComplex:
4836 case Type::STK_IntegralComplex:
4837 case Type::STK_MemberPointer:
4838 llvm_unreachable("illegal cast from pointer");
4839 }
4840 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004841
John McCall8cb679e2010-11-15 09:13:47 +00004842 case Type::STK_Bool: // casting from bool is like casting from an integer
4843 case Type::STK_Integral:
4844 switch (DestTy->getScalarTypeKind()) {
4845 case Type::STK_Pointer:
John McCalld7646252010-11-14 08:17:51 +00004846 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004847 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004848 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004849 case Type::STK_Bool:
4850 return CK_IntegralToBoolean;
4851 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004852 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004853 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004854 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004855 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004856 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004857 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004858 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004859 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004860 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004861 CK_IntegralToFloating);
4862 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004863 case Type::STK_MemberPointer:
4864 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004865 }
4866 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004867
John McCall8cb679e2010-11-15 09:13:47 +00004868 case Type::STK_Floating:
4869 switch (DestTy->getScalarTypeKind()) {
4870 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004871 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004872 case Type::STK_Bool:
4873 return CK_FloatingToBoolean;
4874 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004875 return CK_FloatingToIntegral;
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 McCallfcef3cf2010-12-14 17:51:41 +00004878 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004879 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004880 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004881 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004882 CK_FloatingToIntegral);
4883 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004884 case Type::STK_Pointer:
4885 llvm_unreachable("valid float->pointer cast?");
4886 case Type::STK_MemberPointer:
4887 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004888 }
4889 break;
4890
John McCall8cb679e2010-11-15 09:13:47 +00004891 case Type::STK_FloatingComplex:
4892 switch (DestTy->getScalarTypeKind()) {
4893 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004894 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004895 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004896 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004897 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004898 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004899 if (S.Context.hasSameType(ET, DestTy))
4900 return CK_FloatingComplexToReal;
4901 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4902 return CK_FloatingCast;
4903 }
John McCall8cb679e2010-11-15 09:13:47 +00004904 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004905 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004906 case Type::STK_Integral:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004907 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004908 CK_FloatingComplexToReal);
4909 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004910 case Type::STK_Pointer:
4911 llvm_unreachable("valid complex float->pointer cast?");
4912 case Type::STK_MemberPointer:
4913 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004914 }
4915 break;
4916
John McCall8cb679e2010-11-15 09:13:47 +00004917 case Type::STK_IntegralComplex:
4918 switch (DestTy->getScalarTypeKind()) {
4919 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004920 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004921 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004922 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004923 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004924 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004925 if (S.Context.hasSameType(ET, DestTy))
4926 return CK_IntegralComplexToReal;
4927 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4928 return CK_IntegralCast;
4929 }
John McCall8cb679e2010-11-15 09:13:47 +00004930 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004931 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004932 case Type::STK_Floating:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004933 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004934 CK_IntegralComplexToReal);
4935 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004936 case Type::STK_Pointer:
4937 llvm_unreachable("valid complex int->pointer cast?");
4938 case Type::STK_MemberPointer:
4939 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004940 }
4941 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004942 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004943
John McCalld7646252010-11-14 08:17:51 +00004944 llvm_unreachable("Unhandled scalar cast");
4945 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00004946}
4947
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004948/// CheckCastTypes - Check type constraints for casting between types.
John McCall7decc9e2010-11-18 06:31:45 +00004949bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4950 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4951 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00004952 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00004953 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4954 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00004955 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00004956 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00004957
John McCall7decc9e2010-11-18 06:31:45 +00004958 // We only support r-value casts in C.
4959 VK = VK_RValue;
4960
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004961 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4962 // type needs to be scalar.
4963 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004964 // We don't necessarily do lvalue-to-rvalue conversions on this.
4965 IgnoredValueConversions(castExpr);
4966
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004967 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004968 Kind = CK_ToVoid;
Anders Carlssonef918ac2009-10-16 02:35:04 +00004969 return false;
4970 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004971
John McCall34376a62010-12-04 03:47:34 +00004972 DefaultFunctionArrayLvalueConversion(castExpr);
4973
Eli Friedmane98194d2010-07-17 20:43:49 +00004974 if (RequireCompleteType(TyR.getBegin(), castType,
4975 diag::err_typecheck_cast_to_incomplete))
4976 return true;
4977
Anders Carlssonef918ac2009-10-16 02:35:04 +00004978 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004979 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004980 (castType->isStructureType() || castType->isUnionType())) {
4981 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004982 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004983 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4984 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004985 Kind = CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00004986 return false;
4987 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004988
Anders Carlsson525b76b2009-10-16 02:48:28 +00004989 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004990 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004991 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004992 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004993 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004994 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004995 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004996 castExpr->getType()) &&
4997 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004998 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4999 << castExpr->getSourceRange();
5000 break;
5001 }
5002 }
5003 if (Field == FieldEnd)
5004 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
5005 << castExpr->getType() << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005006 Kind = CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00005007 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005008 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005009
Anders Carlsson525b76b2009-10-16 02:48:28 +00005010 // Reject any other conversions to non-scalar types.
5011 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
5012 << castType << castExpr->getSourceRange();
5013 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005014
John McCalld7646252010-11-14 08:17:51 +00005015 // The type we're casting to is known to be a scalar or vector.
5016
5017 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005018 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00005019 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00005020 return Diag(castExpr->getLocStart(),
5021 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005022 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005023 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005024
5025 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00005026 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005027
Anders Carlsson525b76b2009-10-16 02:48:28 +00005028 if (castType->isVectorType())
5029 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
5030 if (castExpr->getType()->isVectorType())
5031 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
5032
John McCalld7646252010-11-14 08:17:51 +00005033 // The source and target types are both scalars, i.e.
5034 // - arithmetic types (fundamental, enum, and complex)
5035 // - all kinds of pointers
5036 // Note that member pointers were filtered out with C++, above.
5037
Anders Carlsson43d70f82009-10-16 05:23:41 +00005038 if (isa<ObjCSelectorExpr>(castExpr))
5039 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005040
John McCalld7646252010-11-14 08:17:51 +00005041 // If either type is a pointer, the other type has to be either an
5042 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00005043 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005044 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005045 if (!castExprType->isIntegralType(Context) &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005046 castExprType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005047 return Diag(castExpr->getLocStart(),
5048 diag::err_cast_pointer_from_non_pointer_int)
5049 << castExprType << castExpr->getSourceRange();
5050 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00005051 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005052 return Diag(castExpr->getLocStart(),
5053 diag::err_cast_pointer_to_non_pointer_int)
5054 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005055 }
Anders Carlsson094c4592009-10-18 18:12:03 +00005056
John McCalld7646252010-11-14 08:17:51 +00005057 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCall2b5c1b22010-08-12 21:44:57 +00005058
John McCalld7646252010-11-14 08:17:51 +00005059 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00005060 CheckCastAlign(castExpr, castType, TyR);
5061
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005062 return false;
5063}
5064
Anders Carlsson525b76b2009-10-16 02:48:28 +00005065bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005066 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005067 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005068
Anders Carlssonde71adf2007-11-27 05:51:55 +00005069 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00005070 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005071 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005072 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005073 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005074 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005075 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005076 } else
5077 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005078 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005079 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005080
John McCalle3027922010-08-25 11:45:40 +00005081 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005082 return false;
5083}
5084
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005085bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCalle3027922010-08-25 11:45:40 +00005086 CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005087 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005088
Anders Carlsson43d70f82009-10-16 05:23:41 +00005089 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005090
Nate Begemanc8961a42009-06-27 22:05:55 +00005091 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5092 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00005093 if (SrcTy->isVectorType()) {
5094 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
5095 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5096 << DestTy << SrcTy << R;
John McCalle3027922010-08-25 11:45:40 +00005097 Kind = CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00005098 return false;
5099 }
5100
Nate Begemanbd956c42009-06-28 02:36:38 +00005101 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00005102 // conversion will take place first from scalar to elt type, and then
5103 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00005104 if (SrcTy->isPointerType())
5105 return Diag(R.getBegin(),
5106 diag::err_invalid_conversion_between_vector_and_scalar)
5107 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00005108
5109 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5110 ImpCastExprToType(CastExpr, DestElemTy,
John McCalld7646252010-11-14 08:17:51 +00005111 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005112
John McCalle3027922010-08-25 11:45:40 +00005113 Kind = CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00005114 return false;
5115}
5116
John McCalldadc5752010-08-24 06:29:42 +00005117ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005118Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005119 SourceLocation RParenLoc, Expr *castExpr) {
5120 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00005121 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00005122
John McCall97513962010-01-15 18:39:57 +00005123 TypeSourceInfo *castTInfo;
5124 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5125 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00005126 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00005127
Nate Begeman5ec4b312009-08-10 23:49:36 +00005128 // If the Expr being casted is a ParenListExpr, handle it specially.
5129 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00005130 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00005131 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00005132
John McCallb268a282010-08-23 23:25:46 +00005133 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00005134}
5135
John McCalldadc5752010-08-24 06:29:42 +00005136ExprResult
John McCallebe54742010-01-15 18:56:44 +00005137Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00005138 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00005139 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00005140 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00005141 CXXCastPath BasePath;
John McCallebe54742010-01-15 18:56:44 +00005142 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCall7decc9e2010-11-18 06:31:45 +00005143 Kind, VK, BasePath))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005144 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00005145
John McCallcf142162010-08-07 06:22:56 +00005146 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +00005147 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00005148 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00005149 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00005150}
5151
Nate Begeman5ec4b312009-08-10 23:49:36 +00005152/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5153/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005154ExprResult
John McCallb268a282010-08-23 23:25:46 +00005155Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005156 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5157 if (!E)
5158 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00005159
John McCalldadc5752010-08-24 06:29:42 +00005160 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005161
Nate Begeman5ec4b312009-08-10 23:49:36 +00005162 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005163 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5164 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005165
John McCallb268a282010-08-23 23:25:46 +00005166 if (Result.isInvalid()) return ExprError();
5167
5168 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005169}
5170
John McCalldadc5752010-08-24 06:29:42 +00005171ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00005172Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00005173 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00005174 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00005175 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00005176 QualType Ty = TInfo->getType();
John Thompson781ad172010-06-30 22:55:51 +00005177 bool isAltiVecLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00005178
John Thompson781ad172010-06-30 22:55:51 +00005179 // Check for an altivec literal,
5180 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005181 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5182 if (PE->getNumExprs() == 0) {
5183 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5184 return ExprError();
5185 }
John Thompson781ad172010-06-30 22:55:51 +00005186 if (PE->getNumExprs() == 1) {
5187 if (!PE->getExpr(0)->getType()->isVectorType())
5188 isAltiVecLiteral = true;
5189 }
5190 else
5191 isAltiVecLiteral = true;
5192 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00005193
John Thompson781ad172010-06-30 22:55:51 +00005194 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
5195 // then handle it as such.
5196 if (isAltiVecLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005197 llvm::SmallVector<Expr *, 8> initExprs;
5198 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5199 initExprs.push_back(PE->getExpr(i));
5200
5201 // FIXME: This means that pretty-printing the final AST will produce curly
5202 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00005203 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5204 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00005205 initExprs.size(), RParenLoc);
5206 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00005207 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005208 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005209 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00005210 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00005211 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00005212 if (Result.isInvalid()) return ExprError();
5213 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005214 }
5215}
5216
John McCalldadc5752010-08-24 06:29:42 +00005217ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00005218 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005219 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00005220 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005221 unsigned nexprs = Val.size();
5222 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005223 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5224 Expr *expr;
5225 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5226 expr = new (Context) ParenExpr(L, R, exprs[0]);
5227 else
5228 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005229 return Owned(expr);
5230}
5231
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005232/// \brief Emit a specialized diagnostic when one expression is a null pointer
5233/// constant and the other is not a pointer.
5234bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5235 SourceLocation QuestionLoc) {
5236 Expr *NullExpr = LHS;
5237 Expr *NonPointerExpr = RHS;
5238 Expr::NullPointerConstantKind NullKind =
5239 NullExpr->isNullPointerConstant(Context,
5240 Expr::NPC_ValueDependentIsNotNull);
5241
5242 if (NullKind == Expr::NPCK_NotNull) {
5243 NullExpr = RHS;
5244 NonPointerExpr = LHS;
5245 NullKind =
5246 NullExpr->isNullPointerConstant(Context,
5247 Expr::NPC_ValueDependentIsNotNull);
5248 }
5249
5250 if (NullKind == Expr::NPCK_NotNull)
5251 return false;
5252
5253 if (NullKind == Expr::NPCK_ZeroInteger) {
5254 // In this case, check to make sure that we got here from a "NULL"
5255 // string in the source code.
5256 NullExpr = NullExpr->IgnoreParenImpCasts();
5257 SourceManager& SM = Context.getSourceManager();
5258 SourceLocation Loc = SM.getInstantiationLoc(NullExpr->getExprLoc());
5259 unsigned Len =
5260 Lexer::MeasureTokenLength(Loc, SM, Context.getLangOptions());
5261 if (Len != 4 || memcmp(SM.getCharacterData(Loc), "NULL", 4))
5262 return false;
5263 }
5264
5265 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5266 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5267 << NonPointerExpr->getType() << DiagType
5268 << NonPointerExpr->getSourceRange();
5269 return true;
5270}
5271
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005272/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5273/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00005274/// C99 6.5.15
5275QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005276 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00005277 SourceLocation QuestionLoc) {
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005278 // If both LHS and RHS are overloaded functions, try to resolve them.
5279 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
5280 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
5281 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
5282 if (LHSResult.isInvalid())
5283 return QualType();
5284
5285 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
5286 if (RHSResult.isInvalid())
5287 return QualType();
5288
5289 LHS = LHSResult.take();
5290 RHS = RHSResult.take();
5291 }
5292
Sebastian Redl1a99f442009-04-16 17:51:27 +00005293 // C++ is sufficiently different to merit its own checker.
5294 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00005295 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00005296
5297 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005298 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005299
Chris Lattner432cff52009-02-18 04:28:32 +00005300 UsualUnaryConversions(Cond);
John McCallc07a0c72011-02-17 10:25:35 +00005301 UsualUnaryConversions(LHS);
Chris Lattner432cff52009-02-18 04:28:32 +00005302 UsualUnaryConversions(RHS);
5303 QualType CondTy = Cond->getType();
5304 QualType LHSTy = LHS->getType();
5305 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00005306
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005307 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005308 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00005309 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5310 // Throw an error if its not either.
5311 if (getLangOptions().OpenCL) {
5312 if (!CondTy->isVectorType()) {
5313 Diag(Cond->getLocStart(),
5314 diag::err_typecheck_cond_expect_scalar_or_vector)
5315 << CondTy;
5316 return QualType();
5317 }
5318 }
5319 else {
5320 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5321 << CondTy;
5322 return QualType();
5323 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005324 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005325
Chris Lattnere2949f42008-01-06 22:42:25 +00005326 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005327 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5328 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00005329
Nate Begemanabb5a732010-09-20 22:41:17 +00005330 // OpenCL: If the condition is a vector, and both operands are scalar,
5331 // attempt to implicity convert them to the vector type to act like the
5332 // built in select.
5333 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5334 // Both operands should be of scalar type.
5335 if (!LHSTy->isScalarType()) {
5336 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5337 << CondTy;
5338 return QualType();
5339 }
5340 if (!RHSTy->isScalarType()) {
5341 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5342 << CondTy;
5343 return QualType();
5344 }
5345 // Implicity convert these scalars to the type of the condition.
5346 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5347 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5348 }
5349
Chris Lattnere2949f42008-01-06 22:42:25 +00005350 // If both operands have arithmetic type, do the usual arithmetic conversions
5351 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005352 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5353 UsualArithmeticConversions(LHS, RHS);
5354 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005355 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005356
Chris Lattnere2949f42008-01-06 22:42:25 +00005357 // If both operands are the same structure or union type, the result is that
5358 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005359 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5360 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005361 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005362 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005363 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005364 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005365 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005366 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005367
Chris Lattnere2949f42008-01-06 22:42:25 +00005368 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005369 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005370 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5371 if (!LHSTy->isVoidType())
5372 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5373 << RHS->getSourceRange();
5374 if (!RHSTy->isVoidType())
5375 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5376 << LHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005377 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5378 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005379 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005380 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005381 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5382 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005383 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005384 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005385 // promote the null to a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005386 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005387 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005388 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005389 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005390 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00005391 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005392 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005393 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005394
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005395 // All objective-c pointer type analysis is done here.
5396 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5397 QuestionLoc);
5398 if (!compositeType.isNull())
5399 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005400
5401
Steve Naroff05efa972009-07-01 14:36:47 +00005402 // Handle block pointer types.
5403 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5404 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5405 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5406 QualType destType = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005407 ImpCastExprToType(LHS, destType, CK_BitCast);
5408 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005409 return destType;
5410 }
5411 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005412 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005413 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005414 }
Steve Naroff05efa972009-07-01 14:36:47 +00005415 // We have 2 block pointer types.
5416 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5417 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005418 return LHSTy;
5419 }
Steve Naroff05efa972009-07-01 14:36:47 +00005420 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005421 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5422 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005423
Steve Naroff05efa972009-07-01 14:36:47 +00005424 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5425 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005426 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005427 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005428 // In this situation, we assume void* type. No especially good
5429 // reason, but this is what gcc does, and we do have to pick
5430 // to get a consistent AST.
5431 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005432 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5433 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005434 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005435 }
Steve Naroff05efa972009-07-01 14:36:47 +00005436 // The block pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005437 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5438 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005439 return LHSTy;
5440 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005441
Steve Naroff05efa972009-07-01 14:36:47 +00005442 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5443 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5444 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005445 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5446 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005447
5448 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5449 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5450 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005451 QualType destPointee
5452 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005453 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005454 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005455 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005456 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005457 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005458 return destType;
5459 }
5460 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005461 QualType destPointee
5462 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005463 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005464 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005465 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005466 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005467 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005468 return destType;
5469 }
5470
5471 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5472 // Two identical pointer types are always compatible.
5473 return LHSTy;
5474 }
5475 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5476 rhptee.getUnqualifiedType())) {
5477 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5478 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5479 // In this situation, we assume void* type. No especially good
5480 // reason, but this is what gcc does, and we do have to pick
5481 // to get a consistent AST.
5482 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005483 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5484 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005485 return incompatTy;
5486 }
5487 // The pointer types are compatible.
5488 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5489 // differently qualified versions of compatible types, the result type is
5490 // a pointer to an appropriately qualified version of the *composite*
5491 // type.
5492 // FIXME: Need to calculate the composite type.
5493 // FIXME: Need to add qualifiers
John McCalle3027922010-08-25 11:45:40 +00005494 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5495 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005496 return LHSTy;
5497 }
Mike Stump11289f42009-09-09 15:08:12 +00005498
John McCalle84af4e2010-11-13 01:35:44 +00005499 // GCC compatibility: soften pointer/integer mismatch. Note that
5500 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005501 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5502 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5503 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005504 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005505 return RHSTy;
5506 }
5507 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5508 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5509 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005510 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005511 return LHSTy;
5512 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005513
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005514 // Emit a better diagnostic if one of the expressions is a null pointer
5515 // constant and the other is not a pointer type. In this case, the user most
5516 // likely forgot to take the address of the other expression.
5517 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
5518 return QualType();
5519
Chris Lattnere2949f42008-01-06 22:42:25 +00005520 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005521 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5522 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005523 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005524}
5525
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005526/// FindCompositeObjCPointerType - Helper method to find composite type of
5527/// two objective-c pointer types of the two input expressions.
5528QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5529 SourceLocation QuestionLoc) {
5530 QualType LHSTy = LHS->getType();
5531 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005532
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005533 // Handle things like Class and struct objc_class*. Here we case the result
5534 // to the pseudo-builtin, because that will be implicitly cast back to the
5535 // redefinition type if an attempt is made to access its fields.
5536 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005537 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005538 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005539 return LHSTy;
5540 }
5541 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005542 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005543 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005544 return RHSTy;
5545 }
5546 // And the same for struct objc_object* / id
5547 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005548 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005549 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005550 return LHSTy;
5551 }
5552 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005553 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005554 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005555 return RHSTy;
5556 }
5557 // And the same for struct objc_selector* / SEL
5558 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005559 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005560 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005561 return LHSTy;
5562 }
5563 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005564 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005565 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005566 return RHSTy;
5567 }
5568 // Check constraints for Objective-C object pointers types.
5569 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005570
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005571 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5572 // Two identical object pointer types are always compatible.
5573 return LHSTy;
5574 }
5575 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5576 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5577 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005578
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005579 // If both operands are interfaces and either operand can be
5580 // assigned to the other, use that type as the composite
5581 // type. This allows
5582 // xxx ? (A*) a : (B*) b
5583 // where B is a subclass of A.
5584 //
5585 // Additionally, as for assignment, if either type is 'id'
5586 // allow silent coercion. Finally, if the types are
5587 // incompatible then make sure to use 'id' as the composite
5588 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005589
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005590 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5591 // It could return the composite type.
5592 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5593 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5594 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5595 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5596 } else if ((LHSTy->isObjCQualifiedIdType() ||
5597 RHSTy->isObjCQualifiedIdType()) &&
5598 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5599 // Need to handle "id<xx>" explicitly.
5600 // GCC allows qualified id and any Objective-C type to devolve to
5601 // id. Currently localizing to here until clear this should be
5602 // part of ObjCQualifiedIdTypesAreCompatible.
5603 compositeType = Context.getObjCIdType();
5604 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5605 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005606 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005607 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5608 ;
5609 else {
5610 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5611 << LHSTy << RHSTy
5612 << LHS->getSourceRange() << RHS->getSourceRange();
5613 QualType incompatTy = Context.getObjCIdType();
John McCalle3027922010-08-25 11:45:40 +00005614 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5615 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005616 return incompatTy;
5617 }
5618 // The object pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005619 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5620 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005621 return compositeType;
5622 }
5623 // Check Objective-C object pointer types and 'void *'
5624 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5625 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5626 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5627 QualType destPointee
5628 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5629 QualType destType = Context.getPointerType(destPointee);
5630 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005631 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005632 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005633 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005634 return destType;
5635 }
5636 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5637 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5638 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5639 QualType destPointee
5640 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5641 QualType destType = Context.getPointerType(destPointee);
5642 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005643 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005644 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005645 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005646 return destType;
5647 }
5648 return QualType();
5649}
5650
Steve Naroff83895f72007-09-16 03:34:24 +00005651/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005652/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005653ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005654 SourceLocation ColonLoc,
5655 Expr *CondExpr, Expr *LHSExpr,
5656 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005657 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5658 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005659 OpaqueValueExpr *opaqueValue = 0;
5660 Expr *commonExpr = 0;
5661 if (LHSExpr == 0) {
5662 commonExpr = CondExpr;
5663
5664 // We usually want to apply unary conversions *before* saving, except
5665 // in the special case of a C++ l-value conditional.
5666 if (!(getLangOptions().CPlusPlus
5667 && !commonExpr->isTypeDependent()
5668 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5669 && commonExpr->isGLValue()
5670 && commonExpr->isOrdinaryOrBitFieldObject()
5671 && RHSExpr->isOrdinaryOrBitFieldObject()
5672 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5673 UsualUnaryConversions(commonExpr);
5674 }
5675
5676 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5677 commonExpr->getType(),
5678 commonExpr->getValueKind(),
5679 commonExpr->getObjectKind());
5680 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005681 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005682
John McCall7decc9e2010-11-18 06:31:45 +00005683 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005684 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00005685 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCallc07a0c72011-02-17 10:25:35 +00005686 VK, OK, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00005687 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005688 return ExprError();
5689
John McCallc07a0c72011-02-17 10:25:35 +00005690 if (!commonExpr)
5691 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
5692 LHSExpr, ColonLoc,
5693 RHSExpr, result, VK, OK));
5694
5695 return Owned(new (Context)
5696 BinaryConditionalOperator(commonExpr, opaqueValue, CondExpr, LHSExpr,
5697 RHSExpr, QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005698}
5699
John McCallaba90822011-01-31 23:13:11 +00005700// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005701// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005702// routine is it effectively iqnores the qualifiers on the top level pointee.
5703// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5704// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005705static Sema::AssignConvertType
5706checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5707 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5708 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005709
Steve Naroff1f4d7272007-05-11 04:00:31 +00005710 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005711 const Type *lhptee, *rhptee;
5712 Qualifiers lhq, rhq;
5713 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5714 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005715
John McCallaba90822011-01-31 23:13:11 +00005716 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005717
5718 // C99 6.5.16.1p1: This following citation is common to constraints
5719 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5720 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005721 Qualifiers lq;
5722
5723 if (!lhq.compatiblyIncludes(rhq)) {
5724 // Treat address-space mismatches as fatal. TODO: address subspaces
5725 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5726 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5727
5728 // For GCC compatibility, other qualifier mismatches are treated
5729 // as still compatible in C.
5730 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5731 }
Steve Naroff3f597292007-05-11 22:18:03 +00005732
Mike Stump4e1f26a2009-02-19 03:04:26 +00005733 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5734 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005735 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005736 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005737 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005738 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005739
Chris Lattner0a788432008-01-03 22:56:36 +00005740 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005741 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005742 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005743 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005744
Chris Lattner0a788432008-01-03 22:56:36 +00005745 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005746 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005747 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005748
5749 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005750 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005751 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005752 }
John McCall4fff8f62011-02-01 00:10:29 +00005753
Mike Stump4e1f26a2009-02-19 03:04:26 +00005754 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005755 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005756 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5757 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005758 // Check if the pointee types are compatible ignoring the sign.
5759 // We explicitly check for char so that we catch "char" vs
5760 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005761 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005762 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005763 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005764 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005765
Chris Lattnerec3a1562009-10-17 20:33:28 +00005766 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005767 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005768 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005769 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005770
John McCall4fff8f62011-02-01 00:10:29 +00005771 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005772 // Types are compatible ignoring the sign. Qualifier incompatibility
5773 // takes priority over sign incompatibility because the sign
5774 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005775 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005776 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005777
John McCallaba90822011-01-31 23:13:11 +00005778 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005779 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005780
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005781 // If we are a multi-level pointer, it's possible that our issue is simply
5782 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5783 // the eventual target type is the same and the pointers have the same
5784 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005785 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005786 do {
John McCall4fff8f62011-02-01 00:10:29 +00005787 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5788 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005789 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005790
John McCall4fff8f62011-02-01 00:10:29 +00005791 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005792 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005793 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005794
Eli Friedman80160bd2009-03-22 23:59:44 +00005795 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005796 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005797 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005798 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005799}
5800
John McCallaba90822011-01-31 23:13:11 +00005801/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005802/// block pointer types are compatible or whether a block and normal pointer
5803/// are compatible. It is more restrict than comparing two function pointer
5804// types.
John McCallaba90822011-01-31 23:13:11 +00005805static Sema::AssignConvertType
5806checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5807 QualType rhsType) {
5808 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5809 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5810
Steve Naroff081c7422008-09-04 15:10:53 +00005811 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005812
Steve Naroff081c7422008-09-04 15:10:53 +00005813 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005814 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5815 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005816
John McCallaba90822011-01-31 23:13:11 +00005817 // In C++, the types have to match exactly.
5818 if (S.getLangOptions().CPlusPlus)
5819 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005820
John McCallaba90822011-01-31 23:13:11 +00005821 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005822
Steve Naroff081c7422008-09-04 15:10:53 +00005823 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005824 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5825 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005826
John McCallaba90822011-01-31 23:13:11 +00005827 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5828 return Sema::IncompatibleBlockPointer;
5829
Steve Naroff081c7422008-09-04 15:10:53 +00005830 return ConvTy;
5831}
5832
John McCallaba90822011-01-31 23:13:11 +00005833/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005834/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005835static Sema::AssignConvertType
5836checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5837 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5838 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5839
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005840 if (lhsType->isObjCBuiltinType()) {
5841 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005842 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5843 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005844 return Sema::IncompatiblePointer;
5845 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005846 }
5847 if (rhsType->isObjCBuiltinType()) {
5848 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005849 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5850 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005851 return Sema::IncompatiblePointer;
5852 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005853 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005854 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005855 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005856 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005857 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005858
John McCallaba90822011-01-31 23:13:11 +00005859 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5860 return Sema::CompatiblePointerDiscardsQualifiers;
5861
5862 if (S.Context.typesAreCompatible(lhsType, rhsType))
5863 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005864 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005865 return Sema::IncompatibleObjCQualifiedId;
5866 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005867}
5868
John McCall29600e12010-11-16 02:32:08 +00005869Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005870Sema::CheckAssignmentConstraints(SourceLocation Loc,
5871 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005872 // Fake up an opaque expression. We don't actually care about what
5873 // cast operations are required, so if CheckAssignmentConstraints
5874 // adds casts to this they'll be wasted, but fortunately that doesn't
5875 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00005876 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John McCall29600e12010-11-16 02:32:08 +00005877 Expr *rhsPtr = &rhs;
5878 CastKind K = CK_Invalid;
5879
5880 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5881}
5882
Mike Stump4e1f26a2009-02-19 03:04:26 +00005883/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5884/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005885/// pointers. Here are some objectionable examples that GCC considers warnings:
5886///
5887/// int a, *pint;
5888/// short *pshort;
5889/// struct foo *pfoo;
5890///
5891/// pint = pshort; // warning: assignment from incompatible pointer type
5892/// a = pint; // warning: assignment makes integer from pointer without a cast
5893/// pint = a; // warning: assignment makes pointer from integer without a cast
5894/// pint = pfoo; // warning: assignment from incompatible pointer type
5895///
5896/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005897/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005898///
John McCall8cb679e2010-11-15 09:13:47 +00005899/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005900Sema::AssignConvertType
John McCall29600e12010-11-16 02:32:08 +00005901Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005902 CastKind &Kind) {
John McCall29600e12010-11-16 02:32:08 +00005903 QualType rhsType = rhs->getType();
5904
Chris Lattnera52c2f22008-01-04 23:18:45 +00005905 // Get canonical types. We're not formatting these types, just comparing
5906 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005907 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5908 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005909
John McCalle5255932011-01-31 22:28:28 +00005910 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00005911 if (lhsType == rhsType) {
5912 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005913 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005914 }
5915
Douglas Gregor6b754842008-10-28 00:22:11 +00005916 // If the left-hand side is a reference type, then we are in a
5917 // (rare!) case where we've allowed the use of references in C,
5918 // e.g., as a parameter type in a built-in function. In this case,
5919 // just make sure that the type referenced is compatible with the
5920 // right-hand side type. The caller is responsible for adjusting
5921 // lhsType so that the resulting expression does not have reference
5922 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005923 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005924 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5925 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005926 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005927 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005928 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005929 }
John McCalle5255932011-01-31 22:28:28 +00005930
Nate Begemanbd956c42009-06-28 02:36:38 +00005931 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5932 // to the same ExtVector type.
5933 if (lhsType->isExtVectorType()) {
5934 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005935 return Incompatible;
5936 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005937 // CK_VectorSplat does T -> vector T, so first cast to the
5938 // element type.
5939 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5940 if (elType != rhsType) {
5941 Kind = PrepareScalarCast(*this, rhs, elType);
5942 ImpCastExprToType(rhs, elType, Kind);
5943 }
5944 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005945 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005946 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005947 }
Mike Stump11289f42009-09-09 15:08:12 +00005948
John McCalle5255932011-01-31 22:28:28 +00005949 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00005950 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005951 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005952 // Allow assignments of an AltiVec vector type to an equivalent GCC
5953 // vector type and vice versa
5954 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5955 Kind = CK_BitCast;
5956 return Compatible;
5957 }
5958
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005959 // If we are allowing lax vector conversions, and LHS and RHS are both
5960 // vectors, the total size only needs to be the same. This is a bitcast;
5961 // no bits are changed but the result type is different.
5962 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005963 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005964 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005965 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005966 }
Chris Lattner881a2122008-01-04 23:32:24 +00005967 }
5968 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005969 }
Eli Friedman3360d892008-05-30 18:07:22 +00005970
John McCalle5255932011-01-31 22:28:28 +00005971 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00005972 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005973 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005974 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005975 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005976 }
Eli Friedman3360d892008-05-30 18:07:22 +00005977
John McCalle5255932011-01-31 22:28:28 +00005978 // Conversions to normal pointers.
5979 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5980 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00005981 if (isa<PointerType>(rhsType)) {
5982 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00005983 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005984 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005985
John McCalle5255932011-01-31 22:28:28 +00005986 // int -> T*
5987 if (rhsType->isIntegerType()) {
5988 Kind = CK_IntegralToPointer; // FIXME: null?
5989 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005990 }
John McCalle5255932011-01-31 22:28:28 +00005991
5992 // C pointers are not compatible with ObjC object pointers,
5993 // with two exceptions:
5994 if (isa<ObjCObjectPointerType>(rhsType)) {
5995 // - conversions to void*
5996 if (lhsPointer->getPointeeType()->isVoidType()) {
5997 Kind = CK_AnyPointerToObjCPointerCast;
5998 return Compatible;
5999 }
6000
6001 // - conversions from 'Class' to the redefinition type
6002 if (rhsType->isObjCClassType() &&
6003 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006004 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006005 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006006 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006007
John McCalle5255932011-01-31 22:28:28 +00006008 Kind = CK_BitCast;
6009 return IncompatiblePointer;
6010 }
6011
6012 // U^ -> void*
6013 if (rhsType->getAs<BlockPointerType>()) {
6014 if (lhsPointer->getPointeeType()->isVoidType()) {
6015 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006016 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006017 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006018 }
John McCalle5255932011-01-31 22:28:28 +00006019
Steve Naroff081c7422008-09-04 15:10:53 +00006020 return Incompatible;
6021 }
6022
John McCalle5255932011-01-31 22:28:28 +00006023 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00006024 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006025 // U^ -> T^
6026 if (rhsType->isBlockPointerType()) {
6027 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00006028 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006029 }
6030
6031 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006032 if (rhsType->isIntegerType()) {
6033 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00006034 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006035 }
6036
John McCalle5255932011-01-31 22:28:28 +00006037 // id -> T^
6038 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6039 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006040 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006041 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006042
John McCalle5255932011-01-31 22:28:28 +00006043 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006044 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00006045 if (RHSPT->getPointeeType()->isVoidType()) {
6046 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006047 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006048 }
John McCall8cb679e2010-11-15 09:13:47 +00006049
Chris Lattnera52c2f22008-01-04 23:18:45 +00006050 return Incompatible;
6051 }
6052
John McCalle5255932011-01-31 22:28:28 +00006053 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006054 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006055 // A* -> B*
6056 if (rhsType->isObjCObjectPointerType()) {
6057 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006058 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006059 }
6060
6061 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00006062 if (rhsType->isIntegerType()) {
6063 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00006064 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006065 }
6066
John McCalle5255932011-01-31 22:28:28 +00006067 // In general, C pointers are not compatible with ObjC object pointers,
6068 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00006069 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006070 // - conversions from 'void*'
6071 if (rhsType->isVoidPointerType()) {
6072 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006073 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006074 }
6075
6076 // - conversions to 'Class' from its redefinition type
6077 if (lhsType->isObjCClassType() &&
6078 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6079 Kind = CK_BitCast;
6080 return Compatible;
6081 }
6082
6083 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006084 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006085 }
John McCalle5255932011-01-31 22:28:28 +00006086
6087 // T^ -> A*
6088 if (rhsType->isBlockPointerType()) {
6089 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006090 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006091 }
6092
Steve Naroff7cae42b2009-07-10 23:34:53 +00006093 return Incompatible;
6094 }
John McCalle5255932011-01-31 22:28:28 +00006095
6096 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00006097 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006098 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006099 if (lhsType == Context.BoolTy) {
6100 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00006101 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006102 }
Eli Friedman3360d892008-05-30 18:07:22 +00006103
John McCalle5255932011-01-31 22:28:28 +00006104 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006105 if (lhsType->isIntegerType()) {
6106 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006107 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006108 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006109
Chris Lattnera52c2f22008-01-04 23:18:45 +00006110 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00006111 }
John McCalle5255932011-01-31 22:28:28 +00006112
6113 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006114 if (isa<ObjCObjectPointerType>(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;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006118 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006119 }
Steve Naroff7cae42b2009-07-10 23:34:53 +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;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006124 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006125 }
6126
Steve Naroff7cae42b2009-07-10 23:34:53 +00006127 return Incompatible;
6128 }
Eli Friedman3360d892008-05-30 18:07:22 +00006129
John McCalle5255932011-01-31 22:28:28 +00006130 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00006131 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006132 if (Context.typesAreCompatible(lhsType, rhsType)) {
6133 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00006134 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006135 }
Bill Wendling216423b2007-05-30 06:30:29 +00006136 }
John McCalle5255932011-01-31 22:28:28 +00006137
Steve Naroff98cf3e92007-06-06 18:38:38 +00006138 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00006139}
6140
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006141/// \brief Constructs a transparent union from an expression that is
6142/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00006143static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006144 QualType UnionType, FieldDecl *Field) {
6145 // Build an initializer list that designates the appropriate member
6146 // of the transparent union.
Ted Kremenekac034612010-04-13 23:39:13 +00006147 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00006148 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006149 SourceLocation());
6150 Initializer->setType(UnionType);
6151 Initializer->setInitializedFieldInUnion(Field);
6152
6153 // Build a compound literal constructing a value of the transparent
6154 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00006155 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00006156 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall7decc9e2010-11-18 06:31:45 +00006157 VK_RValue, Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006158}
6159
6160Sema::AssignConvertType
6161Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
6162 QualType FromType = rExpr->getType();
6163
Mike Stump11289f42009-09-09 15:08:12 +00006164 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006165 // transparent_union GCC extension.
6166 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006167 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006168 return Incompatible;
6169
6170 // The field to initialize within the transparent union.
6171 RecordDecl *UD = UT->getDecl();
6172 FieldDecl *InitField = 0;
6173 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006174 for (RecordDecl::field_iterator it = UD->field_begin(),
6175 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006176 it != itend; ++it) {
6177 if (it->getType()->isPointerType()) {
6178 // If the transparent union contains a pointer type, we allow:
6179 // 1) void pointer
6180 // 2) null pointer constant
6181 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006182 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +00006183 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006184 InitField = *it;
6185 break;
6186 }
Mike Stump11289f42009-09-09 15:08:12 +00006187
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006188 if (rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006189 Expr::NPC_ValueDependentIsNull)) {
John McCalle84af4e2010-11-13 01:35:44 +00006190 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006191 InitField = *it;
6192 break;
6193 }
6194 }
6195
John McCall29600e12010-11-16 02:32:08 +00006196 Expr *rhs = rExpr;
John McCall8cb679e2010-11-15 09:13:47 +00006197 CastKind Kind = CK_Invalid;
John McCall29600e12010-11-16 02:32:08 +00006198 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006199 == Compatible) {
John McCall29600e12010-11-16 02:32:08 +00006200 ImpCastExprToType(rhs, it->getType(), Kind);
6201 rExpr = rhs;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006202 InitField = *it;
6203 break;
6204 }
6205 }
6206
6207 if (!InitField)
6208 return Incompatible;
6209
6210 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
6211 return Compatible;
6212}
6213
Chris Lattner9bad62c2008-01-04 18:04:52 +00006214Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006215Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00006216 if (getLangOptions().CPlusPlus) {
6217 if (!lhsType->isRecordType()) {
6218 // C++ 5.17p3: If the left operand is not of class type, the
6219 // expression is implicitly converted (C++ 4) to the
6220 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00006221 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006222 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00006223 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00006224 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00006225 }
6226
6227 // FIXME: Currently, we fall through and treat C++ classes like C
6228 // structures.
John McCall34376a62010-12-04 03:47:34 +00006229 }
Douglas Gregor9a657932008-10-21 23:43:52 +00006230
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006231 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6232 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00006233 if ((lhsType->isPointerType() ||
6234 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00006235 lhsType->isBlockPointerType())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006236 && rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006237 Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00006238 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006239 return Compatible;
6240 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006241
Chris Lattnere6dcd502007-10-16 02:55:40 +00006242 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006243 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00006244 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00006245 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00006246 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00006247 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00006248 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00006249 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006250
John McCall8cb679e2010-11-15 09:13:47 +00006251 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006252 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00006253 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006254
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006255 // C99 6.5.16.1p2: The value of the right operand is converted to the
6256 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006257 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6258 // so that we can use references in built-in functions even in C.
6259 // The getNonReferenceType() call makes sure that the resulting expression
6260 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006261 if (result != Incompatible && rExpr->getType() != lhsType)
John McCall8cb679e2010-11-15 09:13:47 +00006262 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006263 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006264}
6265
Chris Lattner326f7572008-11-18 01:30:42 +00006266QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006267 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006268 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00006269 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006270 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006271}
6272
Chris Lattnerfaa54172010-01-12 21:23:57 +00006273QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00006274 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006275 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00006276 QualType lhsType =
6277 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
6278 QualType rhsType =
6279 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006280
Nate Begeman191a6b12008-07-14 18:02:46 +00006281 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006282 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00006283 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006284
Nate Begeman191a6b12008-07-14 18:02:46 +00006285 // Handle the case of a vector & extvector type of the same size and element
6286 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006287 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00006288 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006289 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006290 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006291 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006292 if (lhsType->isExtVectorType()) {
John McCalle3027922010-08-25 11:45:40 +00006293 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006294 return lhsType;
6295 }
6296
John McCalle3027922010-08-25 11:45:40 +00006297 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006298 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00006299 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6300 // If we are allowing lax vector conversions, and LHS and RHS are both
6301 // vectors, the total size only needs to be the same. This is a
6302 // bitcast; no bits are changed but the result type is different.
6303 ImpCastExprToType(rex, lhsType, CK_BitCast);
6304 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006305 }
Eric Christophera613f562010-08-26 00:42:16 +00006306 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006307 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006308 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006309
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006310 // Handle the case of equivalent AltiVec and GCC vector types
6311 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6312 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCalle3027922010-08-25 11:45:40 +00006313 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006314 return rhsType;
6315 }
6316
Nate Begemanbd956c42009-06-28 02:36:38 +00006317 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6318 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6319 bool swapped = false;
6320 if (rhsType->isExtVectorType()) {
6321 swapped = true;
6322 std::swap(rex, lex);
6323 std::swap(rhsType, lhsType);
6324 }
Mike Stump11289f42009-09-09 15:08:12 +00006325
Nate Begeman886448d2009-06-28 19:12:57 +00006326 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00006327 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006328 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00006329 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00006330 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6331 if (order > 0)
6332 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
6333 if (order >= 0) {
6334 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006335 if (swapped) std::swap(rex, lex);
6336 return lhsType;
6337 }
6338 }
6339 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6340 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00006341 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6342 if (order > 0)
6343 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
6344 if (order >= 0) {
6345 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006346 if (swapped) std::swap(rex, lex);
6347 return lhsType;
6348 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006349 }
6350 }
Mike Stump11289f42009-09-09 15:08:12 +00006351
Nate Begeman886448d2009-06-28 19:12:57 +00006352 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00006353 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006354 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00006355 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006356 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006357}
6358
Chris Lattnerfaa54172010-01-12 21:23:57 +00006359QualType Sema::CheckMultiplyDivideOperands(
6360 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00006361 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006362 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006363
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006364 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006365
Chris Lattnerfaa54172010-01-12 21:23:57 +00006366 if (!lex->getType()->isArithmeticType() ||
6367 !rex->getType()->isArithmeticType())
6368 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006369
Chris Lattnerfaa54172010-01-12 21:23:57 +00006370 // Check for division by zero.
6371 if (isDiv &&
6372 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006373 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattner70117952010-01-12 21:30:55 +00006374 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006375
Chris Lattnerfaa54172010-01-12 21:23:57 +00006376 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006377}
6378
Chris Lattnerfaa54172010-01-12 21:23:57 +00006379QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00006380 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006381 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006382 if (lex->getType()->hasIntegerRepresentation() &&
6383 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006384 return CheckVectorOperands(Loc, lex, rex);
6385 return InvalidOperands(Loc, lex, rex);
6386 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006387
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006388 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006389
Chris Lattnerfaa54172010-01-12 21:23:57 +00006390 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6391 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006392
Chris Lattnerfaa54172010-01-12 21:23:57 +00006393 // Check for remainder by zero.
6394 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00006395 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
6396 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006397
Chris Lattnerfaa54172010-01-12 21:23:57 +00006398 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006399}
6400
Chris Lattnerfaa54172010-01-12 21:23:57 +00006401QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00006402 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006403 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6404 QualType compType = CheckVectorOperands(Loc, lex, rex);
6405 if (CompLHSTy) *CompLHSTy = compType;
6406 return compType;
6407 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006408
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006409 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006410
Steve Naroffe4718892007-04-27 18:30:00 +00006411 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006412 if (lex->getType()->isArithmeticType() &&
6413 rex->getType()->isArithmeticType()) {
6414 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006415 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006416 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006417
Eli Friedman8e122982008-05-18 18:08:51 +00006418 // Put any potential pointer into PExp
6419 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00006420 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006421 std::swap(PExp, IExp);
6422
Steve Naroff6b712a72009-07-14 18:25:06 +00006423 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006424
Eli Friedman8e122982008-05-18 18:08:51 +00006425 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006426 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006427
Chris Lattner12bdebb2009-04-24 23:50:08 +00006428 // Check for arithmetic on pointers to incomplete types.
6429 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006430 if (getLangOptions().CPlusPlus) {
6431 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00006432 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00006433 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006434 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006435
6436 // GNU extension: arithmetic on pointer to void
6437 Diag(Loc, diag::ext_gnu_void_ptr)
6438 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006439 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006440 if (getLangOptions().CPlusPlus) {
6441 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6442 << lex->getType() << lex->getSourceRange();
6443 return QualType();
6444 }
6445
6446 // GNU extension: arithmetic on pointer to function
6447 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6448 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00006449 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006450 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00006451 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00006452 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006453 PExp->getType()->isObjCObjectPointerType()) &&
6454 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00006455 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6456 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006457 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006458 return QualType();
6459 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00006460 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006461 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006462 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6463 << PointeeTy << PExp->getSourceRange();
6464 return QualType();
6465 }
Mike Stump11289f42009-09-09 15:08:12 +00006466
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006467 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00006468 QualType LHSTy = Context.isPromotableBitField(lex);
6469 if (LHSTy.isNull()) {
6470 LHSTy = lex->getType();
6471 if (LHSTy->isPromotableIntegerType())
6472 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006473 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006474 *CompLHSTy = LHSTy;
6475 }
Eli Friedman8e122982008-05-18 18:08:51 +00006476 return PExp->getType();
6477 }
6478 }
6479
Chris Lattner326f7572008-11-18 01:30:42 +00006480 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006481}
6482
Chris Lattner2a3569b2008-04-07 05:30:13 +00006483// C99 6.5.6
6484QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006485 SourceLocation Loc, QualType* CompLHSTy) {
6486 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6487 QualType compType = CheckVectorOperands(Loc, lex, rex);
6488 if (CompLHSTy) *CompLHSTy = compType;
6489 return compType;
6490 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006491
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006492 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006493
Chris Lattner4d62f422007-12-09 21:53:25 +00006494 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006495
Chris Lattner4d62f422007-12-09 21:53:25 +00006496 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00006497 if (lex->getType()->isArithmeticType()
6498 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006499 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006500 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006501 }
Mike Stump11289f42009-09-09 15:08:12 +00006502
Chris Lattner4d62f422007-12-09 21:53:25 +00006503 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00006504 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00006505 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006506
Douglas Gregorac1fb652009-03-24 19:52:54 +00006507 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006508
Douglas Gregorac1fb652009-03-24 19:52:54 +00006509 bool ComplainAboutVoid = false;
6510 Expr *ComplainAboutFunc = 0;
6511 if (lpointee->isVoidType()) {
6512 if (getLangOptions().CPlusPlus) {
6513 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6514 << lex->getSourceRange() << rex->getSourceRange();
6515 return QualType();
6516 }
6517
6518 // GNU C extension: arithmetic on pointer to void
6519 ComplainAboutVoid = true;
6520 } else if (lpointee->isFunctionType()) {
6521 if (getLangOptions().CPlusPlus) {
6522 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006523 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006524 return QualType();
6525 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006526
6527 // GNU C extension: arithmetic on pointer to function
6528 ComplainAboutFunc = lex;
6529 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00006530 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006531 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00006532 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006533 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006534 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006535
Chris Lattner12bdebb2009-04-24 23:50:08 +00006536 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006537 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006538 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6539 << lpointee << lex->getSourceRange();
6540 return QualType();
6541 }
Mike Stump11289f42009-09-09 15:08:12 +00006542
Chris Lattner4d62f422007-12-09 21:53:25 +00006543 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00006544 if (rex->getType()->isIntegerType()) {
6545 if (ComplainAboutVoid)
6546 Diag(Loc, diag::ext_gnu_void_ptr)
6547 << lex->getSourceRange() << rex->getSourceRange();
6548 if (ComplainAboutFunc)
6549 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006550 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006551 << ComplainAboutFunc->getSourceRange();
6552
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006553 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006554 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006555 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006556
Chris Lattner4d62f422007-12-09 21:53:25 +00006557 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006558 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006559 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006560
Douglas Gregorac1fb652009-03-24 19:52:54 +00006561 // RHS must be a completely-type object type.
6562 // Handle the GNU void* extension.
6563 if (rpointee->isVoidType()) {
6564 if (getLangOptions().CPlusPlus) {
6565 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6566 << lex->getSourceRange() << rex->getSourceRange();
6567 return QualType();
6568 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006569
Douglas Gregorac1fb652009-03-24 19:52:54 +00006570 ComplainAboutVoid = true;
6571 } else if (rpointee->isFunctionType()) {
6572 if (getLangOptions().CPlusPlus) {
6573 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006574 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006575 return QualType();
6576 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006577
6578 // GNU extension: arithmetic on pointer to function
6579 if (!ComplainAboutFunc)
6580 ComplainAboutFunc = rex;
6581 } else if (!rpointee->isDependentType() &&
6582 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006583 PDiag(diag::err_typecheck_sub_ptr_object)
6584 << rex->getSourceRange()
6585 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006586 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006587
Eli Friedman168fe152009-05-16 13:54:38 +00006588 if (getLangOptions().CPlusPlus) {
6589 // Pointee types must be the same: C++ [expr.add]
6590 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6591 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6592 << lex->getType() << rex->getType()
6593 << lex->getSourceRange() << rex->getSourceRange();
6594 return QualType();
6595 }
6596 } else {
6597 // Pointee types must be compatible C99 6.5.6p3
6598 if (!Context.typesAreCompatible(
6599 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6600 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6601 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6602 << lex->getType() << rex->getType()
6603 << lex->getSourceRange() << rex->getSourceRange();
6604 return QualType();
6605 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006606 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006607
Douglas Gregorac1fb652009-03-24 19:52:54 +00006608 if (ComplainAboutVoid)
6609 Diag(Loc, diag::ext_gnu_void_ptr)
6610 << lex->getSourceRange() << rex->getSourceRange();
6611 if (ComplainAboutFunc)
6612 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006613 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006614 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006615
6616 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006617 return Context.getPointerDiffType();
6618 }
6619 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006620
Chris Lattner326f7572008-11-18 01:30:42 +00006621 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006622}
6623
Douglas Gregor0bf31402010-10-08 23:50:27 +00006624static bool isScopedEnumerationType(QualType T) {
6625 if (const EnumType *ET = dyn_cast<EnumType>(T))
6626 return ET->getDecl()->isScoped();
6627 return false;
6628}
6629
Chris Lattner2a3569b2008-04-07 05:30:13 +00006630// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00006631QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00006632 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006633 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006634 if (!lex->getType()->hasIntegerRepresentation() ||
6635 !rex->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006636 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006637
Douglas Gregor0bf31402010-10-08 23:50:27 +00006638 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6639 // hasIntegerRepresentation() above instead of this.
6640 if (isScopedEnumerationType(lex->getType()) ||
6641 isScopedEnumerationType(rex->getType())) {
6642 return InvalidOperands(Loc, lex, rex);
6643 }
6644
Nate Begemane46ee9a2009-10-25 02:26:48 +00006645 // Vector shifts promote their scalar inputs to vector type.
6646 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6647 return CheckVectorOperands(Loc, lex, rex);
6648
Chris Lattner5c11c412007-12-12 05:47:28 +00006649 // Shifts don't perform usual arithmetic conversions, they just do integer
6650 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006651
John McCall57cdd882010-12-16 19:28:59 +00006652 // For the LHS, do usual unary conversions, but then reset them away
6653 // if this is a compound assignment.
6654 Expr *old_lex = lex;
6655 UsualUnaryConversions(lex);
6656 QualType LHSTy = lex->getType();
6657 if (isCompAssign) lex = old_lex;
6658
6659 // The RHS is simpler.
Chris Lattner5c11c412007-12-12 05:47:28 +00006660 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006661
Ryan Flynnf53fab82009-08-07 16:20:20 +00006662 // Sanity-check shift operands
6663 llvm::APSInt Right;
6664 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00006665 if (!rex->isValueDependent() &&
6666 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00006667 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00006668 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6669 else {
6670 llvm::APInt LeftBits(Right.getBitWidth(),
6671 Context.getTypeSize(lex->getType()));
6672 if (Right.uge(LeftBits))
6673 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6674 }
6675 }
6676
Chris Lattner5c11c412007-12-12 05:47:28 +00006677 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006678 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006679}
6680
Chandler Carruth17773fc2010-07-10 12:30:03 +00006681static bool IsWithinTemplateSpecialization(Decl *D) {
6682 if (DeclContext *DC = D->getDeclContext()) {
6683 if (isa<ClassTemplateSpecializationDecl>(DC))
6684 return true;
6685 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6686 return FD->isFunctionTemplateSpecialization();
6687 }
6688 return false;
6689}
6690
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006691// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00006692QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006693 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006694 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006695
Chris Lattner9a152e22009-12-05 05:40:13 +00006696 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00006697 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006698 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006699
Steve Naroff31090012007-07-16 21:54:35 +00006700 QualType lType = lex->getType();
6701 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006702
Chandler Carruth712563b2011-02-17 08:37:06 +00006703 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6704 Expr *RHSStripped = rex->IgnoreParenImpCasts();
6705 QualType LHSStrippedType = LHSStripped->getType();
6706 QualType RHSStrippedType = RHSStripped->getType();
6707
6708 // Two different enums will raise a warning when compared.
6709 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6710 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6711 if (LHSEnumType->getDecl()->getIdentifier() &&
6712 RHSEnumType->getDecl()->getIdentifier() &&
6713 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6714 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6715 << LHSStrippedType << RHSStrippedType
6716 << lex->getSourceRange() << rex->getSourceRange();
6717 }
6718 }
6719 }
6720
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006721 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006722 !(lType->isBlockPointerType() && isRelational) &&
6723 !lex->getLocStart().isMacroID() &&
6724 !rex->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006725 // For non-floating point types, check for self-comparisons of the form
6726 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6727 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006728 //
6729 // NOTE: Don't warn about comparison expressions resulting from macro
6730 // expansion. Also don't warn about comparisons which are only self
6731 // comparisons within a template specialization. The warnings should catch
6732 // obvious cases in the definition of the template anyways. The idea is to
6733 // warn when the typed comparison operator will always evaluate to the same
6734 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006735 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006736 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006737 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006738 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006739 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6740 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006741 << (Opc == BO_EQ
6742 || Opc == BO_LE
6743 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006744 } else if (lType->isArrayType() && rType->isArrayType() &&
6745 !DRL->getDecl()->getType()->isReferenceType() &&
6746 !DRR->getDecl()->getType()->isReferenceType()) {
6747 // what is it always going to eval to?
6748 char always_evals_to;
6749 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006750 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006751 always_evals_to = 0; // false
6752 break;
John McCalle3027922010-08-25 11:45:40 +00006753 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006754 always_evals_to = 1; // true
6755 break;
6756 default:
6757 // best we can say is 'a constant'
6758 always_evals_to = 2; // e.g. array1 <= array2
6759 break;
6760 }
6761 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6762 << 1 // array
6763 << always_evals_to);
6764 }
6765 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006766 }
Mike Stump11289f42009-09-09 15:08:12 +00006767
Chris Lattner222b8bd2009-03-08 19:39:53 +00006768 if (isa<CastExpr>(LHSStripped))
6769 LHSStripped = LHSStripped->IgnoreParenCasts();
6770 if (isa<CastExpr>(RHSStripped))
6771 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006772
Chris Lattner222b8bd2009-03-08 19:39:53 +00006773 // Warn about comparisons against a string constant (unless the other
6774 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006775 Expr *literalString = 0;
6776 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006777 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006778 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006779 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006780 literalString = lex;
6781 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006782 } else if ((isa<StringLiteral>(RHSStripped) ||
6783 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006784 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006785 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006786 literalString = rex;
6787 literalStringStripped = RHSStripped;
6788 }
6789
6790 if (literalString) {
6791 std::string resultComparison;
6792 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006793 case BO_LT: resultComparison = ") < 0"; break;
6794 case BO_GT: resultComparison = ") > 0"; break;
6795 case BO_LE: resultComparison = ") <= 0"; break;
6796 case BO_GE: resultComparison = ") >= 0"; break;
6797 case BO_EQ: resultComparison = ") == 0"; break;
6798 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006799 default: assert(false && "Invalid comparison operator");
6800 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006801
Douglas Gregor49862b82010-01-12 23:18:54 +00006802 DiagRuntimeBehavior(Loc,
6803 PDiag(diag::warn_stringcompare)
6804 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006805 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006806 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006807 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006808
Douglas Gregorec170db2010-06-08 19:50:34 +00006809 // C99 6.5.8p3 / C99 6.5.9p4
6810 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6811 UsualArithmeticConversions(lex, rex);
6812 else {
6813 UsualUnaryConversions(lex);
6814 UsualUnaryConversions(rex);
6815 }
6816
6817 lType = lex->getType();
6818 rType = rex->getType();
6819
Douglas Gregorca63811b2008-11-19 03:25:36 +00006820 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006821 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006822
Chris Lattnerb620c342007-08-26 01:18:55 +00006823 if (isRelational) {
6824 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006825 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006826 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006827 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006828 if (lType->hasFloatingRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006829 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006830
Chris Lattnerb620c342007-08-26 01:18:55 +00006831 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006832 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006833 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006834
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006835 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006836 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006837 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006838 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006839
Douglas Gregorf267edd2010-06-15 21:38:40 +00006840 // All of the following pointer-related warnings are GCC extensions, except
6841 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006842 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006843 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006844 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006845 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006846 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006847
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006848 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006849 if (LCanPointeeTy == RCanPointeeTy)
6850 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006851 if (!isRelational &&
6852 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6853 // Valid unless comparison between non-null pointer and function pointer
6854 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006855 // In a SFINAE context, we treat this as a hard error to maintain
6856 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006857 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6858 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006859 Diag(Loc,
6860 isSFINAEContext()?
6861 diag::err_typecheck_comparison_of_fptr_to_void
6862 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006863 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006864
6865 if (isSFINAEContext())
6866 return QualType();
6867
John McCalle3027922010-08-25 11:45:40 +00006868 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006869 return ResultTy;
6870 }
6871 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006872
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006873 // C++ [expr.rel]p2:
6874 // [...] Pointer conversions (4.10) and qualification
6875 // conversions (4.4) are performed on pointer operands (or on
6876 // a pointer operand and a null pointer constant) to bring
6877 // them to their composite pointer type. [...]
6878 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006879 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006880 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006881 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006882 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006883 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006884 if (T.isNull()) {
6885 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6886 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6887 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006888 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006889 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006890 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006891 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006892 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006893 }
6894
John McCalle3027922010-08-25 11:45:40 +00006895 ImpCastExprToType(lex, T, CK_BitCast);
6896 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006897 return ResultTy;
6898 }
Eli Friedman16c209612009-08-23 00:27:47 +00006899 // C99 6.5.9p2 and C99 6.5.8p2
6900 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6901 RCanPointeeTy.getUnqualifiedType())) {
6902 // Valid unless a relational comparison of function pointers
6903 if (isRelational && LCanPointeeTy->isFunctionType()) {
6904 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6905 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6906 }
6907 } else if (!isRelational &&
6908 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6909 // Valid unless comparison between non-null pointer and function pointer
6910 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6911 && !LHSIsNull && !RHSIsNull) {
6912 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6913 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6914 }
6915 } else {
6916 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006917 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006918 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006919 }
Eli Friedman16c209612009-08-23 00:27:47 +00006920 if (LCanPointeeTy != RCanPointeeTy)
John McCalle3027922010-08-25 11:45:40 +00006921 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006922 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006923 }
Mike Stump11289f42009-09-09 15:08:12 +00006924
Sebastian Redl576fd422009-05-10 18:38:11 +00006925 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006926 // Comparison of nullptr_t with itself.
6927 if (lType->isNullPtrType() && rType->isNullPtrType())
6928 return ResultTy;
6929
Mike Stump11289f42009-09-09 15:08:12 +00006930 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006931 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006932 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006933 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006934 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006935 ImpCastExprToType(rex, lType,
6936 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006937 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006938 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006939 return ResultTy;
6940 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006941 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006942 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006943 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006944 ImpCastExprToType(lex, rType,
6945 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006946 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006947 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006948 return ResultTy;
6949 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006950
6951 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006952 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006953 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6954 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006955 // In addition, pointers to members can be compared, or a pointer to
6956 // member and a null pointer constant. Pointer to member conversions
6957 // (4.11) and qualification conversions (4.4) are performed to bring
6958 // them to a common type. If one operand is a null pointer constant,
6959 // the common type is the type of the other operand. Otherwise, the
6960 // common type is a pointer to member type similar (4.4) to the type
6961 // of one of the operands, with a cv-qualification signature (4.4)
6962 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006963 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006964 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006965 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006966 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006967 if (T.isNull()) {
6968 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006969 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006970 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006971 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006972 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006973 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006974 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006975 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006976 }
Mike Stump11289f42009-09-09 15:08:12 +00006977
John McCalle3027922010-08-25 11:45:40 +00006978 ImpCastExprToType(lex, T, CK_BitCast);
6979 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006980 return ResultTy;
6981 }
Sebastian Redl576fd422009-05-10 18:38:11 +00006982 }
Mike Stump11289f42009-09-09 15:08:12 +00006983
Steve Naroff081c7422008-09-04 15:10:53 +00006984 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00006985 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006986 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6987 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006988
Steve Naroff081c7422008-09-04 15:10:53 +00006989 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006990 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006991 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006992 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006993 }
John McCalle3027922010-08-25 11:45:40 +00006994 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006995 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006996 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00006997 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006998 if (!isRelational
6999 && ((lType->isBlockPointerType() && rType->isPointerType())
7000 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007001 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007002 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007003 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007004 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007005 ->getPointeeType()->isVoidType())))
7006 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7007 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007008 }
John McCalle3027922010-08-25 11:45:40 +00007009 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007010 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007011 }
Steve Naroff081c7422008-09-04 15:10:53 +00007012
Steve Naroff7cae42b2009-07-10 23:34:53 +00007013 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007014 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007015 const PointerType *LPT = lType->getAs<PointerType>();
7016 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007017 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00007018 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007019 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00007020 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007021
Steve Naroff753567f2008-11-17 19:49:16 +00007022 if (!LPtrToVoid && !RPtrToVoid &&
7023 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007024 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007025 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007026 }
John McCalle3027922010-08-25 11:45:40 +00007027 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007028 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007029 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007030 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007031 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007032 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
7033 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007034 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007035 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007036 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007037 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007038 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7039 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007040 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007041 bool isError = false;
7042 if ((LHSIsNull && lType->isIntegerType()) ||
7043 (RHSIsNull && rType->isIntegerType())) {
7044 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007045 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007046 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007047 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007048 else if (getLangOptions().CPlusPlus) {
7049 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7050 isError = true;
7051 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007052 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007053
Chris Lattnerd99bd522009-08-23 00:03:44 +00007054 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007055 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00007056 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007057 if (isError)
7058 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007059 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007060
7061 if (lType->isIntegerType())
John McCalle84af4e2010-11-13 01:35:44 +00007062 ImpCastExprToType(lex, rType,
7063 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007064 else
John McCalle84af4e2010-11-13 01:35:44 +00007065 ImpCastExprToType(rex, lType,
7066 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007067 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007068 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007069
Steve Naroff4b191572008-09-04 16:56:14 +00007070 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00007071 if (!isRelational && RHSIsNull
7072 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00007073 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007074 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007075 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00007076 if (!isRelational && LHSIsNull
7077 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00007078 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007079 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007080 }
Chris Lattner326f7572008-11-18 01:30:42 +00007081 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007082}
7083
Nate Begeman191a6b12008-07-14 18:02:46 +00007084/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007085/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007086/// like a scalar comparison, a vector comparison produces a vector of integer
7087/// types.
7088QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00007089 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00007090 bool isRelational) {
7091 // Check to make sure we're operating on vectors of the same type and width,
7092 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00007093 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007094 if (vType.isNull())
7095 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007096
Anton Yartsev3f8f2882010-11-18 03:19:30 +00007097 // If AltiVec, the comparison results in a numeric type, i.e.
7098 // bool for C++, int for C
7099 if (getLangOptions().AltiVec)
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007100 return Context.getLogicalOperationType();
Anton Yartsev3f8f2882010-11-18 03:19:30 +00007101
Nate Begeman191a6b12008-07-14 18:02:46 +00007102 QualType lType = lex->getType();
7103 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007104
Nate Begeman191a6b12008-07-14 18:02:46 +00007105 // For non-floating point types, check for self-comparisons of the form
7106 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7107 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007108 if (!lType->hasFloatingRepresentation()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007109 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
7110 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
7111 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregorec170db2010-06-08 19:50:34 +00007112 DiagRuntimeBehavior(Loc,
7113 PDiag(diag::warn_comparison_always)
7114 << 0 // self-
7115 << 2 // "a constant"
7116 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007117 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007118
Nate Begeman191a6b12008-07-14 18:02:46 +00007119 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007120 if (!isRelational && lType->hasFloatingRepresentation()) {
7121 assert (rType->hasFloatingRepresentation());
Chris Lattner326f7572008-11-18 01:30:42 +00007122 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007123 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007124
Nate Begeman191a6b12008-07-14 18:02:46 +00007125 // Return the type for the comparison, which is the same as vector type for
7126 // integer vectors, or an integer type of identical size and number of
7127 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007128 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00007129 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007130
John McCall9dd450b2009-09-21 23:43:11 +00007131 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00007132 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007133 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00007134 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00007135 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007136 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7137
Mike Stump4e1f26a2009-02-19 03:04:26 +00007138 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007139 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00007140 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7141}
7142
Steve Naroff218bc2b2007-05-04 21:54:46 +00007143inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00007144 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007145 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
7146 if (lex->getType()->hasIntegerRepresentation() &&
7147 rex->getType()->hasIntegerRepresentation())
7148 return CheckVectorOperands(Loc, lex, rex);
7149
7150 return InvalidOperands(Loc, lex, rex);
7151 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007152
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007153 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007154
Douglas Gregor0bf31402010-10-08 23:50:27 +00007155 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
7156 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007157 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00007158 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007159}
7160
Steve Naroff218bc2b2007-05-04 21:54:46 +00007161inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner8406c512010-07-13 19:41:32 +00007162 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
7163
7164 // Diagnose cases where the user write a logical and/or but probably meant a
7165 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7166 // is a constant.
7167 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman6b197e02010-07-27 19:14:53 +00007168 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00007169 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00007170 !Loc.isMacroID()) {
7171 // If the RHS can be constant folded, and if it constant folds to something
7172 // that isn't 0 or 1 (which indicate a potential logical operation that
7173 // happened to fold to true/false) then warn.
7174 Expr::EvalResult Result;
7175 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
7176 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7177 Diag(Loc, diag::warn_logical_instead_of_bitwise)
7178 << rex->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00007179 << (Opc == BO_LAnd ? "&&" : "||")
7180 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00007181 }
7182 }
Chris Lattner8406c512010-07-13 19:41:32 +00007183
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007184 if (!Context.getLangOptions().CPlusPlus) {
7185 UsualUnaryConversions(lex);
7186 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007187
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007188 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
7189 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007190
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007191 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007192 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007193
John McCall4a2429a2010-06-04 00:29:51 +00007194 // The following is safe because we only use this method for
7195 // non-overloadable operands.
7196
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007197 // C++ [expr.log.and]p1
7198 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007199 // The operands are both contextually converted to type bool.
7200 if (PerformContextuallyConvertToBool(lex) ||
7201 PerformContextuallyConvertToBool(rex))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007202 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007203
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007204 // C++ [expr.log.and]p2
7205 // C++ [expr.log.or]p2
7206 // The result is a bool.
7207 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007208}
7209
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007210/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7211/// is a read-only property; return true if so. A readonly property expression
7212/// depends on various declarations and thus must be treated specially.
7213///
Mike Stump11289f42009-09-09 15:08:12 +00007214static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007215 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7216 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00007217 if (PropExpr->isImplicitProperty()) return false;
7218
7219 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7220 QualType BaseType = PropExpr->isSuperReceiver() ?
7221 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007222 PropExpr->getBase()->getType();
7223
John McCallb7bd14f2010-12-02 01:19:52 +00007224 if (const ObjCObjectPointerType *OPT =
7225 BaseType->getAsObjCInterfacePointerType())
7226 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7227 if (S.isPropertyReadonly(PDecl, IFace))
7228 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007229 }
7230 return false;
7231}
7232
Chris Lattner30bd3272008-11-18 01:22:49 +00007233/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7234/// emit an error and return true. If so, return false.
7235static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007236 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007237 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007238 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007239 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7240 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00007241 if (IsLV == Expr::MLV_Valid)
7242 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007243
Chris Lattner30bd3272008-11-18 01:22:49 +00007244 unsigned Diag = 0;
7245 bool NeedType = false;
7246 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00007247 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007248 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007249 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7250 NeedType = true;
7251 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007252 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007253 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7254 NeedType = true;
7255 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007256 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007257 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7258 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007259 case Expr::MLV_Valid:
7260 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007261 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007262 case Expr::MLV_MemberFunction:
7263 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007264 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7265 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007266 case Expr::MLV_IncompleteType:
7267 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007268 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007269 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007270 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007271 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007272 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7273 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007274 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007275 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7276 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007277 case Expr::MLV_ReadonlyProperty:
7278 Diag = diag::error_readonly_property_assignment;
7279 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007280 case Expr::MLV_NoSetterProperty:
7281 Diag = diag::error_nosetter_property_assignment;
7282 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007283 case Expr::MLV_SubObjCPropertySetting:
7284 Diag = diag::error_no_subobject_property_setting;
7285 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007286 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007287
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007288 SourceRange Assign;
7289 if (Loc != OrigLoc)
7290 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007291 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007292 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007293 else
Mike Stump11289f42009-09-09 15:08:12 +00007294 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007295 return true;
7296}
7297
7298
7299
7300// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00007301QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
7302 SourceLocation Loc,
7303 QualType CompoundType) {
7304 // Verify that LHS is a modifiable lvalue, and emit error if not.
7305 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007306 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007307
7308 QualType LHSType = LHS->getType();
7309 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007310 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007311 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007312 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007313 // Simple assignment "x = y".
John McCall34376a62010-12-04 03:47:34 +00007314 if (LHS->getObjectKind() == OK_ObjCProperty)
7315 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007316 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007317 // Special case of NSObject attributes on c-style pointer types.
7318 if (ConvTy == IncompatiblePointer &&
7319 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007320 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007321 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007322 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007323 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007324
John McCall7decc9e2010-11-18 06:31:45 +00007325 if (ConvTy == Compatible &&
7326 getLangOptions().ObjCNonFragileABI &&
7327 LHSType->isObjCObjectType())
7328 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7329 << LHSType;
7330
Chris Lattnerea714382008-08-21 18:04:13 +00007331 // If the RHS is a unary plus or minus, check to see if they = and + are
7332 // right next to each other. If so, the user may have typo'd "x =+ 4"
7333 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00007334 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00007335 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7336 RHSCheck = ICE->getSubExpr();
7337 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007338 if ((UO->getOpcode() == UO_Plus ||
7339 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007340 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007341 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00007342 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7343 // And there is a space or other character before the subexpr of the
7344 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00007345 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7346 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007347 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007348 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007349 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007350 }
Chris Lattnerea714382008-08-21 18:04:13 +00007351 }
7352 } else {
7353 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007354 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007355 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007356
Chris Lattner326f7572008-11-18 01:30:42 +00007357 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007358 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007359 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007360
Chris Lattner39561062010-07-07 06:14:23 +00007361
7362 // Check to see if the destination operand is a dereferenced null pointer. If
7363 // so, and if not volatile-qualified, this is undefined behavior that the
7364 // optimizer will delete, so warn about it. People sometimes try to use this
7365 // to get a deterministic trap and are surprised by clang's behavior. This
7366 // only handles the pattern "*null = whatever", which is a very syntactic
7367 // check.
7368 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCalle3027922010-08-25 11:45:40 +00007369 if (UO->getOpcode() == UO_Deref &&
Chris Lattner39561062010-07-07 06:14:23 +00007370 UO->getSubExpr()->IgnoreParenCasts()->
7371 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7372 !UO->getType().isVolatileQualified()) {
7373 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
7374 << UO->getSubExpr()->getSourceRange();
7375 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
7376 }
7377
Ted Kremenek64699be2011-02-16 01:57:07 +00007378 // Check for trivial buffer overflows.
7379 if (const ArraySubscriptExpr *ae
7380 = dyn_cast<ArraySubscriptExpr>(LHS->IgnoreParenCasts()))
7381 CheckArrayAccess(ae);
7382
Steve Naroff98cf3e92007-06-06 18:38:38 +00007383 // C99 6.5.16p3: The type of an assignment expression is the type of the
7384 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007385 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007386 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7387 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007388 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007389 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007390 return (getLangOptions().CPlusPlus
7391 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007392}
7393
Chris Lattner326f7572008-11-18 01:30:42 +00007394// C99 6.5.17
John McCall34376a62010-12-04 03:47:34 +00007395static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007396 SourceLocation Loc) {
7397 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007398
John McCall4bc41ae2010-11-18 19:01:18 +00007399 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007400 if (LHSResult.isInvalid())
7401 return QualType();
7402
John McCall4bc41ae2010-11-18 19:01:18 +00007403 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007404 if (RHSResult.isInvalid())
7405 return QualType();
7406 RHS = RHSResult.take();
7407
John McCall73d36182010-10-12 07:14:40 +00007408 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7409 // operands, but not unary promotions.
7410 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007411
John McCall34376a62010-12-04 03:47:34 +00007412 // So we treat the LHS as a ignored value, and in C++ we allow the
7413 // containing site to determine what should be done with the RHS.
7414 S.IgnoredValueConversions(LHS);
7415
7416 if (!S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007417 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCall73d36182010-10-12 07:14:40 +00007418 if (!RHS->getType()->isVoidType())
John McCall4bc41ae2010-11-18 19:01:18 +00007419 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007420 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007421
Chris Lattner326f7572008-11-18 01:30:42 +00007422 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007423}
7424
Steve Naroff7a5af782007-07-13 16:58:59 +00007425/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7426/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007427static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7428 ExprValueKind &VK,
7429 SourceLocation OpLoc,
7430 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007431 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007432 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007433
Chris Lattner6b0cf142008-11-21 07:05:48 +00007434 QualType ResType = Op->getType();
7435 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007436
John McCall4bc41ae2010-11-18 19:01:18 +00007437 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007438 // Decrement of bool is not allowed.
7439 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007440 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007441 return QualType();
7442 }
7443 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007444 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007445 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007446 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007447 } else if (ResType->isAnyPointerType()) {
7448 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007449
Chris Lattner6b0cf142008-11-21 07:05:48 +00007450 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00007451 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007452 if (S.getLangOptions().CPlusPlus) {
7453 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007454 << Op->getSourceRange();
7455 return QualType();
7456 }
7457
7458 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00007459 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007460 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007461 if (S.getLangOptions().CPlusPlus) {
7462 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007463 << Op->getType() << Op->getSourceRange();
7464 return QualType();
7465 }
7466
John McCall4bc41ae2010-11-18 19:01:18 +00007467 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007468 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007469 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7470 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00007471 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00007472 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00007473 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007474 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00007475 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7476 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007477 << PointeeTy << Op->getSourceRange();
7478 return QualType();
7479 }
Eli Friedman090addd2010-01-03 00:20:48 +00007480 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007481 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007482 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007483 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007484 } else if (ResType->isPlaceholderType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007485 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007486 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007487 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7488 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007489 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7490 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007491 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007492 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007493 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007494 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007495 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007496 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007497 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007498 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007499 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007500 // In C++, a prefix increment is the same type as the operand. Otherwise
7501 // (in C or with postfix), the increment is the unqualified type of the
7502 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007503 if (isPrefix && S.getLangOptions().CPlusPlus) {
7504 VK = VK_LValue;
7505 return ResType;
7506 } else {
7507 VK = VK_RValue;
7508 return ResType.getUnqualifiedType();
7509 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007510}
7511
John McCall34376a62010-12-04 03:47:34 +00007512void Sema::ConvertPropertyForRValue(Expr *&E) {
7513 assert(E->getValueKind() == VK_LValue &&
7514 E->getObjectKind() == OK_ObjCProperty);
7515 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7516
7517 ExprValueKind VK = VK_RValue;
7518 if (PRE->isImplicitProperty()) {
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007519 if (const ObjCMethodDecl *GetterMethod =
7520 PRE->getImplicitPropertyGetter()) {
7521 QualType Result = GetterMethod->getResultType();
7522 VK = Expr::getValueKindForType(Result);
7523 }
7524 else {
7525 Diag(PRE->getLocation(), diag::err_getter_not_found)
7526 << PRE->getBase()->getType();
7527 }
John McCall34376a62010-12-04 03:47:34 +00007528 }
7529
7530 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7531 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007532
7533 ExprResult Result = MaybeBindToTemporary(E);
7534 if (!Result.isInvalid())
7535 E = Result.take();
John McCall34376a62010-12-04 03:47:34 +00007536}
7537
7538void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7539 assert(LHS->getValueKind() == VK_LValue &&
7540 LHS->getObjectKind() == OK_ObjCProperty);
7541 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7542
7543 if (PRE->isImplicitProperty()) {
7544 // If using property-dot syntax notation for assignment, and there is a
7545 // setter, RHS expression is being passed to the setter argument. So,
7546 // type conversion (and comparison) is RHS to setter's argument type.
7547 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7548 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7549 LHSTy = (*P)->getType();
7550
7551 // Otherwise, if the getter returns an l-value, just call that.
7552 } else {
7553 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7554 ExprValueKind VK = Expr::getValueKindForType(Result);
7555 if (VK == VK_LValue) {
7556 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7557 CK_GetObjCProperty, LHS, 0, VK);
7558 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007559 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007560 }
John McCall34376a62010-12-04 03:47:34 +00007561 }
7562
7563 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007564 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007565 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007566 Expr *Arg = RHS;
7567 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7568 Owned(Arg));
7569 if (!ArgE.isInvalid())
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007570 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007571 }
7572}
7573
7574
Anders Carlsson806700f2008-02-01 07:15:58 +00007575/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007576/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007577/// where the declaration is needed for type checking. We only need to
7578/// handle cases when the expression references a function designator
7579/// or is an lvalue. Here are some examples:
7580/// - &(x) => x
7581/// - &*****f => f for f a function designator.
7582/// - &s.xx => s
7583/// - &s.zz[1].yy -> s, if zz is an array
7584/// - *(x + 1) -> x, if x is an array
7585/// - &"123"[2] -> 0
7586/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007587static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007588 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007589 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007590 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007591 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007592 // If this is an arrow operator, the address is an offset from
7593 // the base's value, so the object the base refers to is
7594 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007595 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007596 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007597 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007598 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007599 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007600 // FIXME: This code shouldn't be necessary! We should catch the implicit
7601 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007602 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7603 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7604 if (ICE->getSubExpr()->getType()->isArrayType())
7605 return getPrimaryDecl(ICE->getSubExpr());
7606 }
7607 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007608 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007609 case Stmt::UnaryOperatorClass: {
7610 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007611
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007612 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007613 case UO_Real:
7614 case UO_Imag:
7615 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007616 return getPrimaryDecl(UO->getSubExpr());
7617 default:
7618 return 0;
7619 }
7620 }
Steve Naroff47500512007-04-19 23:00:49 +00007621 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007622 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007623 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007624 // If the result of an implicit cast is an l-value, we care about
7625 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007626 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007627 default:
7628 return 0;
7629 }
7630}
7631
7632/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007633/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007634/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007635/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007636/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007637/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007638/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007639static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7640 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007641 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007642 return S.Context.DependentTy;
7643 if (OrigOp->getType() == S.Context.OverloadTy)
7644 return S.Context.OverloadTy;
John McCall8d08b9b2010-08-27 09:08:28 +00007645
John McCall4bc41ae2010-11-18 19:01:18 +00007646 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007647 if (PR.isInvalid()) return QualType();
7648 OrigOp = PR.take();
7649
John McCall8d08b9b2010-08-27 09:08:28 +00007650 // Make sure to ignore parentheses in subsequent checks
7651 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007652
John McCall4bc41ae2010-11-18 19:01:18 +00007653 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007654 // Implement C99-only parts of addressof rules.
7655 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007656 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007657 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7658 // (assuming the deref expression is valid).
7659 return uOp->getSubExpr()->getType();
7660 }
7661 // Technically, there should be a check for array subscript
7662 // expressions here, but the result of one is always an lvalue anyway.
7663 }
John McCallf3a88602011-02-03 08:15:49 +00007664 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007665 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007666
Chris Lattner9156f1b2010-07-05 19:17:26 +00007667 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007668 bool sfinae = S.isSFINAEContext();
7669 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7670 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007671 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007672 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007673 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007674 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007675 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007676 } else if (lval == Expr::LV_MemberFunction) {
7677 // If it's an instance method, make a member pointer.
7678 // The expression must have exactly the form &A::foo.
7679
7680 // If the underlying expression isn't a decl ref, give up.
7681 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007682 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007683 << OrigOp->getSourceRange();
7684 return QualType();
7685 }
7686 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7687 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7688
7689 // The id-expression was parenthesized.
7690 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007691 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007692 << OrigOp->getSourceRange();
7693
7694 // The method was named without a qualifier.
7695 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007696 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007697 << op->getSourceRange();
7698 }
7699
John McCall4bc41ae2010-11-18 19:01:18 +00007700 return S.Context.getMemberPointerType(op->getType(),
7701 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007702 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007703 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007704 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007705 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007706 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007707 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007708 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007709 return QualType();
7710 }
John McCall086a4642010-11-24 05:12:34 +00007711 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007712 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007713 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007714 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007715 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007716 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007717 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007718 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007719 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007720 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007721 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007722 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007723 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007724 << "property expression" << op->getSourceRange();
7725 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007726 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007727 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007728 // with the register storage-class specifier.
7729 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007730 // in C++ it is not error to take address of a register
7731 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007732 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007733 !S.getLangOptions().CPlusPlus) {
7734 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007735 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007736 return QualType();
7737 }
John McCalld14a8642009-11-21 08:51:07 +00007738 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007739 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007740 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007741 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007742 // Could be a pointer to member, though, if there is an explicit
7743 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007744 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007745 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007746 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007747 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007748 S.Diag(OpLoc,
7749 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007750 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007751 return QualType();
7752 }
Mike Stump11289f42009-09-09 15:08:12 +00007753
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007754 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7755 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007756 return S.Context.getMemberPointerType(op->getType(),
7757 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007758 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007759 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007760 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007761 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007762 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007763
Eli Friedmance7f9002009-05-16 23:27:50 +00007764 if (lval == Expr::LV_IncompleteVoidType) {
7765 // Taking the address of a void variable is technically illegal, but we
7766 // allow it in cases which are otherwise valid.
7767 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007768 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007769 }
7770
Steve Naroff47500512007-04-19 23:00:49 +00007771 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007772 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007773 return S.Context.getObjCObjectPointerType(op->getType());
7774 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007775}
7776
Chris Lattner9156f1b2010-07-05 19:17:26 +00007777/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007778static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7779 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007780 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007781 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007782
John McCall4bc41ae2010-11-18 19:01:18 +00007783 S.UsualUnaryConversions(Op);
Chris Lattner9156f1b2010-07-05 19:17:26 +00007784 QualType OpTy = Op->getType();
7785 QualType Result;
7786
7787 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7788 // is an incomplete type or void. It would be possible to warn about
7789 // dereferencing a void pointer, but it's completely well-defined, and such a
7790 // warning is unlikely to catch any mistakes.
7791 if (const PointerType *PT = OpTy->getAs<PointerType>())
7792 Result = PT->getPointeeType();
7793 else if (const ObjCObjectPointerType *OPT =
7794 OpTy->getAs<ObjCObjectPointerType>())
7795 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007796 else {
John McCall4bc41ae2010-11-18 19:01:18 +00007797 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007798 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007799 if (PR.take() != Op)
7800 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007801 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007802
Chris Lattner9156f1b2010-07-05 19:17:26 +00007803 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007804 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007805 << OpTy << Op->getSourceRange();
7806 return QualType();
7807 }
John McCall4bc41ae2010-11-18 19:01:18 +00007808
7809 // Dereferences are usually l-values...
7810 VK = VK_LValue;
7811
7812 // ...except that certain expressions are never l-values in C.
7813 if (!S.getLangOptions().CPlusPlus &&
7814 IsCForbiddenLValueType(S.Context, Result))
7815 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007816
7817 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007818}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007819
John McCalle3027922010-08-25 11:45:40 +00007820static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007821 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007822 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007823 switch (Kind) {
7824 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007825 case tok::periodstar: Opc = BO_PtrMemD; break;
7826 case tok::arrowstar: Opc = BO_PtrMemI; break;
7827 case tok::star: Opc = BO_Mul; break;
7828 case tok::slash: Opc = BO_Div; break;
7829 case tok::percent: Opc = BO_Rem; break;
7830 case tok::plus: Opc = BO_Add; break;
7831 case tok::minus: Opc = BO_Sub; break;
7832 case tok::lessless: Opc = BO_Shl; break;
7833 case tok::greatergreater: Opc = BO_Shr; break;
7834 case tok::lessequal: Opc = BO_LE; break;
7835 case tok::less: Opc = BO_LT; break;
7836 case tok::greaterequal: Opc = BO_GE; break;
7837 case tok::greater: Opc = BO_GT; break;
7838 case tok::exclaimequal: Opc = BO_NE; break;
7839 case tok::equalequal: Opc = BO_EQ; break;
7840 case tok::amp: Opc = BO_And; break;
7841 case tok::caret: Opc = BO_Xor; break;
7842 case tok::pipe: Opc = BO_Or; break;
7843 case tok::ampamp: Opc = BO_LAnd; break;
7844 case tok::pipepipe: Opc = BO_LOr; break;
7845 case tok::equal: Opc = BO_Assign; break;
7846 case tok::starequal: Opc = BO_MulAssign; break;
7847 case tok::slashequal: Opc = BO_DivAssign; break;
7848 case tok::percentequal: Opc = BO_RemAssign; break;
7849 case tok::plusequal: Opc = BO_AddAssign; break;
7850 case tok::minusequal: Opc = BO_SubAssign; break;
7851 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7852 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7853 case tok::ampequal: Opc = BO_AndAssign; break;
7854 case tok::caretequal: Opc = BO_XorAssign; break;
7855 case tok::pipeequal: Opc = BO_OrAssign; break;
7856 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007857 }
7858 return Opc;
7859}
7860
John McCalle3027922010-08-25 11:45:40 +00007861static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007862 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007863 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007864 switch (Kind) {
7865 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007866 case tok::plusplus: Opc = UO_PreInc; break;
7867 case tok::minusminus: Opc = UO_PreDec; break;
7868 case tok::amp: Opc = UO_AddrOf; break;
7869 case tok::star: Opc = UO_Deref; break;
7870 case tok::plus: Opc = UO_Plus; break;
7871 case tok::minus: Opc = UO_Minus; break;
7872 case tok::tilde: Opc = UO_Not; break;
7873 case tok::exclaim: Opc = UO_LNot; break;
7874 case tok::kw___real: Opc = UO_Real; break;
7875 case tok::kw___imag: Opc = UO_Imag; break;
7876 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007877 }
7878 return Opc;
7879}
7880
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007881/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7882/// This warning is only emitted for builtin assignment operations. It is also
7883/// suppressed in the event of macro expansions.
7884static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7885 SourceLocation OpLoc) {
7886 if (!S.ActiveTemplateInstantiations.empty())
7887 return;
7888 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7889 return;
7890 lhs = lhs->IgnoreParenImpCasts();
7891 rhs = rhs->IgnoreParenImpCasts();
7892 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7893 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7894 if (!LeftDeclRef || !RightDeclRef ||
7895 LeftDeclRef->getLocation().isMacroID() ||
7896 RightDeclRef->getLocation().isMacroID())
7897 return;
7898 const ValueDecl *LeftDecl =
7899 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7900 const ValueDecl *RightDecl =
7901 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7902 if (LeftDecl != RightDecl)
7903 return;
7904 if (LeftDecl->getType().isVolatileQualified())
7905 return;
7906 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7907 if (RefTy->getPointeeType().isVolatileQualified())
7908 return;
7909
7910 S.Diag(OpLoc, diag::warn_self_assignment)
7911 << LeftDeclRef->getType()
7912 << lhs->getSourceRange() << rhs->getSourceRange();
7913}
7914
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007915/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7916/// operator @p Opc at location @c TokLoc. This routine only supports
7917/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007918ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007919 BinaryOperatorKind Opc,
John McCalle3027922010-08-25 11:45:40 +00007920 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007921 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007922 // The following two variables are used for compound assignment operators
7923 QualType CompLHSTy; // Type of LHS after promotions for computation
7924 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007925 ExprValueKind VK = VK_RValue;
7926 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007927
7928 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007929 case BO_Assign:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007930 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007931 if (getLangOptions().CPlusPlus &&
7932 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall4bc41ae2010-11-18 19:01:18 +00007933 VK = lhs->getValueKind();
7934 OK = lhs->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007935 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007936 if (!ResultTy.isNull())
7937 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007938 break;
John McCalle3027922010-08-25 11:45:40 +00007939 case BO_PtrMemD:
7940 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007941 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007942 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007943 break;
John McCalle3027922010-08-25 11:45:40 +00007944 case BO_Mul:
7945 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007946 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007947 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007948 break;
John McCalle3027922010-08-25 11:45:40 +00007949 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007950 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7951 break;
John McCalle3027922010-08-25 11:45:40 +00007952 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007953 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7954 break;
John McCalle3027922010-08-25 11:45:40 +00007955 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007956 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7957 break;
John McCalle3027922010-08-25 11:45:40 +00007958 case BO_Shl:
7959 case BO_Shr:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007960 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
7961 break;
John McCalle3027922010-08-25 11:45:40 +00007962 case BO_LE:
7963 case BO_LT:
7964 case BO_GE:
7965 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007966 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007967 break;
John McCalle3027922010-08-25 11:45:40 +00007968 case BO_EQ:
7969 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007970 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007971 break;
John McCalle3027922010-08-25 11:45:40 +00007972 case BO_And:
7973 case BO_Xor:
7974 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007975 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7976 break;
John McCalle3027922010-08-25 11:45:40 +00007977 case BO_LAnd:
7978 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007979 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007980 break;
John McCalle3027922010-08-25 11:45:40 +00007981 case BO_MulAssign:
7982 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007983 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007984 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007985 CompLHSTy = CompResultTy;
7986 if (!CompResultTy.isNull())
7987 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007988 break;
John McCalle3027922010-08-25 11:45:40 +00007989 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007990 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7991 CompLHSTy = CompResultTy;
7992 if (!CompResultTy.isNull())
7993 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007994 break;
John McCalle3027922010-08-25 11:45:40 +00007995 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007996 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7997 if (!CompResultTy.isNull())
7998 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007999 break;
John McCalle3027922010-08-25 11:45:40 +00008000 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008001 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8002 if (!CompResultTy.isNull())
8003 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008004 break;
John McCalle3027922010-08-25 11:45:40 +00008005 case BO_ShlAssign:
8006 case BO_ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008007 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
8008 CompLHSTy = CompResultTy;
8009 if (!CompResultTy.isNull())
8010 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008011 break;
John McCalle3027922010-08-25 11:45:40 +00008012 case BO_AndAssign:
8013 case BO_XorAssign:
8014 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008015 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8016 CompLHSTy = CompResultTy;
8017 if (!CompResultTy.isNull())
8018 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008019 break;
John McCalle3027922010-08-25 11:45:40 +00008020 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00008021 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCall7decc9e2010-11-18 06:31:45 +00008022 if (getLangOptions().CPlusPlus) {
8023 VK = rhs->getValueKind();
8024 OK = rhs->getObjectKind();
8025 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008026 break;
8027 }
8028 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008029 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008030 if (CompResultTy.isNull())
John McCall7decc9e2010-11-18 06:31:45 +00008031 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
8032 VK, OK, OpLoc));
8033
John McCall34376a62010-12-04 03:47:34 +00008034 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008035 VK = VK_LValue;
8036 OK = lhs->getObjectKind();
8037 }
8038 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
8039 VK, OK, CompLHSTy,
8040 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008041}
8042
Sebastian Redl44615072009-10-27 12:10:02 +00008043/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8044/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008045static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8046 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008047 const PartialDiagnostic &FirstNote,
8048 SourceRange FirstParenRange,
8049 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00008050 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008051 Self.Diag(Loc, PD);
8052
8053 if (!FirstNote.getDiagID())
8054 return;
8055
8056 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8057 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8058 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008059 return;
8060 }
8061
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008062 Self.Diag(Loc, FirstNote)
8063 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00008064 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008065
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008066 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008067 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008068
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008069 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8070 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8071 // We can't display the parentheses, so just dig the
8072 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008073 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008074 return;
8075 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008076
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008077 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00008078 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8079 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008080}
8081
Sebastian Redl44615072009-10-27 12:10:02 +00008082/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8083/// operators are mixed in a way that suggests that the programmer forgot that
8084/// comparison operators have higher precedence. The most typical example of
8085/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008086static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008087 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00008088 typedef BinaryOperator BinOp;
8089 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8090 rhsopc = static_cast<BinOp::Opcode>(-1);
8091 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008092 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00008093 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008094 rhsopc = BO->getOpcode();
8095
8096 // Subs are not binary operators.
8097 if (lhsopc == -1 && rhsopc == -1)
8098 return;
8099
8100 // Bitwise operations are sometimes used as eager logical ops.
8101 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00008102 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8103 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008104 return;
8105
Sebastian Redl44615072009-10-27 12:10:02 +00008106 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008107 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008108 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008109 << SourceRange(lhs->getLocStart(), OpLoc)
8110 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008111 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008112 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008113 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
8114 Self.PDiag(diag::note_precedence_bitwise_silence)
8115 << BinOp::getOpcodeStr(lhsopc),
8116 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00008117 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008118 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008119 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008120 << SourceRange(OpLoc, rhs->getLocEnd())
8121 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008122 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008123 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008124 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
8125 Self.PDiag(diag::note_precedence_bitwise_silence)
8126 << BinOp::getOpcodeStr(rhsopc),
8127 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00008128}
8129
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008130/// \brief It accepts a '&&' expr that is inside a '||' one.
8131/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8132/// in parentheses.
8133static void
8134EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8135 Expr *E) {
8136 assert(isa<BinaryOperator>(E) &&
8137 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
8138 SuggestParentheses(Self, OpLoc,
8139 Self.PDiag(diag::warn_logical_and_in_logical_or)
8140 << E->getSourceRange(),
8141 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8142 E->getSourceRange(),
8143 Self.PDiag(0), SourceRange());
8144}
8145
8146/// \brief Returns true if the given expression can be evaluated as a constant
8147/// 'true'.
8148static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8149 bool Res;
8150 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8151}
8152
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008153/// \brief Returns true if the given expression can be evaluated as a constant
8154/// 'false'.
8155static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8156 bool Res;
8157 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8158}
8159
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008160/// \brief Look for '&&' in the left hand of a '||' expr.
8161static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008162 Expr *OrLHS, Expr *OrRHS) {
8163 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008164 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008165 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8166 if (EvaluatesAsFalse(S, OrRHS))
8167 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008168 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8169 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8170 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8171 } else if (Bop->getOpcode() == BO_LOr) {
8172 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8173 // If it's "a || b && 1 || c" we didn't warn earlier for
8174 // "a || b && 1", but warn now.
8175 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8176 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8177 }
8178 }
8179 }
8180}
8181
8182/// \brief Look for '&&' in the right hand of a '||' expr.
8183static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008184 Expr *OrLHS, Expr *OrRHS) {
8185 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008186 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008187 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8188 if (EvaluatesAsFalse(S, OrLHS))
8189 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008190 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8191 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8192 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008193 }
8194 }
8195}
8196
Sebastian Redl43028242009-10-26 15:24:15 +00008197/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008198/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008199static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008200 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008201 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008202 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008203 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8204
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008205 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8206 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008207 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008208 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8209 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008210 }
Sebastian Redl43028242009-10-26 15:24:15 +00008211}
8212
Steve Naroff218bc2b2007-05-04 21:54:46 +00008213// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008214ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008215 tok::TokenKind Kind,
8216 Expr *lhs, Expr *rhs) {
8217 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00008218 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8219 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008220
Sebastian Redl43028242009-10-26 15:24:15 +00008221 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8222 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8223
Douglas Gregor5287f092009-11-05 00:51:44 +00008224 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8225}
8226
John McCalldadc5752010-08-24 06:29:42 +00008227ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008228 BinaryOperatorKind Opc,
8229 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00008230 if (getLangOptions().CPlusPlus) {
8231 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008232
John McCall622114c2010-12-06 05:26:58 +00008233 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8234 UseBuiltinOperator = false;
8235 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8236 UseBuiltinOperator = true;
8237 } else {
8238 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8239 !rhs->getType()->isOverloadableType();
8240 }
8241
8242 if (!UseBuiltinOperator) {
8243 // Find all of the overloaded operators visible from this
8244 // point. We perform both an operator-name lookup from the local
8245 // scope and an argument-dependent lookup based on the types of
8246 // the arguments.
8247 UnresolvedSet<16> Functions;
8248 OverloadedOperatorKind OverOp
8249 = BinaryOperator::getOverloadedOperator(Opc);
8250 if (S && OverOp != OO_None)
8251 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8252 Functions);
8253
8254 // Build the (potentially-overloaded, potentially-dependent)
8255 // binary operation.
8256 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8257 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008258 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008259
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008260 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00008261 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008262}
8263
John McCalldadc5752010-08-24 06:29:42 +00008264ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008265 UnaryOperatorKind Opc,
John McCall36226622010-10-12 02:09:17 +00008266 Expr *Input) {
John McCall7decc9e2010-11-18 06:31:45 +00008267 ExprValueKind VK = VK_RValue;
8268 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008269 QualType resultType;
8270 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008271 case UO_PreInc:
8272 case UO_PreDec:
8273 case UO_PostInc:
8274 case UO_PostDec:
John McCall4bc41ae2010-11-18 19:01:18 +00008275 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008276 Opc == UO_PreInc ||
8277 Opc == UO_PostInc,
8278 Opc == UO_PreInc ||
8279 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008280 break;
John McCalle3027922010-08-25 11:45:40 +00008281 case UO_AddrOf:
John McCall4bc41ae2010-11-18 19:01:18 +00008282 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008283 break;
John McCalle3027922010-08-25 11:45:40 +00008284 case UO_Deref:
Douglas Gregorb92a1562010-02-03 00:27:59 +00008285 DefaultFunctionArrayLvalueConversion(Input);
John McCall4bc41ae2010-11-18 19:01:18 +00008286 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008287 break;
John McCalle3027922010-08-25 11:45:40 +00008288 case UO_Plus:
8289 case UO_Minus:
Steve Naroff31090012007-07-16 21:54:35 +00008290 UsualUnaryConversions(Input);
8291 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008292 if (resultType->isDependentType())
8293 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008294 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8295 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008296 break;
8297 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8298 resultType->isEnumeralType())
8299 break;
8300 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008301 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008302 resultType->isPointerType())
8303 break;
John McCall36226622010-10-12 02:09:17 +00008304 else if (resultType->isPlaceholderType()) {
8305 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8306 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008307 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008308 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008309
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008310 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8311 << resultType << Input->getSourceRange());
John McCalle3027922010-08-25 11:45:40 +00008312 case UO_Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00008313 UsualUnaryConversions(Input);
8314 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008315 if (resultType->isDependentType())
8316 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008317 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8318 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8319 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008320 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008321 << resultType << Input->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008322 else if (resultType->hasIntegerRepresentation())
8323 break;
8324 else if (resultType->isPlaceholderType()) {
8325 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8326 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008327 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008328 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008329 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8330 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008331 }
Steve Naroff35d85152007-05-07 00:24:15 +00008332 break;
John McCalle3027922010-08-25 11:45:40 +00008333 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008334 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00008335 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00008336 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008337 if (resultType->isDependentType())
8338 break;
John McCall36226622010-10-12 02:09:17 +00008339 if (resultType->isScalarType()) { // C99 6.5.3.3p1
8340 // ok, fallthrough
8341 } else if (resultType->isPlaceholderType()) {
8342 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8343 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008344 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008345 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008346 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8347 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008348 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008349
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008350 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008351 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008352 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008353 break;
John McCalle3027922010-08-25 11:45:40 +00008354 case UO_Real:
8355 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008356 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008357 // _Real and _Imag map ordinary l-values into ordinary l-values.
8358 if (Input->getValueKind() != VK_RValue &&
8359 Input->getObjectKind() == OK_Ordinary)
8360 VK = Input->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008361 break;
John McCalle3027922010-08-25 11:45:40 +00008362 case UO_Extension:
Chris Lattner86554282007-06-08 22:32:33 +00008363 resultType = Input->getType();
John McCall7decc9e2010-11-18 06:31:45 +00008364 VK = Input->getValueKind();
8365 OK = Input->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008366 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008367 }
8368 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008369 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008370
John McCall7decc9e2010-11-18 06:31:45 +00008371 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
8372 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008373}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008374
John McCalldadc5752010-08-24 06:29:42 +00008375ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008376 UnaryOperatorKind Opc,
8377 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008378 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008379 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008380 // Find all of the overloaded operators visible from this
8381 // point. We perform both an operator-name lookup from the local
8382 // scope and an argument-dependent lookup based on the types of
8383 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008384 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008385 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008386 if (S && OverOp != OO_None)
8387 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8388 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008389
John McCallb268a282010-08-23 23:25:46 +00008390 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008391 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008392
John McCallb268a282010-08-23 23:25:46 +00008393 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008394}
8395
Douglas Gregor5287f092009-11-05 00:51:44 +00008396// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008397ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008398 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008399 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008400}
8401
Steve Naroff66356bd2007-09-16 14:56:35 +00008402/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008403ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008404 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008405 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008406 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008407 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008408 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008409}
8410
John McCalldadc5752010-08-24 06:29:42 +00008411ExprResult
John McCallb268a282010-08-23 23:25:46 +00008412Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008413 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008414 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8415 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8416
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008417 bool isFileScope
8418 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008419 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008420 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008421
Chris Lattner366727f2007-07-24 16:58:17 +00008422 // FIXME: there are a variety of strange constraints to enforce here, for
8423 // example, it is not possible to goto into a stmt expression apparently.
8424 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008425
Chris Lattner366727f2007-07-24 16:58:17 +00008426 // If there are sub stmts in the compound stmt, take the type of the last one
8427 // as the type of the stmtexpr.
8428 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008429 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008430 if (!Compound->body_empty()) {
8431 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008432 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008433 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008434 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8435 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008436 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008437 }
8438 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008439 // Do function/array conversion on the last expression, but not
8440 // lvalue-to-rvalue. However, initialize an unqualified type.
8441 DefaultFunctionArrayConversion(LastExpr);
8442 Ty = LastExpr->getType().getUnqualifiedType();
8443
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008444 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8445 ExprResult Res = PerformCopyInitialization(
8446 InitializedEntity::InitializeResult(LPLoc,
8447 Ty,
8448 false),
8449 SourceLocation(),
8450 Owned(LastExpr));
8451 if (Res.isInvalid())
8452 return ExprError();
8453 if ((LastExpr = Res.takeAs<Expr>())) {
8454 if (!LastLabelStmt)
8455 Compound->setLastStmt(LastExpr);
8456 else
8457 LastLabelStmt->setSubStmt(LastExpr);
8458 StmtExprMayBindToTemp = true;
8459 }
8460 }
8461 }
Chris Lattner944d3062008-07-26 19:51:01 +00008462 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008463
Eli Friedmanba961a92009-03-23 00:24:07 +00008464 // FIXME: Check that expression type is complete/non-abstract; statement
8465 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008466 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8467 if (StmtExprMayBindToTemp)
8468 return MaybeBindToTemporary(ResStmtExpr);
8469 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008470}
Steve Naroff78864672007-08-01 22:05:33 +00008471
John McCalldadc5752010-08-24 06:29:42 +00008472ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008473 TypeSourceInfo *TInfo,
8474 OffsetOfComponent *CompPtr,
8475 unsigned NumComponents,
8476 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008477 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008478 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008479 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008480
Chris Lattnerf17bd422007-08-30 17:45:32 +00008481 // We must have at least one component that refers to the type, and the first
8482 // one is known to be a field designator. Verify that the ArgTy represents
8483 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008484 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008485 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8486 << ArgTy << TypeRange);
8487
8488 // Type must be complete per C99 7.17p3 because a declaring a variable
8489 // with an incomplete type would be ill-formed.
8490 if (!Dependent
8491 && RequireCompleteType(BuiltinLoc, ArgTy,
8492 PDiag(diag::err_offsetof_incomplete_type)
8493 << TypeRange))
8494 return ExprError();
8495
Chris Lattner78502cf2007-08-31 21:49:13 +00008496 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8497 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008498 // FIXME: This diagnostic isn't actually visible because the location is in
8499 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008500 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008501 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8502 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008503
8504 bool DidWarnAboutNonPOD = false;
8505 QualType CurrentType = ArgTy;
8506 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8507 llvm::SmallVector<OffsetOfNode, 4> Comps;
8508 llvm::SmallVector<Expr*, 4> Exprs;
8509 for (unsigned i = 0; i != NumComponents; ++i) {
8510 const OffsetOfComponent &OC = CompPtr[i];
8511 if (OC.isBrackets) {
8512 // Offset of an array sub-field. TODO: Should we allow vector elements?
8513 if (!CurrentType->isDependentType()) {
8514 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8515 if(!AT)
8516 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8517 << CurrentType);
8518 CurrentType = AT->getElementType();
8519 } else
8520 CurrentType = Context.DependentTy;
8521
8522 // The expression must be an integral expression.
8523 // FIXME: An integral constant expression?
8524 Expr *Idx = static_cast<Expr*>(OC.U.E);
8525 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8526 !Idx->getType()->isIntegerType())
8527 return ExprError(Diag(Idx->getLocStart(),
8528 diag::err_typecheck_subscript_not_integer)
8529 << Idx->getSourceRange());
8530
8531 // Record this array index.
8532 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8533 Exprs.push_back(Idx);
8534 continue;
8535 }
8536
8537 // Offset of a field.
8538 if (CurrentType->isDependentType()) {
8539 // We have the offset of a field, but we can't look into the dependent
8540 // type. Just record the identifier of the field.
8541 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8542 CurrentType = Context.DependentTy;
8543 continue;
8544 }
8545
8546 // We need to have a complete type to look into.
8547 if (RequireCompleteType(OC.LocStart, CurrentType,
8548 diag::err_offsetof_incomplete_type))
8549 return ExprError();
8550
8551 // Look for the designated field.
8552 const RecordType *RC = CurrentType->getAs<RecordType>();
8553 if (!RC)
8554 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8555 << CurrentType);
8556 RecordDecl *RD = RC->getDecl();
8557
8558 // C++ [lib.support.types]p5:
8559 // The macro offsetof accepts a restricted set of type arguments in this
8560 // International Standard. type shall be a POD structure or a POD union
8561 // (clause 9).
8562 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8563 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8564 DiagRuntimeBehavior(BuiltinLoc,
8565 PDiag(diag::warn_offsetof_non_pod_type)
8566 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8567 << CurrentType))
8568 DidWarnAboutNonPOD = true;
8569 }
8570
8571 // Look for the field.
8572 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8573 LookupQualifiedName(R, RD);
8574 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008575 IndirectFieldDecl *IndirectMemberDecl = 0;
8576 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008577 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008578 MemberDecl = IndirectMemberDecl->getAnonField();
8579 }
8580
Douglas Gregor882211c2010-04-28 22:16:22 +00008581 if (!MemberDecl)
8582 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8583 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8584 OC.LocEnd));
8585
Douglas Gregor10982ea2010-04-28 22:36:06 +00008586 // C99 7.17p3:
8587 // (If the specified member is a bit-field, the behavior is undefined.)
8588 //
8589 // We diagnose this as an error.
8590 if (MemberDecl->getBitWidth()) {
8591 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8592 << MemberDecl->getDeclName()
8593 << SourceRange(BuiltinLoc, RParenLoc);
8594 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8595 return ExprError();
8596 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008597
8598 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008599 if (IndirectMemberDecl)
8600 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008601
Douglas Gregord1702062010-04-29 00:18:15 +00008602 // If the member was found in a base class, introduce OffsetOfNodes for
8603 // the base class indirections.
8604 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8605 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008606 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008607 CXXBasePath &Path = Paths.front();
8608 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8609 B != BEnd; ++B)
8610 Comps.push_back(OffsetOfNode(B->Base));
8611 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008612
Francois Pichet783dd6e2010-11-21 06:08:52 +00008613 if (IndirectMemberDecl) {
8614 for (IndirectFieldDecl::chain_iterator FI =
8615 IndirectMemberDecl->chain_begin(),
8616 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8617 assert(isa<FieldDecl>(*FI));
8618 Comps.push_back(OffsetOfNode(OC.LocStart,
8619 cast<FieldDecl>(*FI), OC.LocEnd));
8620 }
8621 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008622 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008623
Douglas Gregor882211c2010-04-28 22:16:22 +00008624 CurrentType = MemberDecl->getType().getNonReferenceType();
8625 }
8626
8627 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8628 TInfo, Comps.data(), Comps.size(),
8629 Exprs.data(), Exprs.size(), RParenLoc));
8630}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008631
John McCalldadc5752010-08-24 06:29:42 +00008632ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008633 SourceLocation BuiltinLoc,
8634 SourceLocation TypeLoc,
8635 ParsedType argty,
8636 OffsetOfComponent *CompPtr,
8637 unsigned NumComponents,
8638 SourceLocation RPLoc) {
8639
Douglas Gregor882211c2010-04-28 22:16:22 +00008640 TypeSourceInfo *ArgTInfo;
8641 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8642 if (ArgTy.isNull())
8643 return ExprError();
8644
Eli Friedman06dcfd92010-08-05 10:15:45 +00008645 if (!ArgTInfo)
8646 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8647
8648 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8649 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008650}
8651
8652
John McCalldadc5752010-08-24 06:29:42 +00008653ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008654 Expr *CondExpr,
8655 Expr *LHSExpr, Expr *RHSExpr,
8656 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008657 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8658
John McCall7decc9e2010-11-18 06:31:45 +00008659 ExprValueKind VK = VK_RValue;
8660 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008661 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008662 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008663 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008664 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008665 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008666 } else {
8667 // The conditional expression is required to be a constant expression.
8668 llvm::APSInt condEval(32);
8669 SourceLocation ExpLoc;
8670 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008671 return ExprError(Diag(ExpLoc,
8672 diag::err_typecheck_choose_expr_requires_constant)
8673 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008674
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008675 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008676 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8677
8678 resType = ActiveExpr->getType();
8679 ValueDependent = ActiveExpr->isValueDependent();
8680 VK = ActiveExpr->getValueKind();
8681 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008682 }
8683
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008684 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008685 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008686 resType->isDependentType(),
8687 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008688}
8689
Steve Naroffc540d662008-09-03 18:15:37 +00008690//===----------------------------------------------------------------------===//
8691// Clang Extensions.
8692//===----------------------------------------------------------------------===//
8693
8694/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008695void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008696 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8697 PushBlockScope(BlockScope, Block);
8698 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008699 if (BlockScope)
8700 PushDeclContext(BlockScope, Block);
8701 else
8702 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008703}
8704
Mike Stump82f071f2009-02-04 22:31:32 +00008705void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008706 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008707 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008708 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008709
John McCall8cb7bdf2010-06-04 23:28:52 +00008710 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008711 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008712
John McCall3882ace2011-01-05 12:14:39 +00008713 // GetTypeForDeclarator always produces a function type for a block
8714 // literal signature. Furthermore, it is always a FunctionProtoType
8715 // unless the function was written with a typedef.
8716 assert(T->isFunctionType() &&
8717 "GetTypeForDeclarator made a non-function block signature");
8718
8719 // Look for an explicit signature in that function type.
8720 FunctionProtoTypeLoc ExplicitSignature;
8721
8722 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8723 if (isa<FunctionProtoTypeLoc>(tmp)) {
8724 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8725
8726 // Check whether that explicit signature was synthesized by
8727 // GetTypeForDeclarator. If so, don't save that as part of the
8728 // written signature.
8729 if (ExplicitSignature.getLParenLoc() ==
8730 ExplicitSignature.getRParenLoc()) {
8731 // This would be much cheaper if we stored TypeLocs instead of
8732 // TypeSourceInfos.
8733 TypeLoc Result = ExplicitSignature.getResultLoc();
8734 unsigned Size = Result.getFullDataSize();
8735 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8736 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8737
8738 ExplicitSignature = FunctionProtoTypeLoc();
8739 }
John McCalla3ccba02010-06-04 11:21:44 +00008740 }
Mike Stump11289f42009-09-09 15:08:12 +00008741
John McCall3882ace2011-01-05 12:14:39 +00008742 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8743 CurBlock->FunctionType = T;
8744
8745 const FunctionType *Fn = T->getAs<FunctionType>();
8746 QualType RetTy = Fn->getResultType();
8747 bool isVariadic =
8748 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8749
John McCall8e346702010-06-04 19:02:56 +00008750 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008751
John McCalla3ccba02010-06-04 11:21:44 +00008752 // Don't allow returning a objc interface by value.
8753 if (RetTy->isObjCObjectType()) {
8754 Diag(ParamInfo.getSourceRange().getBegin(),
8755 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8756 return;
8757 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008758
John McCalla3ccba02010-06-04 11:21:44 +00008759 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008760 // return type. TODO: what should we do with declarators like:
8761 // ^ * { ... }
8762 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008763 if (RetTy != Context.DependentTy)
8764 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008765
John McCalla3ccba02010-06-04 11:21:44 +00008766 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00008767 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008768 if (ExplicitSignature) {
8769 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8770 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008771 if (Param->getIdentifier() == 0 &&
8772 !Param->isImplicit() &&
8773 !Param->isInvalidDecl() &&
8774 !getLangOptions().CPlusPlus)
8775 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008776 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008777 }
John McCalla3ccba02010-06-04 11:21:44 +00008778
8779 // Fake up parameter variables if we have a typedef, like
8780 // ^ fntype { ... }
8781 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8782 for (FunctionProtoType::arg_type_iterator
8783 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8784 ParmVarDecl *Param =
8785 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8786 ParamInfo.getSourceRange().getBegin(),
8787 *I);
John McCall8e346702010-06-04 19:02:56 +00008788 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008789 }
Steve Naroffc540d662008-09-03 18:15:37 +00008790 }
John McCalla3ccba02010-06-04 11:21:44 +00008791
John McCall8e346702010-06-04 19:02:56 +00008792 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008793 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008794 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008795 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8796 CurBlock->TheDecl->param_end(),
8797 /*CheckParameterNames=*/false);
8798 }
8799
John McCalla3ccba02010-06-04 11:21:44 +00008800 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008801 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008802
John McCall8e346702010-06-04 19:02:56 +00008803 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008804 Diag(ParamInfo.getAttributes()->getLoc(),
8805 diag::warn_attribute_sentinel_not_variadic) << 1;
8806 // FIXME: remove the attribute.
8807 }
8808
8809 // Put the parameter variables in scope. We can bail out immediately
8810 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008811 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008812 return;
8813
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008814 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008815 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8816 (*AI)->setOwningFunction(CurBlock->TheDecl);
8817
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008818 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008819 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008820 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008821
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008822 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008823 }
John McCallf7b2fb52010-01-22 00:28:27 +00008824 }
Steve Naroffc540d662008-09-03 18:15:37 +00008825}
8826
8827/// ActOnBlockError - If there is an error parsing a block, this callback
8828/// is invoked to pop the information about the block from the action impl.
8829void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008830 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008831 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008832 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008833}
8834
8835/// ActOnBlockStmtExpr - This is called when the body of a block statement
8836/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008837ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008838 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008839 // If blocks are disabled, emit an error.
8840 if (!LangOpts.Blocks)
8841 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008842
Douglas Gregor9a28e842010-03-01 23:15:13 +00008843 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008844
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008845 PopDeclContext();
8846
Steve Naroffc540d662008-09-03 18:15:37 +00008847 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008848 if (!BSI->ReturnType.isNull())
8849 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008850
Mike Stump3bf1ab42009-07-28 22:04:01 +00008851 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008852 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008853
John McCallc63de662011-02-02 13:00:07 +00008854 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008855 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8856 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008857
John McCall8e346702010-06-04 19:02:56 +00008858 // If the user wrote a function type in some form, try to use that.
8859 if (!BSI->FunctionType.isNull()) {
8860 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8861
8862 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8863 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8864
8865 // Turn protoless block types into nullary block types.
8866 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008867 FunctionProtoType::ExtProtoInfo EPI;
8868 EPI.ExtInfo = Ext;
8869 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008870
8871 // Otherwise, if we don't need to change anything about the function type,
8872 // preserve its sugar structure.
8873 } else if (FTy->getResultType() == RetTy &&
8874 (!NoReturn || FTy->getNoReturnAttr())) {
8875 BlockTy = BSI->FunctionType;
8876
8877 // Otherwise, make the minimal modifications to the function type.
8878 } else {
8879 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008880 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8881 EPI.TypeQuals = 0; // FIXME: silently?
8882 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008883 BlockTy = Context.getFunctionType(RetTy,
8884 FPT->arg_type_begin(),
8885 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008886 EPI);
John McCall8e346702010-06-04 19:02:56 +00008887 }
8888
8889 // If we don't have a function type, just build one from nothing.
8890 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008891 FunctionProtoType::ExtProtoInfo EPI;
8892 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
8893 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008894 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008895
John McCall8e346702010-06-04 19:02:56 +00008896 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8897 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008898 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008899
Chris Lattner45542ea2009-04-19 05:28:12 +00008900 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00008901 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008902 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008903
Chris Lattner60f84492011-02-17 23:58:47 +00008904 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008905
John McCallc63de662011-02-02 13:00:07 +00008906 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCall1d570a72010-08-25 05:56:39 +00008907
Ted Kremenek918fe842010-03-20 21:06:02 +00008908 // Issue any analysis-based warnings.
Ted Kremenek0b405322010-03-23 00:13:23 +00008909 const sema::AnalysisBasedWarnings::Policy &WP =
8910 AnalysisWarnings.getDefaultPolicy();
John McCall1d570a72010-08-25 05:56:39 +00008911 AnalysisWarnings.IssueWarnings(WP, Result);
Ted Kremenek918fe842010-03-20 21:06:02 +00008912
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008913 PopFunctionOrBlockScope();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008914 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008915}
8916
John McCalldadc5752010-08-24 06:29:42 +00008917ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008918 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008919 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008920 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008921 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008922 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008923}
8924
John McCalldadc5752010-08-24 06:29:42 +00008925ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008926 Expr *E, TypeSourceInfo *TInfo,
8927 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008928 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008929
Eli Friedman121ba0c2008-08-09 23:32:40 +00008930 // Get the va_list type
8931 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008932 if (VaListType->isArrayType()) {
8933 // Deal with implicit array decay; for example, on x86-64,
8934 // va_list is an array, but it's supposed to decay to
8935 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008936 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008937 // Make sure the input expression also decays appropriately.
8938 UsualUnaryConversions(E);
8939 } else {
8940 // Otherwise, the va_list argument must be an l-value because
8941 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008942 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008943 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008944 return ExprError();
8945 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008946
Douglas Gregorad3150c2009-05-19 23:10:31 +00008947 if (!E->isTypeDependent() &&
8948 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008949 return ExprError(Diag(E->getLocStart(),
8950 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008951 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008952 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008953
Eli Friedmanba961a92009-03-23 00:24:07 +00008954 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008955 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008956
Abramo Bagnara27db2392010-08-10 10:06:15 +00008957 QualType T = TInfo->getType().getNonLValueExprType(Context);
8958 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008959}
8960
John McCalldadc5752010-08-24 06:29:42 +00008961ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008962 // The type of __null will be int or long, depending on the size of
8963 // pointers on the target.
8964 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008965 unsigned pw = Context.Target.getPointerWidth(0);
8966 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008967 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008968 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008969 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008970 else if (pw == Context.Target.getLongLongWidth())
8971 Ty = Context.LongLongTy;
8972 else {
8973 assert(!"I don't know size of pointer!");
8974 Ty = Context.IntTy;
8975 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008976
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008977 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008978}
8979
Alexis Huntc46382e2010-04-28 23:02:27 +00008980static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008981 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008982 if (!SemaRef.getLangOptions().ObjC1)
8983 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008984
Anders Carlssonace5d072009-11-10 04:46:30 +00008985 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8986 if (!PT)
8987 return;
8988
8989 // Check if the destination is of type 'id'.
8990 if (!PT->isObjCIdType()) {
8991 // Check if the destination is the 'NSString' interface.
8992 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8993 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8994 return;
8995 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008996
Anders Carlssonace5d072009-11-10 04:46:30 +00008997 // Strip off any parens and casts.
8998 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8999 if (!SL || SL->isWide())
9000 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009001
Douglas Gregora771f462010-03-31 17:46:05 +00009002 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009003}
9004
Chris Lattner9bad62c2008-01-04 18:04:52 +00009005bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9006 SourceLocation Loc,
9007 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009008 Expr *SrcExpr, AssignmentAction Action,
9009 bool *Complained) {
9010 if (Complained)
9011 *Complained = false;
9012
Chris Lattner9bad62c2008-01-04 18:04:52 +00009013 // Decode the result (notice that AST's are still created for extensions).
9014 bool isInvalid = false;
9015 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00009016 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009017
Chris Lattner9bad62c2008-01-04 18:04:52 +00009018 switch (ConvTy) {
9019 default: assert(0 && "Unknown conversion type");
9020 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009021 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009022 DiagKind = diag::ext_typecheck_convert_pointer_int;
9023 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009024 case IntToPointer:
9025 DiagKind = diag::ext_typecheck_convert_int_pointer;
9026 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009027 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009028 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009029 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9030 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009031 case IncompatiblePointerSign:
9032 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9033 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009034 case FunctionVoidPointer:
9035 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9036 break;
John McCall4fff8f62011-02-01 00:10:29 +00009037 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009038 // Perform array-to-pointer decay if necessary.
9039 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9040
John McCall4fff8f62011-02-01 00:10:29 +00009041 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9042 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9043 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9044 DiagKind = diag::err_typecheck_incompatible_address_space;
9045 break;
9046 }
9047
9048 llvm_unreachable("unknown error case for discarding qualifiers!");
9049 // fallthrough
9050 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009051 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009052 // If the qualifiers lost were because we were applying the
9053 // (deprecated) C++ conversion from a string literal to a char*
9054 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9055 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009056 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009057 // bit of refactoring (so that the second argument is an
9058 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009059 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009060 // C++ semantics.
9061 if (getLangOptions().CPlusPlus &&
9062 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9063 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009064 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9065 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009066 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009067 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009068 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009069 case IntToBlockPointer:
9070 DiagKind = diag::err_int_to_block_pointer;
9071 break;
9072 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009073 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009074 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009075 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009076 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009077 // it can give a more specific diagnostic.
9078 DiagKind = diag::warn_incompatible_qualified_id;
9079 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009080 case IncompatibleVectors:
9081 DiagKind = diag::warn_incompatible_vectors;
9082 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009083 case Incompatible:
9084 DiagKind = diag::err_typecheck_convert_incompatible;
9085 isInvalid = true;
9086 break;
9087 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009088
Douglas Gregorc68e1402010-04-09 00:35:39 +00009089 QualType FirstType, SecondType;
9090 switch (Action) {
9091 case AA_Assigning:
9092 case AA_Initializing:
9093 // The destination type comes first.
9094 FirstType = DstType;
9095 SecondType = SrcType;
9096 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009097
Douglas Gregorc68e1402010-04-09 00:35:39 +00009098 case AA_Returning:
9099 case AA_Passing:
9100 case AA_Converting:
9101 case AA_Sending:
9102 case AA_Casting:
9103 // The source type comes first.
9104 FirstType = SrcType;
9105 SecondType = DstType;
9106 break;
9107 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009108
Douglas Gregorc68e1402010-04-09 00:35:39 +00009109 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00009110 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009111 if (Complained)
9112 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009113 return isInvalid;
9114}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009115
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009116bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009117 llvm::APSInt ICEResult;
9118 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9119 if (Result)
9120 *Result = ICEResult;
9121 return false;
9122 }
9123
Anders Carlssone54e8a12008-11-30 19:50:32 +00009124 Expr::EvalResult EvalResult;
9125
Mike Stump4e1f26a2009-02-19 03:04:26 +00009126 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009127 EvalResult.HasSideEffects) {
9128 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9129
9130 if (EvalResult.Diag) {
9131 // We only show the note if it's not the usual "invalid subexpression"
9132 // or if it's actually in a subexpression.
9133 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9134 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9135 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9136 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009137
Anders Carlssone54e8a12008-11-30 19:50:32 +00009138 return true;
9139 }
9140
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009141 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9142 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009143
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009144 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009145 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9146 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009147 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009148
Anders Carlssone54e8a12008-11-30 19:50:32 +00009149 if (Result)
9150 *Result = EvalResult.Val.getInt();
9151 return false;
9152}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009153
Douglas Gregorff790f12009-11-26 00:44:06 +00009154void
Mike Stump11289f42009-09-09 15:08:12 +00009155Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009156 ExprEvalContexts.push_back(
9157 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009158}
9159
Mike Stump11289f42009-09-09 15:08:12 +00009160void
Douglas Gregorff790f12009-11-26 00:44:06 +00009161Sema::PopExpressionEvaluationContext() {
9162 // Pop the current expression evaluation context off the stack.
9163 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9164 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009165
Douglas Gregorfab31f42009-12-12 07:57:52 +00009166 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9167 if (Rec.PotentiallyReferenced) {
9168 // Mark any remaining declarations in the current position of the stack
9169 // as "referenced". If they were not meant to be referenced, semantic
9170 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009171 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009172 I = Rec.PotentiallyReferenced->begin(),
9173 IEnd = Rec.PotentiallyReferenced->end();
9174 I != IEnd; ++I)
9175 MarkDeclarationReferenced(I->first, I->second);
9176 }
9177
9178 if (Rec.PotentiallyDiagnosed) {
9179 // Emit any pending diagnostics.
9180 for (PotentiallyEmittedDiagnostics::iterator
9181 I = Rec.PotentiallyDiagnosed->begin(),
9182 IEnd = Rec.PotentiallyDiagnosed->end();
9183 I != IEnd; ++I)
9184 Diag(I->first, I->second);
9185 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009186 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009187
9188 // When are coming out of an unevaluated context, clear out any
9189 // temporaries that we may have created as part of the evaluation of
9190 // the expression in that context: they aren't relevant because they
9191 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009192 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00009193 ExprTemporaries.size() > Rec.NumTemporaries)
9194 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9195 ExprTemporaries.end());
9196
9197 // Destroy the popped expression evaluation record.
9198 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009199}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009200
9201/// \brief Note that the given declaration was referenced in the source code.
9202///
9203/// This routine should be invoke whenever a given declaration is referenced
9204/// in the source code, and where that reference occurred. If this declaration
9205/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9206/// C99 6.9p3), then the declaration will be marked as used.
9207///
9208/// \param Loc the location where the declaration was referenced.
9209///
9210/// \param D the declaration that has been referenced by the source code.
9211void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9212 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009213
Douglas Gregorebada0772010-06-17 23:14:26 +00009214 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009215 return;
Mike Stump11289f42009-09-09 15:08:12 +00009216
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00009217 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9218 // template or not. The reason for this is that unevaluated expressions
9219 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9220 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009221 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009222 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009223 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009224 return;
9225 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009226
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009227 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9228 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009229
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009230 // Do not mark anything as "used" within a dependent context; wait for
9231 // an instantiation.
9232 if (CurContext->isDependentContext())
9233 return;
Mike Stump11289f42009-09-09 15:08:12 +00009234
Douglas Gregorff790f12009-11-26 00:44:06 +00009235 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009236 case Unevaluated:
9237 // We are in an expression that is not potentially evaluated; do nothing.
9238 return;
Mike Stump11289f42009-09-09 15:08:12 +00009239
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009240 case PotentiallyEvaluated:
9241 // We are in a potentially-evaluated expression, so this declaration is
9242 // "used"; handle this below.
9243 break;
Mike Stump11289f42009-09-09 15:08:12 +00009244
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009245 case PotentiallyPotentiallyEvaluated:
9246 // We are in an expression that may be potentially evaluated; queue this
9247 // declaration reference until we know whether the expression is
9248 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009249 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009250 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009251
9252 case PotentiallyEvaluatedIfUsed:
9253 // Referenced declarations will only be used if the construct in the
9254 // containing expression is used.
9255 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009256 }
Mike Stump11289f42009-09-09 15:08:12 +00009257
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009258 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009259 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009260 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00009261 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00009262 if (Constructor->getParent()->hasTrivialConstructor())
9263 return;
9264 if (!Constructor->isUsed(false))
9265 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00009266 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00009267 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009268 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009269 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9270 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009271
Douglas Gregor88d292c2010-05-13 16:44:06 +00009272 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009273 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009274 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009275 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009276 if (Destructor->isVirtual())
9277 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009278 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9279 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9280 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009281 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009282 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009283 } else if (MethodDecl->isVirtual())
9284 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009285 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009286 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009287 // Recursive functions should be marked when used from another function.
9288 if (CurContext == Function) return;
9289
Mike Stump11289f42009-09-09 15:08:12 +00009290 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009291 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009292 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009293 bool AlreadyInstantiated = false;
9294 if (FunctionTemplateSpecializationInfo *SpecInfo
9295 = Function->getTemplateSpecializationInfo()) {
9296 if (SpecInfo->getPointOfInstantiation().isInvalid())
9297 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009298 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009299 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009300 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009301 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009302 = Function->getMemberSpecializationInfo()) {
9303 if (MSInfo->getPointOfInstantiation().isInvalid())
9304 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009305 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009306 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009307 AlreadyInstantiated = true;
9308 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009309
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009310 if (!AlreadyInstantiated) {
9311 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9312 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9313 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9314 Loc));
9315 else
Chandler Carruth54080172010-08-25 08:44:16 +00009316 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009317 }
John McCall83779672011-02-19 02:53:41 +00009318 } else {
9319 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009320 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9321 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009322 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009323 MarkDeclarationReferenced(Loc, *i);
9324 }
John McCall83779672011-02-19 02:53:41 +00009325 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009326
John McCall83779672011-02-19 02:53:41 +00009327 // Keep track of used but undefined functions.
9328 if (!Function->isPure() && !Function->hasBody() &&
9329 Function->getLinkage() != ExternalLinkage) {
9330 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9331 if (old.isInvalid()) old = Loc;
9332 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009333
John McCall83779672011-02-19 02:53:41 +00009334 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009335 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009336 }
Mike Stump11289f42009-09-09 15:08:12 +00009337
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009338 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009339 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009340 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009341 Var->getInstantiatedFromStaticDataMember()) {
9342 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9343 assert(MSInfo && "Missing member specialization information?");
9344 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9345 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9346 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +00009347 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009348 }
9349 }
Mike Stump11289f42009-09-09 15:08:12 +00009350
John McCall83779672011-02-19 02:53:41 +00009351 // Keep track of used but undefined variables.
9352 if (Var->hasDefinition() == VarDecl::DeclarationOnly
9353 && Var->getLinkage() != ExternalLinkage) {
9354 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9355 if (old.isInvalid()) old = Loc;
9356 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009357
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009358 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009359 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009360 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009361}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009362
Douglas Gregor5597ab42010-05-07 23:12:07 +00009363namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009364 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009365 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009366 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009367 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9368 Sema &S;
9369 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009370
Douglas Gregor5597ab42010-05-07 23:12:07 +00009371 public:
9372 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009373
Douglas Gregor5597ab42010-05-07 23:12:07 +00009374 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009375
9376 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9377 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009378 };
9379}
9380
Chandler Carruthaf80f662010-06-09 08:17:30 +00009381bool MarkReferencedDecls::TraverseTemplateArgument(
9382 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009383 if (Arg.getKind() == TemplateArgument::Declaration) {
9384 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9385 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009386
9387 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009388}
9389
Chandler Carruthaf80f662010-06-09 08:17:30 +00009390bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009391 if (ClassTemplateSpecializationDecl *Spec
9392 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9393 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009394 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009395 }
9396
Chandler Carruthc65667c2010-06-10 10:31:57 +00009397 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009398}
9399
9400void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9401 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009402 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009403}
9404
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009405namespace {
9406 /// \brief Helper class that marks all of the declarations referenced by
9407 /// potentially-evaluated subexpressions as "referenced".
9408 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9409 Sema &S;
9410
9411 public:
9412 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9413
9414 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9415
9416 void VisitDeclRefExpr(DeclRefExpr *E) {
9417 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9418 }
9419
9420 void VisitMemberExpr(MemberExpr *E) {
9421 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009422 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009423 }
9424
9425 void VisitCXXNewExpr(CXXNewExpr *E) {
9426 if (E->getConstructor())
9427 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9428 if (E->getOperatorNew())
9429 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9430 if (E->getOperatorDelete())
9431 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009432 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009433 }
9434
9435 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9436 if (E->getOperatorDelete())
9437 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009438 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9439 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9440 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9441 S.MarkDeclarationReferenced(E->getLocStart(),
9442 S.LookupDestructor(Record));
9443 }
9444
Douglas Gregor32b3de52010-09-11 23:32:50 +00009445 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009446 }
9447
9448 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9449 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009450 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009451 }
9452
9453 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9454 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9455 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009456
9457 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9458 Visit(E->getExpr());
9459 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009460 };
9461}
9462
9463/// \brief Mark any declarations that appear within this expression or any
9464/// potentially-evaluated subexpressions as "referenced".
9465void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9466 EvaluatedExprMarker(*this).Visit(E);
9467}
9468
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009469/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9470/// of the program being compiled.
9471///
9472/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009473/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009474/// possibility that the code will actually be executable. Code in sizeof()
9475/// expressions, code used only during overload resolution, etc., are not
9476/// potentially evaluated. This routine will suppress such diagnostics or,
9477/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009478/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009479/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009480///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009481/// This routine should be used for all diagnostics that describe the run-time
9482/// behavior of a program, such as passing a non-POD value through an ellipsis.
9483/// Failure to do so will likely result in spurious diagnostics or failures
9484/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009485bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009486 const PartialDiagnostic &PD) {
9487 switch (ExprEvalContexts.back().Context ) {
9488 case Unevaluated:
9489 // The argument will never be evaluated, so don't complain.
9490 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009491
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009492 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009493 case PotentiallyEvaluatedIfUsed:
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009494 Diag(Loc, PD);
9495 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009496
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009497 case PotentiallyPotentiallyEvaluated:
9498 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9499 break;
9500 }
9501
9502 return false;
9503}
9504
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009505bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9506 CallExpr *CE, FunctionDecl *FD) {
9507 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9508 return false;
9509
9510 PartialDiagnostic Note =
9511 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9512 << FD->getDeclName() : PDiag();
9513 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009514
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009515 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009516 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009517 PDiag(diag::err_call_function_incomplete_return)
9518 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009519 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009520 << CE->getSourceRange(),
9521 std::make_pair(NoteLoc, Note)))
9522 return true;
9523
9524 return false;
9525}
9526
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009527// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009528// will prevent this condition from triggering, which is what we want.
9529void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9530 SourceLocation Loc;
9531
John McCall0506e4a2009-11-11 02:41:58 +00009532 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009533 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009534
John McCalld5707ab2009-10-12 21:59:07 +00009535 if (isa<BinaryOperator>(E)) {
9536 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009537 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009538 return;
9539
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009540 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9541
John McCallb0e419e2009-11-12 00:06:05 +00009542 // Greylist some idioms by putting them into a warning subcategory.
9543 if (ObjCMessageExpr *ME
9544 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9545 Selector Sel = ME->getSelector();
9546
John McCallb0e419e2009-11-12 00:06:05 +00009547 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009548 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009549 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9550
9551 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009552 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009553 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9554 }
John McCall0506e4a2009-11-11 02:41:58 +00009555
John McCalld5707ab2009-10-12 21:59:07 +00009556 Loc = Op->getOperatorLoc();
9557 } else if (isa<CXXOperatorCallExpr>(E)) {
9558 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009559 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009560 return;
9561
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009562 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009563 Loc = Op->getOperatorLoc();
9564 } else {
9565 // Not an assignment.
9566 return;
9567 }
9568
John McCalld5707ab2009-10-12 21:59:07 +00009569 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00009570 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009571
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009572 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009573
9574 if (IsOrAssign)
9575 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9576 << FixItHint::CreateReplacement(Loc, "!=");
9577 else
9578 Diag(Loc, diag::note_condition_assign_to_comparison)
9579 << FixItHint::CreateReplacement(Loc, "==");
9580
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009581 Diag(Loc, diag::note_condition_assign_silence)
9582 << FixItHint::CreateInsertion(Open, "(")
9583 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +00009584}
9585
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009586/// \brief Redundant parentheses over an equality comparison can indicate
9587/// that the user intended an assignment used as condition.
9588void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009589 // Don't warn if the parens came from a macro.
9590 SourceLocation parenLoc = parenE->getLocStart();
9591 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9592 return;
9593
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009594 Expr *E = parenE->IgnoreParens();
9595
9596 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009597 if (opE->getOpcode() == BO_EQ &&
9598 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9599 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009600 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009601
Ted Kremenekae022092011-02-02 02:20:30 +00009602 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9603 Diag(Loc, diag::note_equality_comparison_to_assign)
9604 << FixItHint::CreateReplacement(Loc, "=");
9605 Diag(Loc, diag::note_equality_comparison_silence)
9606 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9607 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009608 }
9609}
9610
John McCalld5707ab2009-10-12 21:59:07 +00009611bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9612 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009613 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9614 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009615
9616 if (!E->isTypeDependent()) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009617 if (E->isBoundMemberFunction(Context))
9618 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9619 << E->getSourceRange();
9620
John McCall34376a62010-12-04 03:47:34 +00009621 if (getLangOptions().CPlusPlus)
9622 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9623
9624 DefaultFunctionArrayLvalueConversion(E);
John McCall29cb2fd2010-12-04 06:09:13 +00009625
9626 QualType T = E->getType();
John McCall34376a62010-12-04 03:47:34 +00009627 if (!T->isScalarType()) // C99 6.8.4.1p1
9628 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9629 << T << E->getSourceRange();
John McCalld5707ab2009-10-12 21:59:07 +00009630 }
9631
9632 return false;
9633}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009634
John McCalldadc5752010-08-24 06:29:42 +00009635ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9636 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009637 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009638 return ExprError();
9639
Douglas Gregorb412e172010-07-25 18:17:45 +00009640 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00009641 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00009642
9643 return Owned(Sub);
9644}
John McCall36e7fe32010-10-12 00:20:44 +00009645
9646/// Check for operands with placeholder types and complain if found.
9647/// Returns true if there was an error and no recovery was possible.
9648ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9649 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9650 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9651
9652 // If this is overload, check for a single overload.
9653 if (BT->getKind() == BuiltinType::Overload) {
9654 if (FunctionDecl *Specialization
9655 = ResolveSingleFunctionTemplateSpecialization(E)) {
9656 // The access doesn't really matter in this case.
9657 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9658 Specialization->getAccess());
9659 E = FixOverloadedFunctionReference(E, Found, Specialization);
9660 if (!E) return ExprError();
9661 return Owned(E);
9662 }
9663
John McCall36226622010-10-12 02:09:17 +00009664 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
John McCall36e7fe32010-10-12 00:20:44 +00009665 return ExprError();
9666 }
9667
9668 // Otherwise it's a use of undeduced auto.
9669 assert(BT->getKind() == BuiltinType::UndeducedAuto);
9670
9671 DeclRefExpr *DRE = cast<DeclRefExpr>(E->IgnoreParens());
9672 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
9673 << DRE->getDecl() << E->getSourceRange();
9674 return ExprError();
9675}