blob: c084bb0a80d21a57fa57549ded45355c36a4a917 [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
297 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
298 E, 0, VK_RValue);
299}
300
301void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
302 DefaultFunctionArrayConversion(E);
303 DefaultLvalueConversion(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000304}
305
306
Chris Lattner513165e2008-07-25 21:10:04 +0000307/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000308/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000309/// sometimes surpressed. For example, the array->pointer conversion doesn't
310/// apply if the array is an argument to the sizeof or address (&) operators.
311/// In these instances, this routine should *not* be called.
John McCallf3735e02010-12-01 04:43:34 +0000312Expr *Sema::UsualUnaryConversions(Expr *&E) {
313 // First, convert to an r-value.
314 DefaultFunctionArrayLvalueConversion(E);
315
316 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000317 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000318
319 // Try to perform integral promotions if the object has a theoretically
320 // promotable type.
321 if (Ty->isIntegralOrUnscopedEnumerationType()) {
322 // C99 6.3.1.1p2:
323 //
324 // The following may be used in an expression wherever an int or
325 // unsigned int may be used:
326 // - an object or expression with an integer type whose integer
327 // conversion rank is less than or equal to the rank of int
328 // and unsigned int.
329 // - A bit-field of type _Bool, int, signed int, or unsigned int.
330 //
331 // If an int can represent all values of the original type, the
332 // value is converted to an int; otherwise, it is converted to an
333 // unsigned int. These are called the integer promotions. All
334 // other types are unchanged by the integer promotions.
335
336 QualType PTy = Context.isPromotableBitField(E);
337 if (!PTy.isNull()) {
338 ImpCastExprToType(E, PTy, CK_IntegralCast);
339 return E;
340 }
341 if (Ty->isPromotableIntegerType()) {
342 QualType PT = Context.getPromotedIntegerType(Ty);
343 ImpCastExprToType(E, PT, CK_IntegralCast);
344 return E;
345 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000346 }
347
John McCallf3735e02010-12-01 04:43:34 +0000348 return E;
Chris Lattner513165e2008-07-25 21:10:04 +0000349}
350
Chris Lattner2ce500f2008-07-25 22:25:12 +0000351/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000352/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000353/// double. All other argument types are converted by UsualUnaryConversions().
354void Sema::DefaultArgumentPromotion(Expr *&Expr) {
355 QualType Ty = Expr->getType();
356 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000357
John McCall9bc26772010-12-06 18:36:11 +0000358 UsualUnaryConversions(Expr);
359
Chris Lattner2ce500f2008-07-25 22:25:12 +0000360 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000361 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John McCall9bc26772010-12-06 18:36:11 +0000362 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000363}
364
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000365/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
366/// will warn if the resulting type is not a POD type, and rejects ObjC
367/// interfaces passed by value. This returns true if the argument type is
368/// completely illegal.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000369bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
370 FunctionDecl *FDecl) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000371 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000372
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000373 // __builtin_va_start takes the second argument as a "varargs" argument, but
374 // it doesn't actually do anything with it. It doesn't need to be non-pod
375 // etc.
376 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
377 return false;
378
John McCall8b07ec22010-05-15 11:32:37 +0000379 if (Expr->getType()->isObjCObjectType() &&
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000380 DiagRuntimeBehavior(Expr->getLocStart(),
381 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
382 << Expr->getType() << CT))
383 return true;
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000384
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000385 if (!Expr->getType()->isPODType() &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000386 DiagRuntimeBehavior(Expr->getLocStart(),
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000387 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
388 << Expr->getType() << CT))
389 return true;
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000390
391 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000392}
393
Chris Lattner513165e2008-07-25 21:10:04 +0000394/// UsualArithmeticConversions - Performs various conversions that are common to
395/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000396/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000397/// responsible for emitting appropriate error diagnostics.
398/// FIXME: verify the conversion rules for "complex int" are consistent with
399/// GCC.
400QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
401 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000402 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000403 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000404
405 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000406
Mike Stump11289f42009-09-09 15:08:12 +0000407 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000408 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000409 QualType lhs =
410 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000411 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000412 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000413
414 // If both types are identical, no conversion is needed.
415 if (lhs == rhs)
416 return lhs;
417
418 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
419 // The caller can deal with this (e.g. pointer + int).
420 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
421 return lhs;
422
John McCalld005ac92010-11-13 08:17:45 +0000423 // Apply unary and bitfield promotions to the LHS's type.
424 QualType lhs_unpromoted = lhs;
425 if (lhs->isPromotableIntegerType())
426 lhs = Context.getPromotedIntegerType(lhs);
Eli Friedman629ffb92009-08-20 04:21:42 +0000427 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000428 if (!LHSBitfieldPromoteTy.isNull())
429 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000430 if (lhs != lhs_unpromoted && !isCompAssign)
431 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000432
John McCalld005ac92010-11-13 08:17:45 +0000433 // If both types are identical, no conversion is needed.
434 if (lhs == rhs)
435 return lhs;
436
437 // At this point, we have two different arithmetic types.
438
439 // Handle complex types first (C99 6.3.1.8p1).
440 bool LHSComplexFloat = lhs->isComplexType();
441 bool RHSComplexFloat = rhs->isComplexType();
442 if (LHSComplexFloat || RHSComplexFloat) {
443 // if we have an integer operand, the result is the complex type.
444
John McCallc5e62b42010-11-13 09:02:35 +0000445 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
446 if (rhs->isIntegerType()) {
447 QualType fp = cast<ComplexType>(lhs)->getElementType();
448 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
449 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
450 } else {
451 assert(rhs->isComplexIntegerType());
John McCalld7646252010-11-14 08:17:51 +0000452 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000453 }
John McCalld005ac92010-11-13 08:17:45 +0000454 return lhs;
455 }
456
John McCallc5e62b42010-11-13 09:02:35 +0000457 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
458 if (!isCompAssign) {
459 // int -> float -> _Complex float
460 if (lhs->isIntegerType()) {
461 QualType fp = cast<ComplexType>(rhs)->getElementType();
462 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
463 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
464 } else {
465 assert(lhs->isComplexIntegerType());
John McCalld7646252010-11-14 08:17:51 +0000466 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000467 }
468 }
John McCalld005ac92010-11-13 08:17:45 +0000469 return rhs;
470 }
471
472 // This handles complex/complex, complex/float, or float/complex.
473 // When both operands are complex, the shorter operand is converted to the
474 // type of the longer, and that is the type of the result. This corresponds
475 // to what is done when combining two real floating-point operands.
476 // The fun begins when size promotion occur across type domains.
477 // From H&S 6.3.4: When one operand is complex and the other is a real
478 // floating-point type, the less precise type is converted, within it's
479 // real or complex domain, to the precision of the other type. For example,
480 // when combining a "long double" with a "double _Complex", the
481 // "double _Complex" is promoted to "long double _Complex".
482 int order = Context.getFloatingTypeOrder(lhs, rhs);
483
484 // If both are complex, just cast to the more precise type.
485 if (LHSComplexFloat && RHSComplexFloat) {
486 if (order > 0) {
487 // _Complex float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000488 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000489 return lhs;
490
491 } else if (order < 0) {
492 // _Complex float -> _Complex double
493 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000494 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000495 return rhs;
496 }
497 return lhs;
498 }
499
500 // If just the LHS is complex, the RHS needs to be converted,
501 // and the LHS might need to be promoted.
502 if (LHSComplexFloat) {
503 if (order > 0) { // LHS is wider
504 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000505 QualType fp = cast<ComplexType>(lhs)->getElementType();
506 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
507 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000508 return lhs;
509 }
510
511 // RHS is at least as wide. Find its corresponding complex type.
512 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
513
514 // double -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000515 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000516
517 // _Complex float -> _Complex double
518 if (!isCompAssign && order < 0)
John McCallc5e62b42010-11-13 09:02:35 +0000519 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000520
521 return result;
522 }
523
524 // Just the RHS is complex, so the LHS needs to be converted
525 // and the RHS might need to be promoted.
526 assert(RHSComplexFloat);
527
528 if (order < 0) { // RHS is wider
529 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000530 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000531 QualType fp = cast<ComplexType>(rhs)->getElementType();
532 ImpCastExprToType(lhsExpr, fp, CK_FloatingCast);
John McCallc5e62b42010-11-13 09:02:35 +0000533 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
534 }
John McCalld005ac92010-11-13 08:17:45 +0000535 return rhs;
536 }
537
538 // LHS is at least as wide. Find its corresponding complex type.
539 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
540
541 // double -> _Complex double
542 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000543 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000544
545 // _Complex float -> _Complex double
546 if (order > 0)
John McCallc5e62b42010-11-13 09:02:35 +0000547 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000548
549 return result;
550 }
551
552 // Now handle "real" floating types (i.e. float, double, long double).
553 bool LHSFloat = lhs->isRealFloatingType();
554 bool RHSFloat = rhs->isRealFloatingType();
555 if (LHSFloat || RHSFloat) {
556 // If we have two real floating types, convert the smaller operand
557 // to the bigger result.
558 if (LHSFloat && RHSFloat) {
559 int order = Context.getFloatingTypeOrder(lhs, rhs);
560 if (order > 0) {
561 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
562 return lhs;
563 }
564
565 assert(order < 0 && "illegal float comparison");
566 if (!isCompAssign)
567 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
568 return rhs;
569 }
570
571 // If we have an integer operand, the result is the real floating type.
572 if (LHSFloat) {
573 if (rhs->isIntegerType()) {
574 // Convert rhs to the lhs floating point type.
575 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
576 return lhs;
577 }
578
579 // Convert both sides to the appropriate complex float.
580 assert(rhs->isComplexIntegerType());
581 QualType result = Context.getComplexType(lhs);
582
583 // _Complex int -> _Complex float
John McCalld7646252010-11-14 08:17:51 +0000584 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000585
586 // float -> _Complex float
587 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000588 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000589
590 return result;
591 }
592
593 assert(RHSFloat);
594 if (lhs->isIntegerType()) {
595 // Convert lhs to the rhs floating point type.
596 if (!isCompAssign)
597 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
598 return rhs;
599 }
600
601 // Convert both sides to the appropriate complex float.
602 assert(lhs->isComplexIntegerType());
603 QualType result = Context.getComplexType(rhs);
604
605 // _Complex int -> _Complex float
606 if (!isCompAssign)
John McCalld7646252010-11-14 08:17:51 +0000607 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000608
609 // float -> _Complex float
John McCallc5e62b42010-11-13 09:02:35 +0000610 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000611
612 return result;
613 }
614
615 // Handle GCC complex int extension.
616 // FIXME: if the operands are (int, _Complex long), we currently
617 // don't promote the complex. Also, signedness?
618 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
619 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
620 if (lhsComplexInt && rhsComplexInt) {
621 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
622 rhsComplexInt->getElementType());
623 assert(order && "inequal types with equal element ordering");
624 if (order > 0) {
625 // _Complex int -> _Complex long
John McCallc5e62b42010-11-13 09:02:35 +0000626 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000627 return lhs;
628 }
629
630 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000631 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000632 return rhs;
633 } else if (lhsComplexInt) {
634 // int -> _Complex int
John McCallc5e62b42010-11-13 09:02:35 +0000635 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000636 return lhs;
637 } else if (rhsComplexInt) {
638 // int -> _Complex int
639 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000640 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000641 return rhs;
642 }
643
644 // Finally, we have two differing integer types.
645 // The rules for this case are in C99 6.3.1.8
646 int compare = Context.getIntegerTypeOrder(lhs, rhs);
647 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
648 rhsSigned = rhs->hasSignedIntegerRepresentation();
649 if (lhsSigned == rhsSigned) {
650 // Same signedness; use the higher-ranked type
651 if (compare >= 0) {
652 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
653 return lhs;
654 } else if (!isCompAssign)
655 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
656 return rhs;
657 } else if (compare != (lhsSigned ? 1 : -1)) {
658 // The unsigned type has greater than or equal rank to the
659 // signed type, so use the unsigned type
660 if (rhsSigned) {
661 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
662 return lhs;
663 } else if (!isCompAssign)
664 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
665 return rhs;
666 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
667 // The two types are different widths; if we are here, that
668 // means the signed type is larger than the unsigned type, so
669 // use the signed type.
670 if (lhsSigned) {
671 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
672 return lhs;
673 } else if (!isCompAssign)
674 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
675 return rhs;
676 } else {
677 // The signed type is higher-ranked than the unsigned type,
678 // but isn't actually any bigger (like unsigned int and long
679 // on most 32-bit systems). Use the unsigned type corresponding
680 // to the signed type.
681 QualType result =
682 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
683 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
684 if (!isCompAssign)
685 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
686 return result;
687 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000688}
689
Chris Lattner513165e2008-07-25 21:10:04 +0000690//===----------------------------------------------------------------------===//
691// Semantic Analysis for various Expression Types
692//===----------------------------------------------------------------------===//
693
694
Steve Naroff83895f72007-09-16 03:34:24 +0000695/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000696/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
697/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
698/// multiple tokens. However, the common case is that StringToks points to one
699/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000700///
John McCalldadc5752010-08-24 06:29:42 +0000701ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000702Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000703 assert(NumStringToks && "Must have at least one string!");
704
Chris Lattner8a24e582009-01-16 18:51:42 +0000705 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000706 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000707 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000708
Chris Lattner23b7eb62007-06-15 23:05:46 +0000709 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000710 for (unsigned i = 0; i != NumStringToks; ++i)
711 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000712
Chris Lattner36fc8792008-02-11 00:02:17 +0000713 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000714 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000715 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000716
717 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000718 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000719 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000720
Chris Lattner36fc8792008-02-11 00:02:17 +0000721 // Get an array type for the string, according to C99 6.4.5. This includes
722 // the nul terminator character as well as the string length for pascal
723 // strings.
724 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000725 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000726 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000727
Chris Lattner5b183d82006-11-10 05:03:26 +0000728 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000729 return Owned(StringLiteral::Create(Context, Literal.GetString(),
730 Literal.GetStringLength(),
731 Literal.AnyWide, StrTy,
732 &StringTokLocs[0],
733 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000734}
735
Chris Lattner2a9d9892008-10-20 05:16:36 +0000736/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
737/// CurBlock to VD should cause it to be snapshotted (as we do for auto
738/// variables defined outside the block) or false if this is not needed (e.g.
739/// for values inside the block or for globals).
740///
Douglas Gregor4f13beb2010-03-01 20:44:28 +0000741/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
Chris Lattner497d7b02009-04-21 22:26:47 +0000742/// up-to-date.
743///
Douglas Gregor9a28e842010-03-01 23:15:13 +0000744static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
Chris Lattner2a9d9892008-10-20 05:16:36 +0000745 ValueDecl *VD) {
746 // If the value is defined inside the block, we couldn't snapshot it even if
747 // we wanted to.
748 if (CurBlock->TheDecl == VD->getDeclContext())
749 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000750
Chris Lattner2a9d9892008-10-20 05:16:36 +0000751 // If this is an enum constant or function, it is constant, don't snapshot.
752 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
753 return false;
754
755 // If this is a reference to an extern, static, or global variable, no need to
756 // snapshot it.
757 // FIXME: What about 'const' variables in C++?
758 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000759 if (!Var->hasLocalStorage())
760 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000761
Chris Lattner497d7b02009-04-21 22:26:47 +0000762 // Blocks that have these can't be constant.
763 CurBlock->hasBlockDeclRefExprs = true;
764
765 // If we have nested blocks, the decl may be declared in an outer block (in
766 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
767 // be defined outside all of the current blocks (in which case the blocks do
768 // all get the bit). Walk the nesting chain.
Douglas Gregor9a28e842010-03-01 23:15:13 +0000769 for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
770 BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000771
Douglas Gregor9a28e842010-03-01 23:15:13 +0000772 if (!NextBlock)
773 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000774
Chris Lattner497d7b02009-04-21 22:26:47 +0000775 // If we found the defining block for the variable, don't mark the block as
776 // having a reference outside it.
777 if (NextBlock->TheDecl == VD->getDeclContext())
778 break;
Mike Stump11289f42009-09-09 15:08:12 +0000779
Chris Lattner497d7b02009-04-21 22:26:47 +0000780 // Otherwise, the DeclRef from the inner block causes the outer one to need
781 // a snapshot as well.
782 NextBlock->hasBlockDeclRefExprs = true;
783 }
Mike Stump11289f42009-09-09 15:08:12 +0000784
Chris Lattner2a9d9892008-10-20 05:16:36 +0000785 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000786}
787
Chris Lattner2a9d9892008-10-20 05:16:36 +0000788
John McCalldadc5752010-08-24 06:29:42 +0000789ExprResult
John McCall7decc9e2010-11-18 06:31:45 +0000790Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
791 SourceLocation Loc, const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000792 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +0000793 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000794}
795
796/// BuildDeclRefExpr - Build a DeclRefExpr.
John McCalldadc5752010-08-24 06:29:42 +0000797ExprResult
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000798Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +0000799 ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000800 const DeclarationNameInfo &NameInfo,
801 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000802 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000803 Diag(NameInfo.getLoc(),
Mike Stump11289f42009-09-09 15:08:12 +0000804 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000805 << D->getDeclName();
806 return ExprError();
807 }
Mike Stump11289f42009-09-09 15:08:12 +0000808
Anders Carlsson946b86d2009-06-24 00:10:43 +0000809 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Douglas Gregor15243332010-04-27 21:10:04 +0000810 if (isa<NonTypeTemplateParmDecl>(VD)) {
811 // Non-type template parameters can be referenced anywhere they are
812 // visible.
Douglas Gregora8a089b2010-07-13 18:40:04 +0000813 Ty = Ty.getNonLValueExprType(Context);
Douglas Gregor15243332010-04-27 21:10:04 +0000814 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
Anders Carlsson946b86d2009-06-24 00:10:43 +0000815 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
816 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000817 Diag(NameInfo.getLoc(),
818 diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000819 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000820 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000821 << D->getIdentifier();
822 return ExprError();
823 }
824 }
John McCall4bc41ae2010-11-18 19:01:18 +0000825
826 // This ridiculousness brought to you by 'extern void x;' and the
827 // GNU compiler collection.
828 } else if (!getLangOptions().CPlusPlus && !Ty.hasQualifiers() &&
829 Ty->isVoidType()) {
830 VK = VK_RValue;
Anders Carlsson946b86d2009-06-24 00:10:43 +0000831 }
832 }
Mike Stump11289f42009-09-09 15:08:12 +0000833
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000834 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +0000835
John McCall086a4642010-11-24 05:12:34 +0000836 Expr *E = DeclRefExpr::Create(Context,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000837 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
John McCall086a4642010-11-24 05:12:34 +0000838 SS? SS->getRange() : SourceRange(),
839 D, NameInfo, Ty, VK);
840
841 // Just in case we're building an illegal pointer-to-member.
842 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
843 E->setObjectKind(OK_BitField);
844
845 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000846}
847
John McCallfeb624a2010-11-23 20:48:44 +0000848static ExprResult
849BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
850 const CXXScopeSpec &SS, FieldDecl *Field,
851 DeclAccessPair FoundDecl,
852 const DeclarationNameInfo &MemberNameInfo);
853
John McCalldadc5752010-08-24 06:29:42 +0000854ExprResult
Douglas Gregord5846a12009-04-15 06:41:24 +0000855Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +0000856 const CXXScopeSpec &SS,
Francois Pichet783dd6e2010-11-21 06:08:52 +0000857 IndirectFieldDecl *IndirectField,
Douglas Gregord5846a12009-04-15 06:41:24 +0000858 Expr *BaseObjectExpr,
859 SourceLocation OpLoc) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000860 // Build the expression that refers to the base object, from
861 // which we will build a sequence of member references to each
862 // of the anonymous union objects and, eventually, the field we
863 // found via name lookup.
864 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000865 Qualifiers BaseQuals;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000866 VarDecl *BaseObject = IndirectField->getVarDecl();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000867 if (BaseObject) {
868 // BaseObject is an anonymous struct/union variable (and is,
869 // therefore, not part of another non-anonymous record).
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000870 MarkDeclarationReferenced(Loc, BaseObject);
John McCall7decc9e2010-11-18 06:31:45 +0000871 BaseObjectExpr =
872 new (Context) DeclRefExpr(BaseObject, BaseObject->getType(),
873 VK_LValue, Loc);
John McCall8ccfcb52009-09-24 19:53:00 +0000874 BaseQuals
875 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000876 } else if (BaseObjectExpr) {
877 // The caller provided the base object expression. Determine
878 // whether its a pointer and whether it adds any qualifiers to the
879 // anonymous struct/union fields we're looking into.
880 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000881 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000882 BaseObjectIsPointer = true;
883 ObjectType = ObjectPtr->getPointeeType();
884 }
John McCall8ccfcb52009-09-24 19:53:00 +0000885 BaseQuals
886 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000887 } else {
888 // We've found a member of an anonymous struct/union that is
889 // inside a non-anonymous struct/union, so in a well-formed
890 // program our base object expression is "this".
John McCall87fe5d52010-05-20 01:18:31 +0000891 DeclContext *DC = getFunctionLevelDeclContext();
892 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000893 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000894 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000895 = Context.getTagDeclType(
Francois Pichet783dd6e2010-11-21 06:08:52 +0000896 cast<RecordDecl>(
897 (*IndirectField->chain_begin())->getDeclContext()));
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000898 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000899 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000900 == Context.getCanonicalType(ThisType)) ||
901 IsDerivedFrom(ThisType, AnonFieldType)) {
902 // Our base object expression is "this".
Douglas Gregor4b654412009-12-24 20:23:34 +0000903 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000904 MD->getThisType(Context),
905 /*isImplicit=*/true);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000906 BaseObjectIsPointer = true;
907 }
908 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000909 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
Francois Pichet783dd6e2010-11-21 06:08:52 +0000910 << IndirectField->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000911 }
John McCall8ccfcb52009-09-24 19:53:00 +0000912 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000913 }
914
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +0000915 if (!BaseObjectExpr) {
916 // The field is referenced for a pointer-to-member expression, e.g:
917 //
918 // struct S {
919 // union {
920 // char c;
921 // };
922 // };
923 // char S::*foo = &S::c;
924 //
925 FieldDecl *field = IndirectField->getAnonField();
926 DeclarationNameInfo NameInfo(field->getDeclName(), Loc);
927 return BuildDeclRefExpr(field, field->getType().getNonReferenceType(),
928 VK_LValue, NameInfo, &SS);
929 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000930 }
931
932 // Build the implicit member references to the field of the
933 // anonymous struct/union.
934 Expr *Result = BaseObjectExpr;
John McCallfeb624a2010-11-23 20:48:44 +0000935
Francois Pichet783dd6e2010-11-21 06:08:52 +0000936 IndirectFieldDecl::chain_iterator FI = IndirectField->chain_begin(),
937 FEnd = IndirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +0000938
Francois Pichet783dd6e2010-11-21 06:08:52 +0000939 // Skip the first VarDecl if present.
940 if (BaseObject)
941 FI++;
942 for (; FI != FEnd; FI++) {
943 FieldDecl *Field = cast<FieldDecl>(*FI);
John McCall8ccfcb52009-09-24 19:53:00 +0000944
John McCallfeb624a2010-11-23 20:48:44 +0000945 // FIXME: these are somewhat meaningless
946 DeclarationNameInfo MemberNameInfo(Field->getDeclName(), Loc);
947 DeclAccessPair FoundDecl = DeclAccessPair::make(Field, Field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +0000948
John McCallfeb624a2010-11-23 20:48:44 +0000949 Result = BuildFieldReferenceExpr(*this, Result, BaseObjectIsPointer,
950 SS, Field, FoundDecl, MemberNameInfo)
951 .take();
John McCall8ccfcb52009-09-24 19:53:00 +0000952
John McCallfeb624a2010-11-23 20:48:44 +0000953 // All the implicit accesses are dot-accesses.
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000954 BaseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000955 }
956
Sebastian Redlffbcf962009-01-18 18:53:16 +0000957 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000958}
959
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000960/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +0000961/// possibly a list of template arguments.
962///
963/// If this produces template arguments, it is permitted to call
964/// DecomposeTemplateName.
965///
966/// This actually loses a lot of source location information for
967/// non-standard name kinds; we should consider preserving that in
968/// some way.
969static void DecomposeUnqualifiedId(Sema &SemaRef,
970 const UnqualifiedId &Id,
971 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000972 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +0000973 const TemplateArgumentListInfo *&TemplateArgs) {
974 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
975 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
976 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
977
978 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
979 Id.TemplateId->getTemplateArgs(),
980 Id.TemplateId->NumArgs);
981 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
982 TemplateArgsPtr.release();
983
John McCall3e56fd42010-08-23 07:28:44 +0000984 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000985 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
986 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +0000987 TemplateArgs = &Buffer;
988 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000989 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +0000990 TemplateArgs = 0;
991 }
992}
993
John McCall69f9dbc2010-02-08 19:26:07 +0000994/// Determines whether the given record is "fully-formed" at the given
995/// location, i.e. whether a qualified lookup into it is assured of
996/// getting consistent results already.
John McCall10eae182009-11-30 22:42:35 +0000997static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
John McCall69f9dbc2010-02-08 19:26:07 +0000998 if (!Record->hasDefinition())
999 return false;
1000
John McCall10eae182009-11-30 22:42:35 +00001001 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1002 E = Record->bases_end(); I != E; ++I) {
1003 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1004 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1005 if (!BaseRT) return false;
1006
1007 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall69f9dbc2010-02-08 19:26:07 +00001008 if (!BaseRecord->hasDefinition() ||
John McCall10eae182009-11-30 22:42:35 +00001009 !IsFullyFormedScope(SemaRef, BaseRecord))
1010 return false;
1011 }
1012
1013 return true;
1014}
1015
John McCall2d74de92009-12-01 22:10:20 +00001016/// Determines if the given class is provably not derived from all of
1017/// the prospective base classes.
1018static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1019 CXXRecordDecl *Record,
1020 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001021 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001022 return false;
1023
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001024 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001025 if (!RD) return false;
1026 Record = cast<CXXRecordDecl>(RD);
1027
John McCall2d74de92009-12-01 22:10:20 +00001028 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1029 E = Record->bases_end(); I != E; ++I) {
1030 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1031 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1032 if (!BaseRT) return false;
1033
1034 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001035 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1036 return false;
1037 }
1038
1039 return true;
1040}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001041
John McCall2d74de92009-12-01 22:10:20 +00001042enum IMAKind {
1043 /// The reference is definitely not an instance member access.
1044 IMA_Static,
1045
1046 /// The reference may be an implicit instance member access.
1047 IMA_Mixed,
1048
1049 /// The reference may be to an instance member, but it is invalid if
1050 /// so, because the context is not an instance method.
1051 IMA_Mixed_StaticContext,
1052
1053 /// The reference may be to an instance member, but it is invalid if
1054 /// so, because the context is from an unrelated class.
1055 IMA_Mixed_Unrelated,
1056
1057 /// The reference is definitely an implicit instance member access.
1058 IMA_Instance,
1059
1060 /// The reference may be to an unresolved using declaration.
1061 IMA_Unresolved,
1062
1063 /// The reference may be to an unresolved using declaration and the
1064 /// context is not an instance method.
1065 IMA_Unresolved_StaticContext,
1066
John McCall2d74de92009-12-01 22:10:20 +00001067 /// All possible referrents are instance members and the current
1068 /// context is not an instance method.
1069 IMA_Error_StaticContext,
1070
1071 /// All possible referrents are instance members of an unrelated
1072 /// class.
1073 IMA_Error_Unrelated
1074};
1075
1076/// The given lookup names class member(s) and is not being used for
1077/// an address-of-member expression. Classify the type of access
1078/// according to whether it's possible that this reference names an
1079/// instance member. This is best-effort; it is okay to
1080/// conservatively answer "yes", in which case some errors will simply
1081/// not be caught until template-instantiation.
1082static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1083 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001084 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001085
John McCall87fe5d52010-05-20 01:18:31 +00001086 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001087 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001088 (!isa<CXXMethodDecl>(DC) ||
1089 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001090
1091 if (R.isUnresolvableResult())
1092 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1093
1094 // Collect all the declaring classes of instance members we find.
1095 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001096 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001097 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1098 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001099 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001100
John McCalla8ae2222010-04-06 21:38:20 +00001101 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001102 if (dyn_cast<FieldDecl>(D))
1103 hasField = true;
1104
John McCall2d74de92009-12-01 22:10:20 +00001105 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001106 Classes.insert(R->getCanonicalDecl());
1107 }
1108 else
1109 hasNonInstance = true;
1110 }
1111
1112 // If we didn't find any instance members, it can't be an implicit
1113 // member reference.
1114 if (Classes.empty())
1115 return IMA_Static;
1116
1117 // If the current context is not an instance method, it can't be
1118 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001119 if (isStaticContext) {
1120 if (hasNonInstance)
1121 return IMA_Mixed_StaticContext;
1122
1123 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1124 // C++0x [expr.prim.general]p10:
1125 // An id-expression that denotes a non-static data member or non-static
1126 // member function of a class can only be used:
1127 // (...)
1128 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1129 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1130 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1131 if (isUnevaluatedExpression)
1132 return IMA_Mixed_StaticContext;
1133 }
1134
1135 return IMA_Error_StaticContext;
1136 }
John McCall2d74de92009-12-01 22:10:20 +00001137
1138 // If we can prove that the current context is unrelated to all the
1139 // declaring classes, it can't be an implicit member reference (in
1140 // which case it's an error if any of those members are selected).
1141 if (IsProvablyNotDerivedFrom(SemaRef,
John McCall87fe5d52010-05-20 01:18:31 +00001142 cast<CXXMethodDecl>(DC)->getParent(),
John McCall2d74de92009-12-01 22:10:20 +00001143 Classes))
1144 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1145
1146 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1147}
1148
1149/// Diagnose a reference to a field with no object available.
1150static void DiagnoseInstanceReference(Sema &SemaRef,
1151 const CXXScopeSpec &SS,
1152 const LookupResult &R) {
1153 SourceLocation Loc = R.getNameLoc();
1154 SourceRange Range(Loc);
1155 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1156
Argyrios Kyrtzidisb85cd7c2011-01-31 07:04:33 +00001157 if (R.getAsSingle<FieldDecl>() || R.getAsSingle<IndirectFieldDecl>()) {
John McCall2d74de92009-12-01 22:10:20 +00001158 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1159 if (MD->isStatic()) {
1160 // "invalid use of member 'x' in static member function"
1161 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
1162 << Range << R.getLookupName();
1163 return;
1164 }
1165 }
1166
1167 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
1168 << R.getLookupName() << Range;
1169 return;
1170 }
1171
1172 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001173}
1174
John McCalld681c392009-12-16 08:11:27 +00001175/// Diagnose an empty lookup.
1176///
1177/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001178bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1179 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001180 DeclarationName Name = R.getLookupName();
1181
John McCalld681c392009-12-16 08:11:27 +00001182 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001183 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001184 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1185 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001186 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001187 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001188 diagnostic_suggest = diag::err_undeclared_use_suggest;
1189 }
John McCalld681c392009-12-16 08:11:27 +00001190
Douglas Gregor598b08f2009-12-31 05:20:13 +00001191 // If the original lookup was an unqualified lookup, fake an
1192 // unqualified lookup. This is useful when (for example) the
1193 // original lookup would not have found something because it was a
1194 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001195 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001196 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001197 if (isa<CXXRecordDecl>(DC)) {
1198 LookupQualifiedName(R, DC);
1199
1200 if (!R.empty()) {
1201 // Don't give errors about ambiguities in this lookup.
1202 R.suppressDiagnostics();
1203
1204 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1205 bool isInstance = CurMethod &&
1206 CurMethod->isInstance() &&
1207 DC == CurMethod->getParent();
1208
1209 // Give a code modification hint to insert 'this->'.
1210 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1211 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001212 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001213 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1214 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001215 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001216 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001217 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001218 Diag(R.getNameLoc(), diagnostic) << Name
1219 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1220 QualType DepThisType = DepMethod->getThisType(Context);
1221 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1222 R.getNameLoc(), DepThisType, false);
1223 TemplateArgumentListInfo TList;
1224 if (ULE->hasExplicitTemplateArgs())
1225 ULE->copyTemplateArgumentsInto(TList);
1226 CXXDependentScopeMemberExpr *DepExpr =
1227 CXXDependentScopeMemberExpr::Create(
1228 Context, DepThis, DepThisType, true, SourceLocation(),
1229 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
1230 R.getLookupNameInfo(), &TList);
1231 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001232 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001233 // FIXME: we should be able to handle this case too. It is correct
1234 // to add this-> here. This is a workaround for PR7947.
1235 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001236 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001237 } else {
John McCalld681c392009-12-16 08:11:27 +00001238 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001239 }
John McCalld681c392009-12-16 08:11:27 +00001240
1241 // Do we really want to note all of these?
1242 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1243 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1244
1245 // Tell the callee to try to recover.
1246 return false;
1247 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001248
1249 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001250 }
1251 }
1252
Douglas Gregor598b08f2009-12-31 05:20:13 +00001253 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001254 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001255 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001256 if (!R.empty()) {
1257 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1258 if (SS.isEmpty())
1259 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1260 << FixItHint::CreateReplacement(R.getNameLoc(),
1261 R.getLookupName().getAsString());
1262 else
1263 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1264 << Name << computeDeclContext(SS, false) << R.getLookupName()
1265 << SS.getRange()
1266 << FixItHint::CreateReplacement(R.getNameLoc(),
1267 R.getLookupName().getAsString());
1268 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1269 Diag(ND->getLocation(), diag::note_previous_decl)
1270 << ND->getDeclName();
1271
1272 // Tell the callee to try to recover.
1273 return false;
1274 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001275
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001276 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1277 // FIXME: If we ended up with a typo for a type name or
1278 // Objective-C class name, we're in trouble because the parser
1279 // is in the wrong place to recover. Suggest the typo
1280 // correction, but don't make it a fix-it since we're not going
1281 // to recover well anyway.
1282 if (SS.isEmpty())
1283 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1284 else
1285 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1286 << Name << computeDeclContext(SS, false) << R.getLookupName()
1287 << SS.getRange();
1288
1289 // Don't try to recover; it won't work.
1290 return true;
1291 }
1292 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001293 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001294 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001295 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001296 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001297 else
Douglas Gregor25363982010-01-01 00:15:04 +00001298 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001299 << Name << computeDeclContext(SS, false) << Corrected
1300 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001301 return true;
1302 }
Douglas Gregor25363982010-01-01 00:15:04 +00001303 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001304 }
1305
1306 // Emit a special diagnostic for failed member lookups.
1307 // FIXME: computing the declaration context might fail here (?)
1308 if (!SS.isEmpty()) {
1309 Diag(R.getNameLoc(), diag::err_no_member)
1310 << Name << computeDeclContext(SS, false)
1311 << SS.getRange();
1312 return true;
1313 }
1314
John McCalld681c392009-12-16 08:11:27 +00001315 // Give up, we can't recover.
1316 Diag(R.getNameLoc(), diagnostic) << Name;
1317 return true;
1318}
1319
Douglas Gregor05fcf842010-11-02 20:36:02 +00001320ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1321 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001322 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1323 if (!IDecl)
1324 return 0;
1325 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1326 if (!ClassImpDecl)
1327 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001328 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001329 if (!property)
1330 return 0;
1331 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001332 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1333 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001334 return 0;
1335 return property;
1336}
1337
Douglas Gregor05fcf842010-11-02 20:36:02 +00001338bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1339 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1340 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1341 if (!IDecl)
1342 return false;
1343 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1344 if (!ClassImpDecl)
1345 return false;
1346 if (ObjCPropertyImplDecl *PIDecl
1347 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1348 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1349 PIDecl->getPropertyIvarDecl())
1350 return false;
1351
1352 return true;
1353}
1354
Fariborz Jahanian18722982010-07-17 00:59:30 +00001355static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001356 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001357 IdentifierInfo *II,
1358 SourceLocation NameLoc) {
1359 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001360 bool LookForIvars;
1361 if (Lookup.empty())
1362 LookForIvars = true;
1363 else if (CurMeth->isClassMethod())
1364 LookForIvars = false;
1365 else
1366 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001367 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1368 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001369 if (!LookForIvars)
1370 return 0;
1371
Fariborz Jahanian18722982010-07-17 00:59:30 +00001372 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1373 if (!IDecl)
1374 return 0;
1375 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001376 if (!ClassImpDecl)
1377 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001378 bool DynamicImplSeen = false;
1379 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1380 if (!property)
1381 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001382 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001383 DynamicImplSeen =
1384 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001385 // property implementation has a designated ivar. No need to assume a new
1386 // one.
1387 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1388 return 0;
1389 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001390 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001391 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1392 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001393 NameLoc,
1394 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001395 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001396 (Expr *)0, true);
1397 ClassImpDecl->addDecl(Ivar);
1398 IDecl->makeDeclVisibleInContext(Ivar, false);
1399 property->setPropertyIvarDecl(Ivar);
1400 return Ivar;
1401 }
1402 return 0;
1403}
1404
John McCalldadc5752010-08-24 06:29:42 +00001405ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001406 CXXScopeSpec &SS,
1407 UnqualifiedId &Id,
1408 bool HasTrailingLParen,
1409 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001410 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1411 "cannot be direct & operand and have a trailing lparen");
1412
1413 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001414 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001415
John McCall10eae182009-11-30 22:42:35 +00001416 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001417
1418 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001419 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001420 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001421 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001422
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001423 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001424 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001425 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001426
John McCalle66edc12009-11-24 19:00:30 +00001427 // C++ [temp.dep.expr]p3:
1428 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001429 // -- an identifier that was declared with a dependent type,
1430 // (note: handled after lookup)
1431 // -- a template-id that is dependent,
1432 // (note: handled in BuildTemplateIdExpr)
1433 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001434 // -- a nested-name-specifier that contains a class-name that
1435 // names a dependent type.
1436 // Determine whether this is a member of an unknown specialization;
1437 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001438 bool DependentID = false;
1439 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1440 Name.getCXXNameType()->isDependentType()) {
1441 DependentID = true;
1442 } else if (SS.isSet()) {
1443 DeclContext *DC = computeDeclContext(SS, false);
1444 if (DC) {
1445 if (RequireCompleteDeclContext(SS, DC))
1446 return ExprError();
1447 // FIXME: We should be checking whether DC is the current instantiation.
1448 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
1449 DependentID = !IsFullyFormedScope(*this, RD);
1450 } else {
1451 DependentID = true;
1452 }
1453 }
1454
1455 if (DependentID) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001456 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001457 TemplateArgs);
1458 }
Fariborz Jahanian86151342010-07-22 23:33:21 +00001459 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001460 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001461 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001462 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001463 // Lookup the template name again to correctly establish the context in
1464 // which it was found. This is really unfortunate as we already did the
1465 // lookup to determine that it was a template name in the first place. If
1466 // this becomes a performance hit, we can work harder to preserve those
1467 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001468 bool MemberOfUnknownSpecialization;
1469 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1470 MemberOfUnknownSpecialization);
John McCalle66edc12009-11-24 19:00:30 +00001471 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001472 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001473 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001474
John McCalle66edc12009-11-24 19:00:30 +00001475 // If this reference is in an Objective-C method, then we need to do
1476 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001477 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001478 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001479 if (E.isInvalid())
1480 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001481
John McCalle66edc12009-11-24 19:00:30 +00001482 Expr *Ex = E.takeAs<Expr>();
1483 if (Ex) return Owned(Ex);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001484 // Synthesize ivars lazily
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001485 if (getLangOptions().ObjCDefaultSynthProperties &&
1486 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001487 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1488 if (const ObjCPropertyDecl *Property =
1489 canSynthesizeProvisionalIvar(II)) {
1490 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1491 Diag(Property->getLocation(), diag::note_property_declare);
1492 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001493 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1494 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001495 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001496 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001497 // for further use, this must be set to false if in class method.
1498 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001499 }
Chris Lattner59a25942008-03-31 00:36:02 +00001500 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001501
John McCalle66edc12009-11-24 19:00:30 +00001502 if (R.isAmbiguous())
1503 return ExprError();
1504
Douglas Gregor171c45a2009-02-18 21:56:37 +00001505 // Determine whether this name might be a candidate for
1506 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001507 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001508
John McCalle66edc12009-11-24 19:00:30 +00001509 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001510 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001511 // in C90, extension in C99, forbidden in C++).
1512 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1513 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1514 if (D) R.addDecl(D);
1515 }
1516
1517 // If this name wasn't predeclared and if this is not a function
1518 // call, diagnose the problem.
1519 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001520 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001521 return ExprError();
1522
1523 assert(!R.empty() &&
1524 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001525
1526 // If we found an Objective-C instance variable, let
1527 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001528 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001529 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1530 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001531 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001532 assert(E.isInvalid() || E.get());
1533 return move(E);
1534 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001535 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001536 }
Mike Stump11289f42009-09-09 15:08:12 +00001537
John McCalle66edc12009-11-24 19:00:30 +00001538 // This is guaranteed from this point on.
1539 assert(!R.empty() || ADL);
1540
1541 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001542 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001543 !(getLangOptions().ObjCDefaultSynthProperties &&
1544 getLangOptions().ObjCNonFragileABI2) &&
Fariborz Jahanianc15dfd82010-07-29 16:53:53 +00001545 Var->isFileVarDecl()) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001546 ObjCPropertyDecl *Property = canSynthesizeProvisionalIvar(II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001547 if (Property) {
1548 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1549 Diag(Property->getLocation(), diag::note_property_declare);
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001550 Diag(Var->getLocation(), diag::note_global_declared_at);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001551 }
1552 }
John McCalle66edc12009-11-24 19:00:30 +00001553 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001554 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1555 // C99 DR 316 says that, if a function type comes from a
1556 // function definition (without a prototype), that type is only
1557 // used for checking compatibility. Therefore, when referencing
1558 // the function, we pretend that we don't have the full function
1559 // type.
John McCalle66edc12009-11-24 19:00:30 +00001560 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001561 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001562
Douglas Gregor3256d042009-06-30 15:47:41 +00001563 QualType T = Func->getType();
1564 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001565 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Eli Friedmanb41ad0f2010-05-17 02:50:18 +00001566 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(),
1567 Proto->getExtInfo());
John McCall7decc9e2010-11-18 06:31:45 +00001568 // Note that functions are r-values in C.
1569 return BuildDeclRefExpr(Func, NoProtoType, VK_RValue, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001570 }
1571 }
Mike Stump11289f42009-09-09 15:08:12 +00001572
John McCall2d74de92009-12-01 22:10:20 +00001573 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001574 // C++ [class.mfct.non-static]p3:
1575 // When an id-expression that is not part of a class member access
1576 // syntax and not used to form a pointer to member is used in the
1577 // body of a non-static member function of class X, if name lookup
1578 // resolves the name in the id-expression to a non-static non-type
1579 // member of some class C, the id-expression is transformed into a
1580 // class member access expression using (*this) as the
1581 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001582 //
1583 // But we don't actually need to do this for '&' operands if R
1584 // resolved to a function or overloaded function set, because the
1585 // expression is ill-formed if it actually works out to be a
1586 // non-static member function:
1587 //
1588 // C++ [expr.ref]p4:
1589 // Otherwise, if E1.E2 refers to a non-static member function. . .
1590 // [t]he expression can be used only as the left-hand operand of a
1591 // member function call.
1592 //
1593 // There are other safeguards against such uses, but it's important
1594 // to get this right here so that we don't end up making a
1595 // spuriously dependent expression if we're inside a dependent
1596 // instance method.
John McCall57500772009-12-16 12:17:52 +00001597 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001598 bool MightBeImplicitMember;
1599 if (!isAddressOfOperand)
1600 MightBeImplicitMember = true;
1601 else if (!SS.isEmpty())
1602 MightBeImplicitMember = false;
1603 else if (R.isOverloadedResult())
1604 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001605 else if (R.isUnresolvableResult())
1606 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001607 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001608 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1609 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001610
1611 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001612 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001613 }
1614
John McCalle66edc12009-11-24 19:00:30 +00001615 if (TemplateArgs)
1616 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001617
John McCalle66edc12009-11-24 19:00:30 +00001618 return BuildDeclarationNameExpr(SS, R, ADL);
1619}
1620
John McCall57500772009-12-16 12:17:52 +00001621/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001622ExprResult
John McCall57500772009-12-16 12:17:52 +00001623Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1624 LookupResult &R,
1625 const TemplateArgumentListInfo *TemplateArgs) {
1626 switch (ClassifyImplicitMemberAccess(*this, R)) {
1627 case IMA_Instance:
1628 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1629
John McCall57500772009-12-16 12:17:52 +00001630 case IMA_Mixed:
1631 case IMA_Mixed_Unrelated:
1632 case IMA_Unresolved:
1633 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1634
1635 case IMA_Static:
1636 case IMA_Mixed_StaticContext:
1637 case IMA_Unresolved_StaticContext:
1638 if (TemplateArgs)
1639 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1640 return BuildDeclarationNameExpr(SS, R, false);
1641
1642 case IMA_Error_StaticContext:
1643 case IMA_Error_Unrelated:
1644 DiagnoseInstanceReference(*this, SS, R);
1645 return ExprError();
1646 }
1647
1648 llvm_unreachable("unexpected instance member access kind");
1649 return ExprError();
1650}
1651
John McCall10eae182009-11-30 22:42:35 +00001652/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1653/// declaration name, generally during template instantiation.
1654/// There's a large number of things which don't need to be done along
1655/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001656ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001657Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001658 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001659 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001660 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001661 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001662
John McCall0b66eb32010-05-01 00:40:08 +00001663 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001664 return ExprError();
1665
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001666 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001667 LookupQualifiedName(R, DC);
1668
1669 if (R.isAmbiguous())
1670 return ExprError();
1671
1672 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001673 Diag(NameInfo.getLoc(), diag::err_no_member)
1674 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001675 return ExprError();
1676 }
1677
1678 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1679}
1680
1681/// LookupInObjCMethod - The parser has read a name in, and Sema has
1682/// detected that we're currently inside an ObjC method. Perform some
1683/// additional lookup.
1684///
1685/// Ideally, most of this would be done by lookup, but there's
1686/// actually quite a lot of extra work involved.
1687///
1688/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001689ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001690Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001691 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001692 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001693 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001694
John McCalle66edc12009-11-24 19:00:30 +00001695 // There are two cases to handle here. 1) scoped lookup could have failed,
1696 // in which case we should look for an ivar. 2) scoped lookup could have
1697 // found a decl, but that decl is outside the current instance method (i.e.
1698 // a global variable). In these two cases, we do a lookup for an ivar with
1699 // this name, if the lookup sucedes, we replace it our current decl.
1700
1701 // If we're in a class method, we don't normally want to look for
1702 // ivars. But if we don't find anything else, and there's an
1703 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001704 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001705
1706 bool LookForIvars;
1707 if (Lookup.empty())
1708 LookForIvars = true;
1709 else if (IsClassMethod)
1710 LookForIvars = false;
1711 else
1712 LookForIvars = (Lookup.isSingleResult() &&
1713 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001714 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001715 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001716 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001717 ObjCInterfaceDecl *ClassDeclared;
1718 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1719 // Diagnose using an ivar in a class method.
1720 if (IsClassMethod)
1721 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1722 << IV->getDeclName());
1723
1724 // If we're referencing an invalid decl, just return this as a silent
1725 // error node. The error diagnostic was already emitted on the decl.
1726 if (IV->isInvalidDecl())
1727 return ExprError();
1728
1729 // Check if referencing a field with __attribute__((deprecated)).
1730 if (DiagnoseUseOfDecl(IV, Loc))
1731 return ExprError();
1732
1733 // Diagnose the use of an ivar outside of the declaring class.
1734 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1735 ClassDeclared != IFace)
1736 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1737
1738 // FIXME: This should use a new expr for a direct reference, don't
1739 // turn this into Self->ivar, just return a BareIVarExpr or something.
1740 IdentifierInfo &II = Context.Idents.get("self");
1741 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001742 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001743 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001744 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001745 SelfName, false, false);
1746 if (SelfExpr.isInvalid())
1747 return ExprError();
1748
John McCall27584242010-12-06 20:48:59 +00001749 Expr *SelfE = SelfExpr.take();
1750 DefaultLvalueConversion(SelfE);
1751
John McCalle66edc12009-11-24 19:00:30 +00001752 MarkDeclarationReferenced(Loc, IV);
1753 return Owned(new (Context)
1754 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall27584242010-12-06 20:48:59 +00001755 SelfE, true, true));
John McCalle66edc12009-11-24 19:00:30 +00001756 }
Chris Lattner87313662010-04-12 05:10:17 +00001757 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001758 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001759 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001760 ObjCInterfaceDecl *ClassDeclared;
1761 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1762 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1763 IFace == ClassDeclared)
1764 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1765 }
1766 }
1767
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001768 if (Lookup.empty() && II && AllowBuiltinCreation) {
1769 // FIXME. Consolidate this with similar code in LookupName.
1770 if (unsigned BuiltinID = II->getBuiltinID()) {
1771 if (!(getLangOptions().CPlusPlus &&
1772 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1773 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1774 S, Lookup.isForRedeclaration(),
1775 Lookup.getNameLoc());
1776 if (D) Lookup.addDecl(D);
1777 }
1778 }
1779 }
John McCalle66edc12009-11-24 19:00:30 +00001780 // Sentinel value saying that we didn't do anything special.
1781 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001782}
John McCalld14a8642009-11-21 08:51:07 +00001783
John McCall16df1e52010-03-30 21:47:33 +00001784/// \brief Cast a base object to a member's actual type.
1785///
1786/// Logically this happens in three phases:
1787///
1788/// * First we cast from the base type to the naming class.
1789/// The naming class is the class into which we were looking
1790/// when we found the member; it's the qualifier type if a
1791/// qualifier was provided, and otherwise it's the base type.
1792///
1793/// * Next we cast from the naming class to the declaring class.
1794/// If the member we found was brought into a class's scope by
1795/// a using declaration, this is that class; otherwise it's
1796/// the class declaring the member.
1797///
1798/// * Finally we cast from the declaring class to the "true"
1799/// declaring class of the member. This conversion does not
1800/// obey access control.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001801bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001802Sema::PerformObjectMemberConversion(Expr *&From,
1803 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001804 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001805 NamedDecl *Member) {
1806 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1807 if (!RD)
1808 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001809
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001810 QualType DestRecordType;
1811 QualType DestType;
1812 QualType FromRecordType;
1813 QualType FromType = From->getType();
1814 bool PointerConversions = false;
1815 if (isa<FieldDecl>(Member)) {
1816 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001817
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001818 if (FromType->getAs<PointerType>()) {
1819 DestType = Context.getPointerType(DestRecordType);
1820 FromRecordType = FromType->getPointeeType();
1821 PointerConversions = true;
1822 } else {
1823 DestType = DestRecordType;
1824 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001825 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001826 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1827 if (Method->isStatic())
1828 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001829
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001830 DestType = Method->getThisType(Context);
1831 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001832
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001833 if (FromType->getAs<PointerType>()) {
1834 FromRecordType = FromType->getPointeeType();
1835 PointerConversions = true;
1836 } else {
1837 FromRecordType = FromType;
1838 DestType = DestRecordType;
1839 }
1840 } else {
1841 // No conversion necessary.
1842 return false;
1843 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001844
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001845 if (DestType->isDependentType() || FromType->isDependentType())
1846 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001847
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001848 // If the unqualified types are the same, no conversion is necessary.
1849 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1850 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001851
John McCall16df1e52010-03-30 21:47:33 +00001852 SourceRange FromRange = From->getSourceRange();
1853 SourceLocation FromLoc = FromRange.getBegin();
1854
John McCall2536c6d2010-08-25 10:28:54 +00001855 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001856
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001857 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001858 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001859 // class name.
1860 //
1861 // If the member was a qualified name and the qualified referred to a
1862 // specific base subobject type, we'll cast to that intermediate type
1863 // first and then to the object in which the member is declared. That allows
1864 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1865 //
1866 // class Base { public: int x; };
1867 // class Derived1 : public Base { };
1868 // class Derived2 : public Base { };
1869 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1870 //
1871 // void VeryDerived::f() {
1872 // x = 17; // error: ambiguous base subobjects
1873 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1874 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001875 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001876 QualType QType = QualType(Qualifier->getAsType(), 0);
1877 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1878 assert(QType->isRecordType() && "lookup done with non-record type");
1879
1880 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1881
1882 // In C++98, the qualifier type doesn't actually have to be a base
1883 // type of the object type, in which case we just ignore it.
1884 // Otherwise build the appropriate casts.
1885 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00001886 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001887 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001888 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001889 return true;
1890
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001891 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00001892 QType = Context.getPointerType(QType);
John McCall2536c6d2010-08-25 10:28:54 +00001893 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
1894 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00001895
1896 FromType = QType;
1897 FromRecordType = QRecordType;
1898
1899 // If the qualifier type was the same as the destination type,
1900 // we're done.
1901 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1902 return false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001903 }
1904 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001905
John McCall16df1e52010-03-30 21:47:33 +00001906 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001907
John McCall16df1e52010-03-30 21:47:33 +00001908 // If we actually found the member through a using declaration, cast
1909 // down to the using declaration's type.
1910 //
1911 // Pointer equality is fine here because only one declaration of a
1912 // class ever has member declarations.
1913 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1914 assert(isa<UsingShadowDecl>(FoundDecl));
1915 QualType URecordType = Context.getTypeDeclType(
1916 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1917
1918 // We only need to do this if the naming-class to declaring-class
1919 // conversion is non-trivial.
1920 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1921 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00001922 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001923 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001924 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001925 return true;
Alexis Huntc46382e2010-04-28 23:02:27 +00001926
John McCall16df1e52010-03-30 21:47:33 +00001927 QualType UType = URecordType;
1928 if (PointerConversions)
1929 UType = Context.getPointerType(UType);
John McCalle3027922010-08-25 11:45:40 +00001930 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001931 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00001932 FromType = UType;
1933 FromRecordType = URecordType;
1934 }
1935
1936 // We don't do access control for the conversion from the
1937 // declaring class to the true declaring class.
1938 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001939 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001940
John McCallcf142162010-08-07 06:22:56 +00001941 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00001942 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1943 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00001944 IgnoreAccess))
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001945 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001946
John McCalle3027922010-08-25 11:45:40 +00001947 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001948 VK, &BasePath);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001949 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001950}
Douglas Gregor3256d042009-06-30 15:47:41 +00001951
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001952/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001953static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001954 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00001955 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001956 const DeclarationNameInfo &MemberNameInfo,
1957 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00001958 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00001959 const TemplateArgumentListInfo *TemplateArgs = 0) {
1960 NestedNameSpecifier *Qualifier = 0;
1961 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001962 if (SS.isSet()) {
1963 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1964 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001965 }
Mike Stump11289f42009-09-09 15:08:12 +00001966
John McCalle66edc12009-11-24 19:00:30 +00001967 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001968 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00001969 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00001970}
1971
John McCallfeb624a2010-11-23 20:48:44 +00001972static ExprResult
1973BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1974 const CXXScopeSpec &SS, FieldDecl *Field,
1975 DeclAccessPair FoundDecl,
1976 const DeclarationNameInfo &MemberNameInfo) {
1977 // x.a is an l-value if 'a' has a reference type. Otherwise:
1978 // x.a is an l-value/x-value/pr-value if the base is (and note
1979 // that *x is always an l-value), except that if the base isn't
1980 // an ordinary object then we must have an rvalue.
1981 ExprValueKind VK = VK_LValue;
1982 ExprObjectKind OK = OK_Ordinary;
1983 if (!IsArrow) {
1984 if (BaseExpr->getObjectKind() == OK_Ordinary)
1985 VK = BaseExpr->getValueKind();
1986 else
1987 VK = VK_RValue;
1988 }
1989 if (VK != VK_RValue && Field->isBitField())
1990 OK = OK_BitField;
1991
1992 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1993 QualType MemberType = Field->getType();
1994 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1995 MemberType = Ref->getPointeeType();
1996 VK = VK_LValue;
1997 } else {
1998 QualType BaseType = BaseExpr->getType();
1999 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2000
2001 Qualifiers BaseQuals = BaseType.getQualifiers();
2002
2003 // GC attributes are never picked up by members.
2004 BaseQuals.removeObjCGCAttr();
2005
2006 // CVR attributes from the base are picked up by members,
2007 // except that 'mutable' members don't pick up 'const'.
2008 if (Field->isMutable()) BaseQuals.removeConst();
2009
2010 Qualifiers MemberQuals
2011 = S.Context.getCanonicalType(MemberType).getQualifiers();
2012
2013 // TR 18037 does not allow fields to be declared with address spaces.
2014 assert(!MemberQuals.hasAddressSpace());
2015
2016 Qualifiers Combined = BaseQuals + MemberQuals;
2017 if (Combined != MemberQuals)
2018 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2019 }
2020
2021 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2022 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2023 FoundDecl, Field))
2024 return ExprError();
2025 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2026 Field, FoundDecl, MemberNameInfo,
2027 MemberType, VK, OK));
2028}
2029
John McCall2d74de92009-12-01 22:10:20 +00002030/// Builds an implicit member access expression. The current context
2031/// is known to be an instance method, and the given unqualified lookup
2032/// set is known to contain only instance members, at least one of which
2033/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002034ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002035Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2036 LookupResult &R,
2037 const TemplateArgumentListInfo *TemplateArgs,
2038 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002039 assert(!R.empty() && !R.isAmbiguous());
2040
John McCalld14a8642009-11-21 08:51:07 +00002041 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002042
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002043 // We may have found a field within an anonymous union or struct
2044 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00002045 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00002046 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002047 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00002048 return BuildAnonymousStructUnionMemberReference(Loc, SS, FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002049
Sebastian Redlffbcf962009-01-18 18:53:16 +00002050
John McCall2d74de92009-12-01 22:10:20 +00002051 // If this is known to be an instance access, go ahead and build a
2052 // 'this' expression now.
John McCall87fe5d52010-05-20 01:18:31 +00002053 DeclContext *DC = getFunctionLevelDeclContext();
2054 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2d74de92009-12-01 22:10:20 +00002055 Expr *This = 0; // null signifies implicit access
2056 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002057 SourceLocation Loc = R.getNameLoc();
2058 if (SS.getRange().isValid())
2059 Loc = SS.getRange().getBegin();
2060 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002061 }
2062
John McCallb268a282010-08-23 23:25:46 +00002063 return BuildMemberReferenceExpr(This, ThisType,
John McCall2d74de92009-12-01 22:10:20 +00002064 /*OpLoc*/ SourceLocation(),
2065 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002066 SS,
2067 /*FirstQualifierInScope*/ 0,
2068 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002069}
2070
John McCalle66edc12009-11-24 19:00:30 +00002071bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002072 const LookupResult &R,
2073 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002074 // Only when used directly as the postfix-expression of a call.
2075 if (!HasTrailingLParen)
2076 return false;
2077
2078 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002079 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002080 return false;
2081
2082 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002083 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002084 return false;
2085
2086 // Turn off ADL when we find certain kinds of declarations during
2087 // normal lookup:
2088 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2089 NamedDecl *D = *I;
2090
2091 // C++0x [basic.lookup.argdep]p3:
2092 // -- a declaration of a class member
2093 // Since using decls preserve this property, we check this on the
2094 // original decl.
John McCall57500772009-12-16 12:17:52 +00002095 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002096 return false;
2097
2098 // C++0x [basic.lookup.argdep]p3:
2099 // -- a block-scope function declaration that is not a
2100 // using-declaration
2101 // NOTE: we also trigger this for function templates (in fact, we
2102 // don't check the decl type at all, since all other decl types
2103 // turn off ADL anyway).
2104 if (isa<UsingShadowDecl>(D))
2105 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2106 else if (D->getDeclContext()->isFunctionOrMethod())
2107 return false;
2108
2109 // C++0x [basic.lookup.argdep]p3:
2110 // -- a declaration that is neither a function or a function
2111 // template
2112 // And also for builtin functions.
2113 if (isa<FunctionDecl>(D)) {
2114 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2115
2116 // But also builtin functions.
2117 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2118 return false;
2119 } else if (!isa<FunctionTemplateDecl>(D))
2120 return false;
2121 }
2122
2123 return true;
2124}
2125
2126
John McCalld14a8642009-11-21 08:51:07 +00002127/// Diagnoses obvious problems with the use of the given declaration
2128/// as an expression. This is only actually called for lookups that
2129/// were not overloaded, and it doesn't promise that the declaration
2130/// will in fact be used.
2131static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2132 if (isa<TypedefDecl>(D)) {
2133 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2134 return true;
2135 }
2136
2137 if (isa<ObjCInterfaceDecl>(D)) {
2138 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2139 return true;
2140 }
2141
2142 if (isa<NamespaceDecl>(D)) {
2143 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2144 return true;
2145 }
2146
2147 return false;
2148}
2149
John McCalldadc5752010-08-24 06:29:42 +00002150ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002151Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002152 LookupResult &R,
2153 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002154 // If this is a single, fully-resolved result and we don't need ADL,
2155 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002156 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002157 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2158 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002159
2160 // We only need to check the declaration if there's exactly one
2161 // result, because in the overloaded case the results can only be
2162 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002163 if (R.isSingleResult() &&
2164 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002165 return ExprError();
2166
John McCall58cc69d2010-01-27 01:50:18 +00002167 // Otherwise, just build an unresolved lookup expression. Suppress
2168 // any lookup-related diagnostics; we'll hash these out later, when
2169 // we've picked a target.
2170 R.suppressDiagnostics();
2171
John McCalld14a8642009-11-21 08:51:07 +00002172 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002173 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00002174 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002175 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002176 NeedsADL, R.isOverloadedResult(),
2177 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002178
2179 return Owned(ULE);
2180}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002181
John McCall7decc9e2010-11-18 06:31:45 +00002182static ExprValueKind getValueKindForDecl(ASTContext &Context,
2183 const ValueDecl *D) {
John McCall4bc41ae2010-11-18 19:01:18 +00002184 // FIXME: It's not clear to me why NonTypeTemplateParmDecl is a VarDecl.
2185 if (isa<VarDecl>(D) && !isa<NonTypeTemplateParmDecl>(D)) return VK_LValue;
2186 if (isa<FieldDecl>(D)) return VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00002187 if (!Context.getLangOptions().CPlusPlus) return VK_RValue;
2188 if (isa<FunctionDecl>(D)) {
2189 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
2190 return VK_RValue;
2191 return VK_LValue;
2192 }
2193 return Expr::getValueKindForType(D->getType());
2194}
2195
John McCalld14a8642009-11-21 08:51:07 +00002196
2197/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002198ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002199Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002200 const DeclarationNameInfo &NameInfo,
2201 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002202 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002203 assert(!isa<FunctionTemplateDecl>(D) &&
2204 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002205
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002206 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002207 if (CheckDeclInExpr(*this, Loc, D))
2208 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002209
Douglas Gregore7488b92009-12-01 16:58:18 +00002210 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2211 // Specifically diagnose references to class templates that are missing
2212 // a template argument list.
2213 Diag(Loc, diag::err_template_decl_ref)
2214 << Template << SS.getRange();
2215 Diag(Template->getLocation(), diag::note_template_decl_here);
2216 return ExprError();
2217 }
2218
2219 // Make sure that we're referring to a value.
2220 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2221 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002222 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002223 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002224 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002225 return ExprError();
2226 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002227
Douglas Gregor171c45a2009-02-18 21:56:37 +00002228 // Check whether this declaration can be used. Note that we suppress
2229 // this check when we're going to perform argument-dependent lookup
2230 // on this function name, because this might not be the function
2231 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002232 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002233 return ExprError();
2234
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002235 // Only create DeclRefExpr's for valid Decl's.
2236 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002237 return ExprError();
2238
Francois Pichet783dd6e2010-11-21 06:08:52 +00002239 // Handle anonymous.
2240 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(VD))
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00002241 return BuildAnonymousStructUnionMemberReference(Loc, SS, FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002242
John McCall7decc9e2010-11-18 06:31:45 +00002243 ExprValueKind VK = getValueKindForDecl(Context, VD);
2244
Chris Lattner2a9d9892008-10-20 05:16:36 +00002245 // If the identifier reference is inside a block, and it refers to a value
2246 // that is outside the block, create a BlockDeclRefExpr instead of a
2247 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2248 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002249 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002250 // We do not do this for things like enum constants, global variables, etc,
2251 // as they do not get snapshotted.
2252 //
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002253 if (getCurBlock() &&
Douglas Gregor9a28e842010-03-01 23:15:13 +00002254 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
Mike Stump7dafa0d2010-01-05 02:56:35 +00002255 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
2256 Diag(Loc, diag::err_ref_vm_type);
2257 Diag(D->getLocation(), diag::note_declared_at);
2258 return ExprError();
2259 }
2260
Fariborz Jahanianfa24e102010-03-16 23:39:51 +00002261 if (VD->getType()->isArrayType()) {
Mike Stump8971a862010-01-05 03:10:36 +00002262 Diag(Loc, diag::err_ref_array_type);
2263 Diag(D->getLocation(), diag::note_declared_at);
2264 return ExprError();
2265 }
2266
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00002267 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00002268 QualType ExprTy = VD->getType().getNonReferenceType();
John McCall7decc9e2010-11-18 06:31:45 +00002269
Steve Naroff1d95e5a2008-10-10 01:28:17 +00002270 // The BlocksAttr indicates the variable is bound by-reference.
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002271 bool byrefVar = (VD->getAttr<BlocksAttr>() != 0);
Fariborz Jahanian70c0b082010-07-12 17:26:57 +00002272 QualType T = VD->getType();
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002273 BlockDeclRefExpr *BDRE;
2274
2275 if (!byrefVar) {
2276 // This is to record that a 'const' was actually synthesize and added.
2277 bool constAdded = !ExprTy.isConstQualified();
2278 // Variable will be bound by-copy, make it const within the closure.
2279 ExprTy.addConst();
John McCall7decc9e2010-11-18 06:31:45 +00002280 BDRE = new (Context) BlockDeclRefExpr(VD, ExprTy, VK,
2281 Loc, false, constAdded);
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002282 }
2283 else
John McCall7decc9e2010-11-18 06:31:45 +00002284 BDRE = new (Context) BlockDeclRefExpr(VD, ExprTy, VK, Loc, true);
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002285
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002286 if (getLangOptions().CPlusPlus) {
2287 if (!T->isDependentType() && !T->isReferenceType()) {
2288 Expr *E = new (Context)
2289 DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T,
John McCall7decc9e2010-11-18 06:31:45 +00002290 VK, SourceLocation());
Fariborz Jahanian2a5deb52010-11-11 00:11:38 +00002291 if (T->getAs<RecordType>())
2292 if (!T->isUnionType()) {
2293 ExprResult Res = PerformCopyInitialization(
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002294 InitializedEntity::InitializeBlock(VD->getLocation(),
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002295 T, false),
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002296 SourceLocation(),
2297 Owned(E));
Fariborz Jahanian2a5deb52010-11-11 00:11:38 +00002298 if (!Res.isInvalid()) {
Douglas Gregora40433a2010-12-07 00:41:46 +00002299 Res = MaybeCreateExprWithCleanups(Res);
Fariborz Jahanian2a5deb52010-11-11 00:11:38 +00002300 Expr *Init = Res.takeAs<Expr>();
2301 BDRE->setCopyConstructorExpr(Init);
2302 }
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002303 }
Fariborz Jahanianea882cd2010-06-04 21:35:44 +00002304 }
2305 }
2306 return Owned(BDRE);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00002307 }
2308 // If this reference is not in a block or if the referenced variable is
2309 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00002310
John McCall7decc9e2010-11-18 06:31:45 +00002311 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002312 NameInfo, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00002313}
Chris Lattnere168f762006-11-10 05:29:30 +00002314
John McCalldadc5752010-08-24 06:29:42 +00002315ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlffbcf962009-01-18 18:53:16 +00002316 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002317 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002318
Chris Lattnere168f762006-11-10 05:29:30 +00002319 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002320 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002321 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2322 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2323 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002324 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002325
Chris Lattnera81a0272008-01-12 08:14:25 +00002326 // Pre-defined identifiers are of type char[x], where x is the length of the
2327 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002328
Anders Carlsson2fb08242009-09-08 18:24:21 +00002329 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002330 if (!currentDecl && getCurBlock())
2331 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002332 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002333 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002334 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002335 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002336
Anders Carlsson0b209a82009-09-11 01:22:35 +00002337 QualType ResTy;
2338 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2339 ResTy = Context.DependentTy;
2340 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002341 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002342
Anders Carlsson0b209a82009-09-11 01:22:35 +00002343 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002344 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002345 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2346 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002347 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002348}
2349
John McCalldadc5752010-08-24 06:29:42 +00002350ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002351 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002352 bool Invalid = false;
2353 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2354 if (Invalid)
2355 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002356
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002357 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2358 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002359 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002360 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002361
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002362 QualType Ty;
2363 if (!getLangOptions().CPlusPlus)
2364 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2365 else if (Literal.isWide())
2366 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002367 else if (Literal.isMultiChar())
2368 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002369 else
2370 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002371
Sebastian Redl20614a72009-01-20 22:23:13 +00002372 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2373 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002374 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002375}
2376
John McCalldadc5752010-08-24 06:29:42 +00002377ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002378 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002379 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2380 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002381 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002382 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002383 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002384 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002385 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002386
Chris Lattner23b7eb62007-06-15 23:05:46 +00002387 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002388 // Add padding so that NumericLiteralParser can overread by one character.
2389 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002390 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002391
Chris Lattner67ca9252007-05-21 01:08:44 +00002392 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002393 bool Invalid = false;
2394 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2395 if (Invalid)
2396 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002397
Mike Stump11289f42009-09-09 15:08:12 +00002398 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002399 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002400 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002401 return ExprError();
2402
Chris Lattner1c20a172007-08-26 03:42:43 +00002403 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002404
Chris Lattner1c20a172007-08-26 03:42:43 +00002405 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002406 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002407 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002408 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002409 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002410 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002411 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002412 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002413
2414 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2415
John McCall53b93a02009-12-24 09:08:04 +00002416 using llvm::APFloat;
2417 APFloat Val(Format);
2418
2419 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002420
2421 // Overflow is always an error, but underflow is only an error if
2422 // we underflowed to zero (APFloat reports denormals as underflow).
2423 if ((result & APFloat::opOverflow) ||
2424 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002425 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002426 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002427 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002428 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002429 APFloat::getLargest(Format).toString(buffer);
2430 } else {
John McCall62abc942010-02-26 23:35:57 +00002431 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002432 APFloat::getSmallest(Format).toString(buffer);
2433 }
2434
2435 Diag(Tok.getLocation(), diagnostic)
2436 << Ty
2437 << llvm::StringRef(buffer.data(), buffer.size());
2438 }
2439
2440 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002441 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002442
Peter Collingbourne0b69e1a2010-12-04 01:50:56 +00002443 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2444 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2445
Chris Lattner1c20a172007-08-26 03:42:43 +00002446 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002447 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002448 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002449 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002450
Neil Boothac582c52007-08-29 22:00:19 +00002451 // long long is a C99 feature.
2452 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002453 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002454 Diag(Tok.getLocation(), diag::ext_longlong);
2455
Chris Lattner67ca9252007-05-21 01:08:44 +00002456 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002457 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002458
Chris Lattner67ca9252007-05-21 01:08:44 +00002459 if (Literal.GetIntegerValue(ResultVal)) {
2460 // If this value didn't fit into uintmax_t, warn and force to ull.
2461 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002462 Ty = Context.UnsignedLongLongTy;
2463 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002464 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002465 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002466 // If this value fits into a ULL, try to figure out what else it fits into
2467 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002468
Chris Lattner67ca9252007-05-21 01:08:44 +00002469 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2470 // be an unsigned int.
2471 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2472
2473 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002474 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002475 if (!Literal.isLong && !Literal.isLongLong) {
2476 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002477 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002478
Chris Lattner67ca9252007-05-21 01:08:44 +00002479 // Does it fit in a unsigned int?
2480 if (ResultVal.isIntN(IntSize)) {
2481 // Does it fit in a signed int?
2482 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002483 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002484 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002485 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002486 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002487 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002488 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002489
Chris Lattner67ca9252007-05-21 01:08:44 +00002490 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002491 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002492 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002493
Chris Lattner67ca9252007-05-21 01:08:44 +00002494 // Does it fit in a unsigned long?
2495 if (ResultVal.isIntN(LongSize)) {
2496 // Does it fit in a signed long?
2497 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002498 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002499 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002500 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002501 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002502 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002503 }
2504
Chris Lattner67ca9252007-05-21 01:08:44 +00002505 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002506 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002507 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002508
Chris Lattner67ca9252007-05-21 01:08:44 +00002509 // Does it fit in a unsigned long long?
2510 if (ResultVal.isIntN(LongLongSize)) {
2511 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002512 // To be compatible with MSVC, hex integer literals ending with the
2513 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002514 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2515 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002516 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002517 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002518 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002519 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002520 }
2521 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002522
Chris Lattner67ca9252007-05-21 01:08:44 +00002523 // If we still couldn't decide a type, we probably have something that
2524 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002525 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002526 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002527 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002528 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002529 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002530
Chris Lattner55258cf2008-05-09 05:59:00 +00002531 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002532 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002533 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002534 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002535 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002536
Chris Lattner1c20a172007-08-26 03:42:43 +00002537 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2538 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002539 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002540 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002541
2542 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002543}
2544
John McCalldadc5752010-08-24 06:29:42 +00002545ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002546 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002547 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002548 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002549}
2550
Steve Naroff71b59a92007-06-04 22:22:31 +00002551/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002552/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002553bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00002554 SourceLocation OpLoc,
John McCall36e7fe32010-10-12 00:20:44 +00002555 SourceRange ExprRange,
Sebastian Redl6f282892008-11-11 17:56:53 +00002556 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002557 if (exprType->isDependentType())
2558 return false;
2559
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002560 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2561 // the result is the size of the referenced type."
2562 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2563 // result shall be the alignment of the referenced type."
2564 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2565 exprType = Ref->getPointeeType();
2566
Steve Naroff043d45d2007-05-15 02:32:35 +00002567 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002568 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002569 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002570 if (isSizeof)
2571 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2572 return false;
2573 }
Mike Stump11289f42009-09-09 15:08:12 +00002574
Chris Lattner62975a72009-04-24 00:30:45 +00002575 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002576 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002577 Diag(OpLoc, diag::ext_sizeof_void_type)
2578 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002579 return false;
2580 }
Mike Stump11289f42009-09-09 15:08:12 +00002581
Chris Lattner62975a72009-04-24 00:30:45 +00002582 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002583 PDiag(diag::err_sizeof_alignof_incomplete_type)
2584 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002585 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002586
Chris Lattner62975a72009-04-24 00:30:45 +00002587 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002588 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002589 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002590 << exprType << isSizeof << ExprRange;
2591 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002592 }
Mike Stump11289f42009-09-09 15:08:12 +00002593
Chris Lattner62975a72009-04-24 00:30:45 +00002594 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002595}
2596
John McCall36e7fe32010-10-12 00:20:44 +00002597static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2598 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002599 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002600
Mike Stump11289f42009-09-09 15:08:12 +00002601 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002602 if (isa<DeclRefExpr>(E))
2603 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002604
2605 // Cannot know anything else if the expression is dependent.
2606 if (E->isTypeDependent())
2607 return false;
2608
Douglas Gregor71235ec2009-05-02 02:18:30 +00002609 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00002610 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00002611 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002612 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002613
2614 // Alignment of a field access is always okay, so long as it isn't a
2615 // bit-field.
2616 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002617 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002618 return false;
2619
John McCall36e7fe32010-10-12 00:20:44 +00002620 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
Chris Lattner8dff0172009-01-24 20:17:12 +00002621}
2622
Douglas Gregor0950e412009-03-13 21:01:28 +00002623/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002624ExprResult
John McCallbcd03502009-12-07 02:54:59 +00002625Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00002626 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002627 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002628 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002629 return ExprError();
2630
John McCallbcd03502009-12-07 02:54:59 +00002631 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002632
Douglas Gregor0950e412009-03-13 21:01:28 +00002633 if (!T->isDependentType() &&
2634 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2635 return ExprError();
2636
2637 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00002638 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00002639 Context.getSizeType(), OpLoc,
2640 R.getEnd()));
2641}
2642
2643/// \brief Build a sizeof or alignof expression given an expression
2644/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002645ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00002646Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002647 bool isSizeOf, SourceRange R) {
2648 // Verify that the operand is valid.
2649 bool isInvalid = false;
2650 if (E->isTypeDependent()) {
2651 // Delay type-checking for type-dependent expressions.
2652 } else if (!isSizeOf) {
John McCall36e7fe32010-10-12 00:20:44 +00002653 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002654 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002655 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2656 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00002657 } else if (E->getType()->isPlaceholderType()) {
2658 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2659 if (PE.isInvalid()) return ExprError();
2660 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00002661 } else {
2662 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2663 }
2664
2665 if (isInvalid)
2666 return ExprError();
2667
2668 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2669 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2670 Context.getSizeType(), OpLoc,
2671 R.getEnd()));
2672}
2673
Sebastian Redl6f282892008-11-11 17:56:53 +00002674/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2675/// the same for @c alignof and @c __alignof
2676/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002677ExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00002678Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2679 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002680 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002681 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002682
Sebastian Redl6f282892008-11-11 17:56:53 +00002683 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002684 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002685 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
John McCallbcd03502009-12-07 02:54:59 +00002686 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002687 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002688
Douglas Gregor0950e412009-03-13 21:01:28 +00002689 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00002690 ExprResult Result
Douglas Gregor0950e412009-03-13 21:01:28 +00002691 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2692
Douglas Gregor0950e412009-03-13 21:01:28 +00002693 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002694}
2695
John McCall4bc41ae2010-11-18 19:01:18 +00002696static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2697 bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002698 if (V->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002699 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002700
John McCall34376a62010-12-04 03:47:34 +00002701 // _Real and _Imag are only l-values for normal l-values.
2702 if (V->getObjectKind() != OK_Ordinary)
John McCall27584242010-12-06 20:48:59 +00002703 S.DefaultLvalueConversion(V);
John McCall34376a62010-12-04 03:47:34 +00002704
Chris Lattnere267f5d2007-08-26 05:39:26 +00002705 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00002706 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002707 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002708
Chris Lattnere267f5d2007-08-26 05:39:26 +00002709 // Otherwise they pass through real integer and floating point types here.
2710 if (V->getType()->isArithmeticType())
2711 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002712
John McCall36226622010-10-12 02:09:17 +00002713 // Test for placeholders.
John McCall4bc41ae2010-11-18 19:01:18 +00002714 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall36226622010-10-12 02:09:17 +00002715 if (PR.isInvalid()) return QualType();
2716 if (PR.take() != V) {
2717 V = PR.take();
John McCall4bc41ae2010-11-18 19:01:18 +00002718 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002719 }
2720
Chris Lattnere267f5d2007-08-26 05:39:26 +00002721 // Reject anything else.
John McCall4bc41ae2010-11-18 19:01:18 +00002722 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002723 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002724 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002725}
2726
2727
Chris Lattnere168f762006-11-10 05:29:30 +00002728
John McCalldadc5752010-08-24 06:29:42 +00002729ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002730Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002731 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002732 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002733 switch (Kind) {
2734 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002735 case tok::plusplus: Opc = UO_PostInc; break;
2736 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002737 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002738
John McCallb268a282010-08-23 23:25:46 +00002739 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002740}
2741
John McCall4bc41ae2010-11-18 19:01:18 +00002742/// Expressions of certain arbitrary types are forbidden by C from
2743/// having l-value type. These are:
2744/// - 'void', but not qualified void
2745/// - function types
2746///
2747/// The exact rule here is C99 6.3.2.1:
2748/// An lvalue is an expression with an object type or an incomplete
2749/// type other than void.
2750static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2751 return ((T->isVoidType() && !T.hasQualifiers()) ||
2752 T->isFunctionType());
2753}
2754
John McCalldadc5752010-08-24 06:29:42 +00002755ExprResult
John McCallb268a282010-08-23 23:25:46 +00002756Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2757 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002758 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002759 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002760 if (Result.isInvalid()) return ExprError();
2761 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002762
John McCallb268a282010-08-23 23:25:46 +00002763 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002764
Douglas Gregor40412ac2008-11-19 17:17:41 +00002765 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002766 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002767 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002768 Context.DependentTy,
2769 VK_LValue, OK_Ordinary,
2770 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002771 }
2772
Mike Stump11289f42009-09-09 15:08:12 +00002773 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002774 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002775 LHSExp->getType()->isEnumeralType() ||
2776 RHSExp->getType()->isRecordType() ||
2777 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002778 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002779 }
2780
John McCallb268a282010-08-23 23:25:46 +00002781 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002782}
2783
2784
John McCalldadc5752010-08-24 06:29:42 +00002785ExprResult
John McCallb268a282010-08-23 23:25:46 +00002786Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2787 Expr *Idx, SourceLocation RLoc) {
2788 Expr *LHSExp = Base;
2789 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002790
Chris Lattner36d572b2007-07-16 00:14:47 +00002791 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002792 if (!LHSExp->getType()->getAs<VectorType>())
2793 DefaultFunctionArrayLvalueConversion(LHSExp);
2794 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002795
Chris Lattner36d572b2007-07-16 00:14:47 +00002796 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00002797 ExprValueKind VK = VK_LValue;
2798 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00002799
Steve Naroffc1aadb12007-03-28 21:49:40 +00002800 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002801 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002802 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002803 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002804 Expr *BaseExpr, *IndexExpr;
2805 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002806 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2807 BaseExpr = LHSExp;
2808 IndexExpr = RHSExp;
2809 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002810 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002811 BaseExpr = LHSExp;
2812 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002813 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002814 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002815 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002816 BaseExpr = RHSExp;
2817 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002818 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002819 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002820 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002821 BaseExpr = LHSExp;
2822 IndexExpr = RHSExp;
2823 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002824 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002825 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002826 // Handle the uncommon case of "123[Ptr]".
2827 BaseExpr = RHSExp;
2828 IndexExpr = LHSExp;
2829 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00002830 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00002831 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00002832 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00002833 VK = LHSExp->getValueKind();
2834 if (VK != VK_RValue)
2835 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00002836
Chris Lattner36d572b2007-07-16 00:14:47 +00002837 // FIXME: need to deal with const...
2838 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002839 } else if (LHSTy->isArrayType()) {
2840 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00002841 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00002842 // wasn't promoted because of the C90 rule that doesn't
2843 // allow promoting non-lvalue arrays. Warn, then
2844 // force the promotion here.
2845 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2846 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002847 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCalle3027922010-08-25 11:45:40 +00002848 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002849 LHSTy = LHSExp->getType();
2850
2851 BaseExpr = LHSExp;
2852 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002853 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002854 } else if (RHSTy->isArrayType()) {
2855 // Same as previous, except for 123[f().a] case
2856 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2857 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002858 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCalle3027922010-08-25 11:45:40 +00002859 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002860 RHSTy = RHSExp->getType();
2861
2862 BaseExpr = RHSExp;
2863 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002864 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00002865 } else {
Chris Lattner003af242009-04-25 22:50:55 +00002866 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2867 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002868 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00002869 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002870 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00002871 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2872 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00002873
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002874 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00002875 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2876 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00002877 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2878
Douglas Gregorac1fb652009-03-24 19:52:54 +00002879 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00002880 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2881 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00002882 // incomplete types are not object types.
2883 if (ResultType->isFunctionType()) {
2884 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2885 << ResultType << BaseExpr->getSourceRange();
2886 return ExprError();
2887 }
Mike Stump11289f42009-09-09 15:08:12 +00002888
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00002889 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
2890 // GNU extension: subscripting on pointer to void
2891 Diag(LLoc, diag::ext_gnu_void_ptr)
2892 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00002893
2894 // C forbids expressions of unqualified void type from being l-values.
2895 // See IsCForbiddenLValueType.
2896 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00002897 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00002898 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00002899 PDiag(diag::err_subscript_incomplete_type)
2900 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00002901 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002902
Chris Lattner62975a72009-04-24 00:30:45 +00002903 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00002904 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00002905 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2906 << ResultType << BaseExpr->getSourceRange();
2907 return ExprError();
2908 }
Mike Stump11289f42009-09-09 15:08:12 +00002909
John McCall4bc41ae2010-11-18 19:01:18 +00002910 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
2911 !IsCForbiddenLValueType(Context, ResultType));
2912
Mike Stump4e1f26a2009-02-19 03:04:26 +00002913 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002914 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00002915}
2916
John McCall4bc41ae2010-11-18 19:01:18 +00002917/// Check an ext-vector component access expression.
2918///
2919/// VK should be set in advance to the value kind of the base
2920/// expression.
2921static QualType
2922CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
2923 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00002924 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00002925 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2926 // see FIXME there.
2927 //
2928 // FIXME: This logic can be greatly simplified by splitting it along
2929 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00002930 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00002931
Steve Narofff8fd09e2007-07-27 22:15:19 +00002932 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002933 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002934
Mike Stump4e1f26a2009-02-19 03:04:26 +00002935 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00002936 // special names that indicate a subset of exactly half the elements are
2937 // to be selected.
2938 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002939
Nate Begemanbb70bf62009-01-18 01:47:54 +00002940 // This flag determines whether or not CompName has an 's' char prefix,
2941 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00002942 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00002943
John McCall4bc41ae2010-11-18 19:01:18 +00002944 bool HasRepeated = false;
2945 bool HasIndex[16] = {};
2946
2947 int Idx;
2948
Nate Begemanf322eab2008-05-09 06:41:27 +00002949 // Check that we've found one of the special components, or that the component
2950 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002951 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00002952 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2953 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00002954 } else if (!HexSwizzle &&
2955 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
2956 do {
2957 if (HasIndex[Idx]) HasRepeated = true;
2958 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00002959 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00002960 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
2961 } else {
2962 if (HexSwizzle) compStr++;
2963 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
2964 if (HasIndex[Idx]) HasRepeated = true;
2965 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00002966 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00002967 }
Chris Lattner7e152db2007-08-02 22:33:49 +00002968 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002969
Mike Stump4e1f26a2009-02-19 03:04:26 +00002970 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002971 // We didn't get to the end of the string. This means the component names
2972 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00002973 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00002974 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002975 return QualType();
2976 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002977
Nate Begemanbb70bf62009-01-18 01:47:54 +00002978 // Ensure no component accessor exceeds the width of the vector type it
2979 // operates on.
2980 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002981 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002982
2983 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002984 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002985
2986 while (*compStr) {
2987 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00002988 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00002989 << baseType << SourceRange(CompLoc);
2990 return QualType();
2991 }
2992 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002993 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002994
Steve Narofff8fd09e2007-07-27 22:15:19 +00002995 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002996 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002997 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002998 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002999 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00003000 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00003001 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003002 if (HexSwizzle)
3003 CompSize--;
3004
Steve Narofff8fd09e2007-07-27 22:15:19 +00003005 if (CompSize == 1)
3006 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003007
John McCall4bc41ae2010-11-18 19:01:18 +00003008 if (HasRepeated) VK = VK_RValue;
3009
3010 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003011 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003012 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003013 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3014 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3015 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003016 }
3017 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003018}
3019
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003020static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003021 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003022 const Selector &Sel,
3023 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003024 if (Member)
3025 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3026 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003027 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003028 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003029
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003030 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3031 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003032 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3033 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003034 return D;
3035 }
3036 return 0;
3037}
3038
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003039static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3040 IdentifierInfo *Member,
3041 const Selector &Sel,
3042 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003043 // Check protocols on qualified interfaces.
3044 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003045 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003046 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003047 if (Member)
3048 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3049 GDecl = PD;
3050 break;
3051 }
3052 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003053 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003054 GDecl = OMD;
3055 break;
3056 }
3057 }
3058 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003059 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003060 E = QIdTy->qual_end(); I != E; ++I) {
3061 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003062 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3063 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003064 if (GDecl)
3065 return GDecl;
3066 }
3067 }
3068 return GDecl;
3069}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003070
John McCalldadc5752010-08-24 06:29:42 +00003071ExprResult
John McCallb268a282010-08-23 23:25:46 +00003072Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003073 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003074 const CXXScopeSpec &SS,
3075 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003076 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003077 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003078 // Even in dependent contexts, try to diagnose base expressions with
3079 // obviously wrong types, e.g.:
3080 //
3081 // T* t;
3082 // t.f;
3083 //
3084 // In Obj-C++, however, the above expression is valid, since it could be
3085 // accessing the 'f' property if T is an Obj-C interface. The extra check
3086 // allows this, while still reporting an error if T is a struct pointer.
3087 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003088 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003089 if (PT && (!getLangOptions().ObjC1 ||
3090 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003091 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003092 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003093 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003094 return ExprError();
3095 }
3096 }
3097
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003098 assert(BaseType->isDependentType() ||
3099 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003100 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003101
3102 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3103 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003104 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003105 IsArrow, OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003106 SS.getScopeRep(),
John McCall10eae182009-11-30 22:42:35 +00003107 SS.getRange(),
3108 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003109 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003110}
3111
3112/// We know that the given qualified member reference points only to
3113/// declarations which do not belong to the static type of the base
3114/// expression. Diagnose the problem.
3115static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3116 Expr *BaseExpr,
3117 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003118 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003119 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00003120 // If this is an implicit member access, use a different set of
3121 // diagnostics.
3122 if (!BaseExpr)
3123 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00003124
John McCall1e67dd62010-04-27 01:43:38 +00003125 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
3126 << SS.getRange() << R.getRepresentativeDecl() << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003127}
3128
3129// Check whether the declarations we found through a nested-name
3130// specifier in a member expression are actually members of the base
3131// type. The restriction here is:
3132//
3133// C++ [expr.ref]p2:
3134// ... In these cases, the id-expression shall name a
3135// member of the class or of one of its base classes.
3136//
3137// So it's perfectly legitimate for the nested-name specifier to name
3138// an unrelated class, and for us to find an overload set including
3139// decls from classes which are not superclasses, as long as the decl
3140// we actually pick through overload resolution is from a superclass.
3141bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3142 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003143 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003144 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003145 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3146 if (!BaseRT) {
3147 // We can't check this yet because the base type is still
3148 // dependent.
3149 assert(BaseType->isDependentType());
3150 return false;
3151 }
3152 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003153
3154 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003155 // If this is an implicit member reference and we find a
3156 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003157 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003158 return false;
John McCall10eae182009-11-30 22:42:35 +00003159
John McCall2d74de92009-12-01 22:10:20 +00003160 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003161 DeclContext *DC = (*I)->getDeclContext();
3162 while (DC->isTransparentContext())
3163 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003164
Douglas Gregora9c3e822010-07-28 22:27:52 +00003165 if (!DC->isRecord())
3166 continue;
3167
John McCall2d74de92009-12-01 22:10:20 +00003168 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003169 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003170
3171 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3172 return false;
3173 }
3174
John McCallcd4b4772009-12-02 03:53:29 +00003175 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00003176 return true;
3177}
3178
3179static bool
3180LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3181 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003182 SourceLocation OpLoc, CXXScopeSpec &SS,
3183 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003184 RecordDecl *RDecl = RTy->getDecl();
3185 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003186 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003187 << BaseRange))
3188 return true;
3189
John McCalle9cccd82010-06-16 08:42:20 +00003190 if (HasTemplateArgs) {
3191 // LookupTemplateName doesn't expect these both to exist simultaneously.
3192 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3193
3194 bool MOUS;
3195 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3196 return false;
3197 }
3198
John McCall2d74de92009-12-01 22:10:20 +00003199 DeclContext *DC = RDecl;
3200 if (SS.isSet()) {
3201 // If the member name was a qualified-id, look into the
3202 // nested-name-specifier.
3203 DC = SemaRef.computeDeclContext(SS, false);
3204
John McCall0b66eb32010-05-01 00:40:08 +00003205 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003206 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3207 << SS.getRange() << DC;
3208 return true;
3209 }
3210
John McCall2d74de92009-12-01 22:10:20 +00003211 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003212
John McCall2d74de92009-12-01 22:10:20 +00003213 if (!isa<TypeDecl>(DC)) {
3214 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3215 << DC << SS.getRange();
3216 return true;
John McCall10eae182009-11-30 22:42:35 +00003217 }
3218 }
3219
John McCall2d74de92009-12-01 22:10:20 +00003220 // The record definition is complete, now look up the member.
3221 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003222
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003223 if (!R.empty())
3224 return false;
3225
3226 // We didn't find anything with the given name, so try to correct
3227 // for typos.
3228 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003229 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003230 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003231 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3232 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3233 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003234 << FixItHint::CreateReplacement(R.getNameLoc(),
3235 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003236 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3237 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3238 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003239 return false;
3240 } else {
3241 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003242 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003243 }
3244
John McCall10eae182009-11-30 22:42:35 +00003245 return false;
3246}
3247
John McCalldadc5752010-08-24 06:29:42 +00003248ExprResult
John McCallb268a282010-08-23 23:25:46 +00003249Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003250 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003251 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003252 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003253 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003254 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003255 if (BaseType->isDependentType() ||
3256 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003257 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003258 IsArrow, OpLoc,
3259 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003260 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003261
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003262 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003263
John McCall2d74de92009-12-01 22:10:20 +00003264 // Implicit member accesses.
3265 if (!Base) {
3266 QualType RecordTy = BaseType;
3267 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3268 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3269 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003270 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003271 return ExprError();
3272
3273 // Explicit member accesses.
3274 } else {
John McCalldadc5752010-08-24 06:29:42 +00003275 ExprResult Result =
John McCall2d74de92009-12-01 22:10:20 +00003276 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003277 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003278
3279 if (Result.isInvalid()) {
3280 Owned(Base);
3281 return ExprError();
3282 }
3283
3284 if (Result.get())
3285 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003286
3287 // LookupMemberExpr can modify Base, and thus change BaseType
3288 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003289 }
3290
John McCallb268a282010-08-23 23:25:46 +00003291 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003292 OpLoc, IsArrow, SS, FirstQualifierInScope,
3293 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003294}
3295
John McCalldadc5752010-08-24 06:29:42 +00003296ExprResult
John McCallb268a282010-08-23 23:25:46 +00003297Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003298 SourceLocation OpLoc, bool IsArrow,
3299 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003300 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003301 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003302 const TemplateArgumentListInfo *TemplateArgs,
3303 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003304 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003305 if (IsArrow) {
3306 assert(BaseType->isPointerType());
3307 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3308 }
John McCalla8ae2222010-04-06 21:38:20 +00003309 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003310
John McCallb268a282010-08-23 23:25:46 +00003311 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003312 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3313 DeclarationName MemberName = MemberNameInfo.getName();
3314 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003315
3316 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003317 return ExprError();
3318
John McCall10eae182009-11-30 22:42:35 +00003319 if (R.empty()) {
3320 // Rederive where we looked up.
3321 DeclContext *DC = (SS.isSet()
3322 ? computeDeclContext(SS, false)
3323 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003324
John McCall10eae182009-11-30 22:42:35 +00003325 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003326 << MemberName << DC
3327 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003328 return ExprError();
3329 }
3330
John McCall38836f02010-01-15 08:34:02 +00003331 // Diagnose lookups that find only declarations from a non-base
3332 // type. This is possible for either qualified lookups (which may
3333 // have been qualified with an unrelated type) or implicit member
3334 // expressions (which were found with unqualified lookup and thus
3335 // may have come from an enclosing scope). Note that it's okay for
3336 // lookup to find declarations from a non-base type as long as those
3337 // aren't the ones picked by overload resolution.
3338 if ((SS.isSet() || !BaseExpr ||
3339 (isa<CXXThisExpr>(BaseExpr) &&
3340 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003341 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003342 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003343 return ExprError();
3344
3345 // Construct an unresolved result if we in fact got an unresolved
3346 // result.
3347 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003348 // Suppress any lookup-related diagnostics; we'll do these when we
3349 // pick a member.
3350 R.suppressDiagnostics();
3351
John McCall10eae182009-11-30 22:42:35 +00003352 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003353 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003354 BaseExpr, BaseExprType,
3355 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003356 Qualifier, SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003357 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003358 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003359
3360 return Owned(MemExpr);
3361 }
3362
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003363 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003364 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003365 NamedDecl *MemberDecl = R.getFoundDecl();
3366
3367 // FIXME: diagnose the presence of template arguments now.
3368
3369 // If the decl being referenced had an error, return an error for this
3370 // sub-expr without emitting another error, in order to avoid cascading
3371 // error cases.
3372 if (MemberDecl->isInvalidDecl())
3373 return ExprError();
3374
John McCall2d74de92009-12-01 22:10:20 +00003375 // Handle the implicit-member-access case.
3376 if (!BaseExpr) {
3377 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003378 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003379 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003380
Douglas Gregorb15af892010-01-07 23:12:05 +00003381 SourceLocation Loc = R.getNameLoc();
3382 if (SS.getRange().isValid())
3383 Loc = SS.getRange().getBegin();
3384 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003385 }
3386
John McCall10eae182009-11-30 22:42:35 +00003387 bool ShouldCheckUse = true;
3388 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3389 // Don't diagnose the use of a virtual member function unless it's
3390 // explicitly qualified.
3391 if (MD->isVirtual() && !SS.isSet())
3392 ShouldCheckUse = false;
3393 }
3394
3395 // Check the use of this member.
3396 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3397 Owned(BaseExpr);
3398 return ExprError();
3399 }
3400
John McCall34376a62010-12-04 03:47:34 +00003401 // Perform a property load on the base regardless of whether we
3402 // actually need it for the declaration.
3403 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3404 ConvertPropertyForRValue(BaseExpr);
3405
John McCallfeb624a2010-11-23 20:48:44 +00003406 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3407 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3408 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003409
Francois Pichet783dd6e2010-11-21 06:08:52 +00003410 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3411 // We may have found a field within an anonymous union or struct
3412 // (C++ [class.union]).
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00003413 return BuildAnonymousStructUnionMemberReference(MemberLoc, SS, FD,
John McCall34376a62010-12-04 03:47:34 +00003414 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003415
John McCall10eae182009-11-30 22:42:35 +00003416 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3417 MarkDeclarationReferenced(MemberLoc, Var);
3418 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003419 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003420 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003421 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003422 }
3423
John McCall7decc9e2010-11-18 06:31:45 +00003424 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall10eae182009-11-30 22:42:35 +00003425 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3426 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003427 MemberFn, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003428 MemberFn->getType(),
3429 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3430 OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003431 }
John McCall7decc9e2010-11-18 06:31:45 +00003432 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003433
3434 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3435 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3436 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003437 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003438 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003439 }
3440
3441 Owned(BaseExpr);
3442
Douglas Gregor861eb802010-04-25 20:55:08 +00003443 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003444 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003445 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003446 << MemberName << BaseType << int(IsArrow);
3447 else
3448 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3449 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003450
Douglas Gregor861eb802010-04-25 20:55:08 +00003451 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3452 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003453 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003454 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003455}
3456
John McCall68fc88ec2010-12-15 16:46:44 +00003457/// Given that normal member access failed on the given expression,
3458/// and given that the expression's type involves builtin-id or
3459/// builtin-Class, decide whether substituting in the redefinition
3460/// types would be profitable. The redefinition type is whatever
3461/// this translation unit tried to typedef to id/Class; we store
3462/// it to the side and then re-use it in places like this.
3463static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3464 const ObjCObjectPointerType *opty
3465 = base->getType()->getAs<ObjCObjectPointerType>();
3466 if (!opty) return false;
3467
3468 const ObjCObjectType *ty = opty->getObjectType();
3469
3470 QualType redef;
3471 if (ty->isObjCId()) {
3472 redef = S.Context.ObjCIdRedefinitionType;
3473 } else if (ty->isObjCClass()) {
3474 redef = S.Context.ObjCClassRedefinitionType;
3475 } else {
3476 return false;
3477 }
3478
3479 // Do the substitution as long as the redefinition type isn't just a
3480 // possibly-qualified pointer to builtin-id or builtin-Class again.
3481 opty = redef->getAs<ObjCObjectPointerType>();
3482 if (opty && !opty->getObjectType()->getInterface() != 0)
3483 return false;
3484
3485 S.ImpCastExprToType(base, redef, CK_BitCast);
3486 return true;
3487}
3488
John McCall10eae182009-11-30 22:42:35 +00003489/// Look up the given member of the given non-type-dependent
3490/// expression. This can return in one of two ways:
3491/// * If it returns a sentinel null-but-valid result, the caller will
3492/// assume that lookup was performed and the results written into
3493/// the provided structure. It will take over from there.
3494/// * Otherwise, the returned expression will be produced in place of
3495/// an ordinary member expression.
3496///
3497/// The ObjCImpDecl bit is a gross hack that will need to be properly
3498/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00003499ExprResult
John McCall10eae182009-11-30 22:42:35 +00003500Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00003501 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003502 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00003503 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003504 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00003505
Steve Naroffeaaae462007-12-16 21:42:28 +00003506 // Perform default conversions.
3507 DefaultFunctionArrayConversion(BaseExpr);
John McCall15317a22010-12-15 04:42:30 +00003508 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003509
Steve Naroff185616f2007-07-26 03:11:44 +00003510 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00003511 assert(!BaseType->isDependentType());
3512
3513 DeclarationName MemberName = R.getLookupName();
3514 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00003515
John McCall68fc88ec2010-12-15 16:46:44 +00003516 // For later type-checking purposes, turn arrow accesses into dot
3517 // accesses. The only access type we support that doesn't follow
3518 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3519 // and those never use arrows, so this is unaffected.
3520 if (IsArrow) {
3521 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3522 BaseType = Ptr->getPointeeType();
3523 else if (const ObjCObjectPointerType *Ptr
3524 = BaseType->getAs<ObjCObjectPointerType>())
3525 BaseType = Ptr->getPointeeType();
3526 else if (BaseType->isRecordType()) {
3527 // Recover from arrow accesses to records, e.g.:
3528 // struct MyRecord foo;
3529 // foo->bar
3530 // This is actually well-formed in C++ if MyRecord has an
3531 // overloaded operator->, but that should have been dealt with
3532 // by now.
3533 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3534 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3535 << FixItHint::CreateReplacement(OpLoc, ".");
3536 IsArrow = false;
3537 } else {
3538 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3539 << BaseType << BaseExpr->getSourceRange();
3540 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00003541 }
3542 }
3543
John McCall68fc88ec2010-12-15 16:46:44 +00003544 // Handle field access to simple records.
3545 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3546 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3547 RTy, OpLoc, SS, HasTemplateArgs))
3548 return ExprError();
3549
3550 // Returning valid-but-null is how we indicate to the caller that
3551 // the lookup result was filled in.
3552 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00003553 }
John McCall10eae182009-11-30 22:42:35 +00003554
John McCall68fc88ec2010-12-15 16:46:44 +00003555 // Handle ivar access to Objective-C objects.
3556 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003557 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00003558
3559 // There are three cases for the base type:
3560 // - builtin id (qualified or unqualified)
3561 // - builtin Class (qualified or unqualified)
3562 // - an interface
3563 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3564 if (!IDecl) {
3565 // There's an implicit 'isa' ivar on all objects.
3566 // But we only actually find it this way on objects of type 'id',
3567 // apparently.
3568 if (OTy->isObjCId() && Member->isStr("isa"))
3569 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3570 Context.getObjCClassType()));
3571
3572 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3573 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3574 ObjCImpDecl, HasTemplateArgs);
3575 goto fail;
3576 }
3577
3578 ObjCInterfaceDecl *ClassDeclared;
3579 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3580
3581 if (!IV) {
3582 // Attempt to correct for typos in ivar names.
3583 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3584 LookupMemberName);
3585 if (CorrectTypo(Res, 0, 0, IDecl, false,
3586 IsArrow ? CTC_ObjCIvarLookup
3587 : CTC_ObjCPropertyLookup) &&
3588 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3589 Diag(R.getNameLoc(),
3590 diag::err_typecheck_member_reference_ivar_suggest)
3591 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3592 << FixItHint::CreateReplacement(R.getNameLoc(),
3593 IV->getNameAsString());
3594 Diag(IV->getLocation(), diag::note_previous_decl)
3595 << IV->getDeclName();
3596 } else {
3597 Res.clear();
3598 Res.setLookupName(Member);
3599
3600 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3601 << IDecl->getDeclName() << MemberName
3602 << BaseExpr->getSourceRange();
3603 return ExprError();
3604 }
3605 }
3606
3607 // If the decl being referenced had an error, return an error for this
3608 // sub-expr without emitting another error, in order to avoid cascading
3609 // error cases.
3610 if (IV->isInvalidDecl())
3611 return ExprError();
3612
3613 // Check whether we can reference this field.
3614 if (DiagnoseUseOfDecl(IV, MemberLoc))
3615 return ExprError();
3616 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3617 IV->getAccessControl() != ObjCIvarDecl::Package) {
3618 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3619 if (ObjCMethodDecl *MD = getCurMethodDecl())
3620 ClassOfMethodDecl = MD->getClassInterface();
3621 else if (ObjCImpDecl && getCurFunctionDecl()) {
3622 // Case of a c-function declared inside an objc implementation.
3623 // FIXME: For a c-style function nested inside an objc implementation
3624 // class, there is no implementation context available, so we pass
3625 // down the context as argument to this routine. Ideally, this context
3626 // need be passed down in the AST node and somehow calculated from the
3627 // AST for a function decl.
3628 if (ObjCImplementationDecl *IMPD =
3629 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3630 ClassOfMethodDecl = IMPD->getClassInterface();
3631 else if (ObjCCategoryImplDecl* CatImplClass =
3632 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3633 ClassOfMethodDecl = CatImplClass->getClassInterface();
3634 }
3635
3636 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3637 if (ClassDeclared != IDecl ||
3638 ClassOfMethodDecl != ClassDeclared)
3639 Diag(MemberLoc, diag::error_private_ivar_access)
3640 << IV->getDeclName();
3641 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3642 // @protected
3643 Diag(MemberLoc, diag::error_protected_ivar_access)
3644 << IV->getDeclName();
3645 }
3646
3647 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3648 MemberLoc, BaseExpr,
3649 IsArrow));
3650 }
3651
3652 // Objective-C property access.
3653 const ObjCObjectPointerType *OPT;
3654 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3655 // This actually uses the base as an r-value.
3656 DefaultLvalueConversion(BaseExpr);
3657 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3658
3659 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3660
3661 const ObjCObjectType *OT = OPT->getObjectType();
3662
3663 // id, with and without qualifiers.
3664 if (OT->isObjCId()) {
3665 // Check protocols on qualified interfaces.
3666 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3667 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3668 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3669 // Check the use of this declaration
3670 if (DiagnoseUseOfDecl(PD, MemberLoc))
3671 return ExprError();
3672
3673 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3674 VK_LValue,
3675 OK_ObjCProperty,
3676 MemberLoc,
3677 BaseExpr));
3678 }
3679
3680 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3681 // Check the use of this method.
3682 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3683 return ExprError();
3684 Selector SetterSel =
3685 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3686 PP.getSelectorTable(), Member);
3687 ObjCMethodDecl *SMD = 0;
3688 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3689 SetterSel, Context))
3690 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3691 QualType PType = OMD->getSendResultType();
3692
3693 ExprValueKind VK = VK_LValue;
3694 if (!getLangOptions().CPlusPlus &&
3695 IsCForbiddenLValueType(Context, PType))
3696 VK = VK_RValue;
3697 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3698
3699 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3700 VK, OK,
3701 MemberLoc, BaseExpr));
3702 }
3703 }
3704
3705 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3706 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3707 ObjCImpDecl, HasTemplateArgs);
3708
3709 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3710 << MemberName << BaseType);
3711 }
3712
3713 // 'Class', unqualified only.
3714 if (OT->isObjCClass()) {
3715 // Only works in a method declaration (??!).
3716 ObjCMethodDecl *MD = getCurMethodDecl();
3717 if (!MD) {
3718 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3719 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3720 ObjCImpDecl, HasTemplateArgs);
3721
3722 goto fail;
3723 }
3724
3725 // Also must look for a getter name which uses property syntax.
3726 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003727 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3728 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003729 if ((Getter = IFace->lookupClassMethod(Sel))) {
3730 // Check the use of this method.
3731 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3732 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00003733 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003734 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003735 // If we found a getter then this may be a valid dot-reference, we
3736 // will look for the matching setter, in case it is needed.
3737 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00003738 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3739 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003740 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3741 if (!Setter) {
3742 // If this reference is in an @implementation, also check for 'private'
3743 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003744 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003745 }
3746 // Look through local category implementations associated with the class.
3747 if (!Setter)
3748 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003749
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003750 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3751 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003752
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003753 if (Getter || Setter) {
3754 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003755
John McCall4bc41ae2010-11-18 19:01:18 +00003756 ExprValueKind VK = VK_LValue;
3757 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00003758 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00003759 if (!getLangOptions().CPlusPlus &&
3760 IsCForbiddenLValueType(Context, PType))
3761 VK = VK_RValue;
3762 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003763 // Get the expression type from Setter's incoming parameter.
3764 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00003765 }
3766 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3767
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003768 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00003769 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3770 PType, VK, OK,
3771 MemberLoc, BaseExpr));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003772 }
John McCall68fc88ec2010-12-15 16:46:44 +00003773
3774 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3775 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3776 ObjCImpDecl, HasTemplateArgs);
3777
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003778 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00003779 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003780 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003781
John McCall68fc88ec2010-12-15 16:46:44 +00003782 // Normal property access.
3783 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3784 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003785 }
Alexis Huntc46382e2010-04-28 23:02:27 +00003786
Chris Lattnerb63a7452008-07-21 04:28:12 +00003787 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003788 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00003789 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00003790 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall15317a22010-12-15 04:42:30 +00003791 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00003792 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3793 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00003794 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003795 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00003796
3797 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3798 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003799 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003800
John McCall68fc88ec2010-12-15 16:46:44 +00003801 // Adjust builtin-sel to the appropriate redefinition type if that's
3802 // not just a pointer to builtin-sel again.
3803 if (IsArrow &&
3804 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
3805 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
3806 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
3807 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3808 ObjCImpDecl, HasTemplateArgs);
3809 }
3810
3811 // Failure cases.
3812 fail:
3813
3814 // There's a possible road to recovery for function types.
3815 const FunctionType *Fun = 0;
3816
3817 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
3818 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
3819 // fall out, handled below.
3820
3821 // Recover from dot accesses to pointers, e.g.:
3822 // type *foo;
3823 // foo.bar
3824 // This is actually well-formed in two cases:
3825 // - 'type' is an Objective C type
3826 // - 'bar' is a pseudo-destructor name which happens to refer to
3827 // the appropriate pointer type
Argyrios Kyrtzidiscd81fe02011-01-25 23:16:36 +00003828 } else if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
John McCall68fc88ec2010-12-15 16:46:44 +00003829 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3830 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3831 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3832 << FixItHint::CreateReplacement(OpLoc, "->");
3833
3834 // Recurse as an -> access.
3835 IsArrow = true;
3836 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3837 ObjCImpDecl, HasTemplateArgs);
3838 }
3839 } else {
3840 Fun = BaseType->getAs<FunctionType>();
3841 }
3842
3843 // If the user is trying to apply -> or . to a function pointer
3844 // type, it's probably because they forgot parentheses to call that
3845 // function. Suggest the addition of those parentheses, build the
3846 // call, and continue on.
3847 if (Fun || BaseType == Context.OverloadTy) {
3848 bool TryCall;
3849 if (BaseType == Context.OverloadTy) {
3850 TryCall = true;
3851 } else {
3852 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
3853 TryCall = (FPT->getNumArgs() == 0);
3854 } else {
3855 TryCall = true;
3856 }
3857
3858 if (TryCall) {
3859 QualType ResultTy = Fun->getResultType();
3860 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
3861 (IsArrow && ResultTy->isPointerType() &&
3862 ResultTy->getAs<PointerType>()->getPointeeType()->isRecordType());
3863 }
3864 }
3865
3866
3867 if (TryCall) {
3868 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
3869 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
3870 << QualType(Fun, 0)
3871 << FixItHint::CreateInsertion(Loc, "()");
3872
3873 ExprResult NewBase
3874 = ActOnCallExpr(0, BaseExpr, Loc, MultiExprArg(*this, 0, 0), Loc);
3875 if (NewBase.isInvalid())
3876 return ExprError();
3877 BaseExpr = NewBase.takeAs<Expr>();
3878
3879
3880 DefaultFunctionArrayConversion(BaseExpr);
3881 BaseType = BaseExpr->getType();
3882
3883 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3884 ObjCImpDecl, HasTemplateArgs);
3885 }
3886 }
3887
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003888 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3889 << BaseType << BaseExpr->getSourceRange();
3890
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003891 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00003892}
3893
John McCall10eae182009-11-30 22:42:35 +00003894/// The main callback when the parser finds something like
3895/// expression . [nested-name-specifier] identifier
3896/// expression -> [nested-name-specifier] identifier
3897/// where 'identifier' encompasses a fairly broad spectrum of
3898/// possibilities, including destructor and operator references.
3899///
3900/// \param OpKind either tok::arrow or tok::period
3901/// \param HasTrailingLParen whether the next token is '(', which
3902/// is used to diagnose mis-uses of special members that can
3903/// only be called
3904/// \param ObjCImpDecl the current ObjC @implementation decl;
3905/// this is an ugly hack around the fact that ObjC @implementations
3906/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00003907ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00003908 SourceLocation OpLoc,
3909 tok::TokenKind OpKind,
3910 CXXScopeSpec &SS,
3911 UnqualifiedId &Id,
3912 Decl *ObjCImpDecl,
3913 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00003914 if (SS.isSet() && SS.isInvalid())
3915 return ExprError();
3916
Francois Pichet64225792011-01-18 05:04:39 +00003917 // Warn about the explicit constructor calls Microsoft extension.
3918 if (getLangOptions().Microsoft &&
3919 Id.getKind() == UnqualifiedId::IK_ConstructorName)
3920 Diag(Id.getSourceRange().getBegin(),
3921 diag::ext_ms_explicit_constructor_call);
3922
John McCall10eae182009-11-30 22:42:35 +00003923 TemplateArgumentListInfo TemplateArgsBuffer;
3924
3925 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003926 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00003927 const TemplateArgumentListInfo *TemplateArgs;
3928 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003929 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003930
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003931 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00003932 bool IsArrow = (OpKind == tok::arrow);
3933
3934 NamedDecl *FirstQualifierInScope
3935 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3936 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3937
3938 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003939 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003940 if (Result.isInvalid()) return ExprError();
3941 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00003942
Douglas Gregor41f90302010-04-12 20:54:26 +00003943 if (Base->getType()->isDependentType() || Name.isDependentName() ||
3944 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00003945 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00003946 IsArrow, OpLoc,
3947 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003948 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003949 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003950 LookupResult R(*this, NameInfo, LookupMemberName);
John McCalle9cccd82010-06-16 08:42:20 +00003951 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3952 SS, ObjCImpDecl, TemplateArgs != 0);
Alexis Huntc46382e2010-04-28 23:02:27 +00003953
John McCalle9cccd82010-06-16 08:42:20 +00003954 if (Result.isInvalid()) {
3955 Owned(Base);
3956 return ExprError();
3957 }
John McCall10eae182009-11-30 22:42:35 +00003958
John McCalle9cccd82010-06-16 08:42:20 +00003959 if (Result.get()) {
3960 // The only way a reference to a destructor can be used is to
3961 // immediately call it, which falls into this case. If the
3962 // next token is not a '(', produce a diagnostic and build the
3963 // call now.
3964 if (!HasTrailingLParen &&
3965 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00003966 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00003967
John McCalle9cccd82010-06-16 08:42:20 +00003968 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00003969 }
3970
John McCallb268a282010-08-23 23:25:46 +00003971 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00003972 OpLoc, IsArrow, SS, FirstQualifierInScope,
3973 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003974 }
3975
3976 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003977}
3978
John McCalldadc5752010-08-24 06:29:42 +00003979ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003980 FunctionDecl *FD,
3981 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003982 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003983 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003984 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003985 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003986 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003987 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003988 return ExprError();
3989 }
3990
3991 if (Param->hasUninstantiatedDefaultArg()) {
3992 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003993
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003994 // Instantiate the expression.
3995 MultiLevelTemplateArgumentList ArgList
3996 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003997
Nico Weber44887f62010-11-29 18:19:25 +00003998 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003999 = ArgList.getInnermost();
4000 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4001 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00004002
Nico Weber44887f62010-11-29 18:19:25 +00004003 ExprResult Result;
4004 {
4005 // C++ [dcl.fct.default]p5:
4006 // The names in the [default argument] expression are bound, and
4007 // the semantic constraints are checked, at the point where the
4008 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004009 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004010 Result = SubstExpr(UninstExpr, ArgList);
4011 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004012 if (Result.isInvalid())
4013 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004014
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004015 // Check the expression as an initializer for the parameter.
4016 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004017 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004018 InitializationKind Kind
4019 = InitializationKind::CreateCopy(Param->getLocation(),
4020 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4021 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004022
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004023 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4024 Result = InitSeq.Perform(*this, Entity, Kind,
4025 MultiExprArg(*this, &ResultE, 1));
4026 if (Result.isInvalid())
4027 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004028
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004029 // Build the default argument expression.
4030 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4031 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004032 }
4033
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004034 // If the default expression creates temporaries, we need to
4035 // push them to the current stack of expression temporaries so they'll
4036 // be properly destroyed.
4037 // FIXME: We should really be rebuilding the default argument with new
4038 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004039 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4040 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4041 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4042 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4043 ExprTemporaries.push_back(Temporary);
4044 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004045
4046 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004047 // Just mark all of the declarations in this potentially-evaluated expression
4048 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004049 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004050 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004051}
4052
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004053/// ConvertArgumentsForCall - Converts the arguments specified in
4054/// Args/NumArgs to the parameter types of the function FDecl with
4055/// function prototype Proto. Call is the call expression itself, and
4056/// Fn is the function expression. For a C++ member function, this
4057/// routine does not attempt to convert the object argument. Returns
4058/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004059bool
4060Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004061 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004062 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004063 Expr **Args, unsigned NumArgs,
4064 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004065 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004066 // assignment, to the types of the corresponding parameter, ...
4067 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004068 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004069
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004070 // If too few arguments are available (and we don't have default
4071 // arguments for the remaining parameters), don't make the call.
4072 if (NumArgs < NumArgsInProto) {
4073 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4074 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004075 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004076 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004077 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004078 }
4079
4080 // If too many are passed and not variadic, error on the extras and drop
4081 // them.
4082 if (NumArgs > NumArgsInProto) {
4083 if (!Proto->isVariadic()) {
4084 Diag(Args[NumArgsInProto]->getLocStart(),
4085 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004086 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004087 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004088 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4089 Args[NumArgs-1]->getLocEnd());
4090 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004091 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004092 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004093 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004094 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004095 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004096 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004097 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4098 if (Fn->getType()->isBlockPointerType())
4099 CallType = VariadicBlock; // Block
4100 else if (isa<MemberExpr>(Fn))
4101 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004102 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004103 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004104 if (Invalid)
4105 return true;
4106 unsigned TotalNumArgs = AllArgs.size();
4107 for (unsigned i = 0; i < TotalNumArgs; ++i)
4108 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004109
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004110 return false;
4111}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004112
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004113bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4114 FunctionDecl *FDecl,
4115 const FunctionProtoType *Proto,
4116 unsigned FirstProtoArg,
4117 Expr **Args, unsigned NumArgs,
4118 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004119 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004120 unsigned NumArgsInProto = Proto->getNumArgs();
4121 unsigned NumArgsToCheck = NumArgs;
4122 bool Invalid = false;
4123 if (NumArgs != NumArgsInProto)
4124 // Use default arguments for missing arguments
4125 NumArgsToCheck = NumArgsInProto;
4126 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004127 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004128 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004129 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004130
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004131 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004132 if (ArgIx < NumArgs) {
4133 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004134
Eli Friedman3164fb12009-03-22 22:00:50 +00004135 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4136 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004137 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004138 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004139 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004140
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004141 // Pass the argument
4142 ParmVarDecl *Param = 0;
4143 if (FDecl && i < FDecl->getNumParams())
4144 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004145
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004146 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004147 Param? InitializedEntity::InitializeParameter(Context, Param)
4148 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004149 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004150 SourceLocation(),
4151 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004152 if (ArgE.isInvalid())
4153 return true;
4154
4155 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004156 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004157 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004158
John McCalldadc5752010-08-24 06:29:42 +00004159 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004160 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004161 if (ArgExpr.isInvalid())
4162 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004163
Anders Carlsson355933d2009-08-25 03:49:14 +00004164 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004165 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004166 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004167 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004168
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004169 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004170 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004171 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004172 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004173 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004174 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004175 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004176 }
4177 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004178 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004179}
4180
Steve Naroff83895f72007-09-16 03:34:24 +00004181/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004182/// This provides the location of the left/right parens and a list of comma
4183/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004184ExprResult
John McCallb268a282010-08-23 23:25:46 +00004185Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004186 MultiExprArg args, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004187 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004188
4189 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004190 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004191 if (Result.isInvalid()) return ExprError();
4192 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004193
John McCallb268a282010-08-23 23:25:46 +00004194 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004195
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004196 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004197 // If this is a pseudo-destructor expression, build the call immediately.
4198 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4199 if (NumArgs > 0) {
4200 // Pseudo-destructor calls should not have any arguments.
4201 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004202 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004203 SourceRange(Args[0]->getLocStart(),
4204 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004205
Douglas Gregorad8a3362009-09-04 17:36:40 +00004206 NumArgs = 0;
4207 }
Mike Stump11289f42009-09-09 15:08:12 +00004208
Douglas Gregorad8a3362009-09-04 17:36:40 +00004209 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004210 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004211 }
Mike Stump11289f42009-09-09 15:08:12 +00004212
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004213 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004214 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004215 // FIXME: Will need to cache the results of name lookup (including ADL) in
4216 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004217 bool Dependent = false;
4218 if (Fn->isTypeDependent())
4219 Dependent = true;
4220 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4221 Dependent = true;
4222
4223 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004224 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00004225 Context.DependentTy, VK_RValue,
4226 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004227
4228 // Determine whether this is a call to an object (C++ [over.call.object]).
4229 if (Fn->getType()->isRecordType())
4230 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004231 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004232
John McCall10eae182009-11-30 22:42:35 +00004233 Expr *NakedFn = Fn->IgnoreParens();
4234
4235 // Determine whether this is a call to an unresolved member function.
4236 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4237 // If lookup was unresolved but not dependent (i.e. didn't find
4238 // an unresolved using declaration), it has to be an overloaded
4239 // function set, which means it must contain either multiple
4240 // declarations (all methods or method templates) or a single
4241 // method template.
4242 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00004243 isa<FunctionTemplateDecl>(
4244 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00004245 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00004246
John McCall2d74de92009-12-01 22:10:20 +00004247 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004248 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004249 }
4250
Douglas Gregore254f902009-02-04 00:32:51 +00004251 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00004252 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004253 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00004254 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00004255 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004256 RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004257 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004258
Anders Carlsson61914b52009-10-03 17:40:22 +00004259 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00004260 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCalle3027922010-08-25 11:45:40 +00004261 if (BO->getOpcode() == BO_PtrMemD ||
4262 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00004263 if (const FunctionProtoType *FPT
4264 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004265 QualType ResultTy = FPT->getCallResultType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004266 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004267
John McCallb268a282010-08-23 23:25:46 +00004268 CXXMemberCallExpr *TheCall
Abramo Bagnara21e9d862010-12-03 21:39:42 +00004269 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCall7decc9e2010-11-18 06:31:45 +00004270 NumArgs, ResultTy, VK,
John McCallb268a282010-08-23 23:25:46 +00004271 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004272
4273 if (CheckCallReturnType(FPT->getResultType(),
4274 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00004275 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004276 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00004277
John McCallb268a282010-08-23 23:25:46 +00004278 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004279 RParenLoc))
4280 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00004281
John McCallb268a282010-08-23 23:25:46 +00004282 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004283 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004284 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004285 diag::err_typecheck_call_not_function)
4286 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00004287 }
4288 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004289 }
4290
Douglas Gregore254f902009-02-04 00:32:51 +00004291 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004292 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00004293 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004294
Eli Friedmane14b1992009-12-26 03:35:45 +00004295 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004296 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4297 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4298 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4299 RParenLoc);
4300 }
4301
John McCall57500772009-12-16 12:17:52 +00004302 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004303 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4304 if (UnOp->getOpcode() == UO_AddrOf)
4305 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4306
John McCall57500772009-12-16 12:17:52 +00004307 if (isa<DeclRefExpr>(NakedFn))
4308 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4309
John McCall2d74de92009-12-01 22:10:20 +00004310 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
4311}
4312
John McCall57500772009-12-16 12:17:52 +00004313/// BuildResolvedCallExpr - Build a call to a resolved expression,
4314/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004315/// unary-convert to an expression of function-pointer or
4316/// block-pointer type.
4317///
4318/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004319ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004320Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4321 SourceLocation LParenLoc,
4322 Expr **Args, unsigned NumArgs,
4323 SourceLocation RParenLoc) {
4324 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4325
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004326 // Promote the function operand.
4327 UsualUnaryConversions(Fn);
4328
Chris Lattner08464942007-12-28 05:29:59 +00004329 // Make the call expr early, before semantic checks. This guarantees cleanup
4330 // of arguments and function on error.
John McCallb268a282010-08-23 23:25:46 +00004331 CallExpr *TheCall = new (Context) CallExpr(Context, Fn,
4332 Args, NumArgs,
4333 Context.BoolTy,
John McCall7decc9e2010-11-18 06:31:45 +00004334 VK_RValue,
John McCallb268a282010-08-23 23:25:46 +00004335 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004336
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004337 const FunctionType *FuncT;
4338 if (!Fn->getType()->isBlockPointerType()) {
4339 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4340 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004341 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004342 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004343 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4344 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00004345 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004346 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004347 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00004348 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004349 }
Chris Lattner08464942007-12-28 05:29:59 +00004350 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004351 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4352 << Fn->getType() << Fn->getSourceRange());
4353
Eli Friedman3164fb12009-03-22 22:00:50 +00004354 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004355 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00004356 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004357 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004358 return ExprError();
4359
Chris Lattner08464942007-12-28 05:29:59 +00004360 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004361 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004362 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004363
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004364 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00004365 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004366 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004367 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004368 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004369 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004370
Douglas Gregord8e97de2009-04-02 15:37:10 +00004371 if (FDecl) {
4372 // Check if we have too few/too many template arguments, based
4373 // on our knowledge of the function definition.
4374 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004375 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004376 const FunctionProtoType *Proto
4377 = Def->getType()->getAs<FunctionProtoType>();
4378 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004379 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4380 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004381 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004382
4383 // If the function we're calling isn't a function prototype, but we have
4384 // a function prototype from a prior declaratiom, use that prototype.
4385 if (!FDecl->hasPrototype())
4386 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004387 }
4388
Steve Naroff0b661582007-08-28 23:30:39 +00004389 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004390 for (unsigned i = 0; i != NumArgs; i++) {
4391 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004392
4393 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004394 InitializedEntity Entity
4395 = InitializedEntity::InitializeParameter(Context,
4396 Proto->getArgType(i));
4397 ExprResult ArgE = PerformCopyInitialization(Entity,
4398 SourceLocation(),
4399 Owned(Arg));
4400 if (ArgE.isInvalid())
4401 return true;
4402
4403 Arg = ArgE.takeAs<Expr>();
4404
4405 } else {
4406 DefaultArgumentPromotion(Arg);
Douglas Gregor8e09a722010-10-25 20:39:23 +00004407 }
4408
Douglas Gregor83025412010-10-26 05:45:40 +00004409 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4410 Arg->getType(),
4411 PDiag(diag::err_call_incomplete_argument)
4412 << Arg->getSourceRange()))
4413 return ExprError();
4414
Chris Lattner08464942007-12-28 05:29:59 +00004415 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004416 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004417 }
Chris Lattner08464942007-12-28 05:29:59 +00004418
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004419 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4420 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004421 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4422 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004423
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004424 // Check for sentinels
4425 if (NDecl)
4426 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004427
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004428 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004429 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00004430 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004431 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004432
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004433 if (unsigned BuiltinID = FDecl->getBuiltinID())
4434 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004435 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00004436 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004437 return ExprError();
4438 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004439
John McCallb268a282010-08-23 23:25:46 +00004440 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004441}
4442
John McCalldadc5752010-08-24 06:29:42 +00004443ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004444Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004445 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004446 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004447 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004448 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004449
4450 TypeSourceInfo *TInfo;
4451 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4452 if (!TInfo)
4453 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4454
John McCallb268a282010-08-23 23:25:46 +00004455 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004456}
4457
John McCalldadc5752010-08-24 06:29:42 +00004458ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004459Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00004460 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004461 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004462
Eli Friedman37a186d2008-05-20 05:22:08 +00004463 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004464 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4465 PDiag(diag::err_illegal_decl_array_incomplete_type)
4466 << SourceRange(LParenLoc,
4467 literalExpr->getSourceRange().getEnd())))
4468 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004469 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004470 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4471 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004472 } else if (!literalType->isDependentType() &&
4473 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00004474 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00004475 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00004476 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004477 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004478
Douglas Gregor85dabae2009-12-16 01:38:02 +00004479 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004480 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004481 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004482 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004483 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004484 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004485 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004486 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004487 &literalType);
4488 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004489 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004490 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004491
Chris Lattner79413952008-12-04 23:50:19 +00004492 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004493 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00004494 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004495 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004496 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004497
John McCall7decc9e2010-11-18 06:31:45 +00004498 // In C, compound literals are l-values for some reason.
4499 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4500
John McCall5d7aa7f2010-01-19 22:33:45 +00004501 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00004502 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004503}
4504
John McCalldadc5752010-08-24 06:29:42 +00004505ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00004506Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004507 SourceLocation RBraceLoc) {
4508 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00004509 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004510
Steve Naroff30d242c2007-09-15 18:49:24 +00004511 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004512 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004513
Ted Kremenekac034612010-04-13 23:39:13 +00004514 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4515 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004516 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004517 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004518}
4519
John McCalld7646252010-11-14 08:17:51 +00004520/// Prepares for a scalar cast, performing all the necessary stages
4521/// except the final cast and returning the kind required.
4522static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4523 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4524 // Also, callers should have filtered out the invalid cases with
4525 // pointers. Everything else should be possible.
4526
Abramo Bagnaraba854972011-01-04 09:50:03 +00004527 QualType SrcTy = Src->getType();
John McCalld7646252010-11-14 08:17:51 +00004528 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004529 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004530
John McCall8cb679e2010-11-15 09:13:47 +00004531 switch (SrcTy->getScalarTypeKind()) {
4532 case Type::STK_MemberPointer:
4533 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004534
John McCall8cb679e2010-11-15 09:13:47 +00004535 case Type::STK_Pointer:
4536 switch (DestTy->getScalarTypeKind()) {
4537 case Type::STK_Pointer:
4538 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00004539 CK_AnyPointerToObjCPointerCast :
4540 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00004541 case Type::STK_Bool:
4542 return CK_PointerToBoolean;
4543 case Type::STK_Integral:
4544 return CK_PointerToIntegral;
4545 case Type::STK_Floating:
4546 case Type::STK_FloatingComplex:
4547 case Type::STK_IntegralComplex:
4548 case Type::STK_MemberPointer:
4549 llvm_unreachable("illegal cast from pointer");
4550 }
4551 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004552
John McCall8cb679e2010-11-15 09:13:47 +00004553 case Type::STK_Bool: // casting from bool is like casting from an integer
4554 case Type::STK_Integral:
4555 switch (DestTy->getScalarTypeKind()) {
4556 case Type::STK_Pointer:
John McCalld7646252010-11-14 08:17:51 +00004557 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004558 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004559 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004560 case Type::STK_Bool:
4561 return CK_IntegralToBoolean;
4562 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004563 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004564 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004565 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004566 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004567 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004568 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004569 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004570 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004571 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004572 CK_IntegralToFloating);
4573 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004574 case Type::STK_MemberPointer:
4575 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004576 }
4577 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004578
John McCall8cb679e2010-11-15 09:13:47 +00004579 case Type::STK_Floating:
4580 switch (DestTy->getScalarTypeKind()) {
4581 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004582 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004583 case Type::STK_Bool:
4584 return CK_FloatingToBoolean;
4585 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004586 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004587 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004588 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004589 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004590 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004591 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004592 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004593 CK_FloatingToIntegral);
4594 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004595 case Type::STK_Pointer:
4596 llvm_unreachable("valid float->pointer cast?");
4597 case Type::STK_MemberPointer:
4598 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004599 }
4600 break;
4601
John McCall8cb679e2010-11-15 09:13:47 +00004602 case Type::STK_FloatingComplex:
4603 switch (DestTy->getScalarTypeKind()) {
4604 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004605 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004606 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004607 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004608 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004609 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004610 if (S.Context.hasSameType(ET, DestTy))
4611 return CK_FloatingComplexToReal;
4612 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4613 return CK_FloatingCast;
4614 }
John McCall8cb679e2010-11-15 09:13:47 +00004615 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004616 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004617 case Type::STK_Integral:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004618 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004619 CK_FloatingComplexToReal);
4620 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004621 case Type::STK_Pointer:
4622 llvm_unreachable("valid complex float->pointer cast?");
4623 case Type::STK_MemberPointer:
4624 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004625 }
4626 break;
4627
John McCall8cb679e2010-11-15 09:13:47 +00004628 case Type::STK_IntegralComplex:
4629 switch (DestTy->getScalarTypeKind()) {
4630 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004631 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004632 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004633 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004634 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004635 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004636 if (S.Context.hasSameType(ET, DestTy))
4637 return CK_IntegralComplexToReal;
4638 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4639 return CK_IntegralCast;
4640 }
John McCall8cb679e2010-11-15 09:13:47 +00004641 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004642 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004643 case Type::STK_Floating:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004644 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004645 CK_IntegralComplexToReal);
4646 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004647 case Type::STK_Pointer:
4648 llvm_unreachable("valid complex int->pointer cast?");
4649 case Type::STK_MemberPointer:
4650 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004651 }
4652 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004653 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004654
John McCalld7646252010-11-14 08:17:51 +00004655 llvm_unreachable("Unhandled scalar cast");
4656 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00004657}
4658
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004659/// CheckCastTypes - Check type constraints for casting between types.
John McCall7decc9e2010-11-18 06:31:45 +00004660bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4661 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4662 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00004663 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00004664 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4665 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00004666 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00004667 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00004668
John McCall7decc9e2010-11-18 06:31:45 +00004669 // We only support r-value casts in C.
4670 VK = VK_RValue;
4671
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004672 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4673 // type needs to be scalar.
4674 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004675 // We don't necessarily do lvalue-to-rvalue conversions on this.
4676 IgnoredValueConversions(castExpr);
4677
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004678 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004679 Kind = CK_ToVoid;
Anders Carlssonef918ac2009-10-16 02:35:04 +00004680 return false;
4681 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004682
John McCall34376a62010-12-04 03:47:34 +00004683 DefaultFunctionArrayLvalueConversion(castExpr);
4684
Eli Friedmane98194d2010-07-17 20:43:49 +00004685 if (RequireCompleteType(TyR.getBegin(), castType,
4686 diag::err_typecheck_cast_to_incomplete))
4687 return true;
4688
Anders Carlssonef918ac2009-10-16 02:35:04 +00004689 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004690 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004691 (castType->isStructureType() || castType->isUnionType())) {
4692 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004693 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004694 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4695 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004696 Kind = CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00004697 return false;
4698 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004699
Anders Carlsson525b76b2009-10-16 02:48:28 +00004700 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004701 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004702 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004703 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004704 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004705 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004706 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004707 castExpr->getType()) &&
4708 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004709 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4710 << castExpr->getSourceRange();
4711 break;
4712 }
4713 }
4714 if (Field == FieldEnd)
4715 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4716 << castExpr->getType() << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004717 Kind = CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00004718 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004719 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004720
Anders Carlsson525b76b2009-10-16 02:48:28 +00004721 // Reject any other conversions to non-scalar types.
4722 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
4723 << castType << castExpr->getSourceRange();
4724 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004725
John McCalld7646252010-11-14 08:17:51 +00004726 // The type we're casting to is known to be a scalar or vector.
4727
4728 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004729 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00004730 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004731 return Diag(castExpr->getLocStart(),
4732 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004733 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004734 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004735
4736 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00004737 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004738
Anders Carlsson525b76b2009-10-16 02:48:28 +00004739 if (castType->isVectorType())
4740 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
4741 if (castExpr->getType()->isVectorType())
4742 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
4743
John McCalld7646252010-11-14 08:17:51 +00004744 // The source and target types are both scalars, i.e.
4745 // - arithmetic types (fundamental, enum, and complex)
4746 // - all kinds of pointers
4747 // Note that member pointers were filtered out with C++, above.
4748
Anders Carlsson43d70f82009-10-16 05:23:41 +00004749 if (isa<ObjCSelectorExpr>(castExpr))
4750 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004751
John McCalld7646252010-11-14 08:17:51 +00004752 // If either type is a pointer, the other type has to be either an
4753 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00004754 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004755 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00004756 if (!castExprType->isIntegralType(Context) &&
Douglas Gregorb90df602010-06-16 00:17:44 +00004757 castExprType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004758 return Diag(castExpr->getLocStart(),
4759 diag::err_cast_pointer_from_non_pointer_int)
4760 << castExprType << castExpr->getSourceRange();
4761 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004762 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004763 return Diag(castExpr->getLocStart(),
4764 diag::err_cast_pointer_to_non_pointer_int)
4765 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004766 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004767
John McCalld7646252010-11-14 08:17:51 +00004768 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCall2b5c1b22010-08-12 21:44:57 +00004769
John McCalld7646252010-11-14 08:17:51 +00004770 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004771 CheckCastAlign(castExpr, castType, TyR);
4772
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004773 return false;
4774}
4775
Anders Carlsson525b76b2009-10-16 02:48:28 +00004776bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004777 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004778 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004779
Anders Carlssonde71adf2007-11-27 05:51:55 +00004780 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004781 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004782 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004783 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004784 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004785 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004786 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004787 } else
4788 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004789 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004790 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004791
John McCalle3027922010-08-25 11:45:40 +00004792 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004793 return false;
4794}
4795
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004796bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCalle3027922010-08-25 11:45:40 +00004797 CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004798 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004799
Anders Carlsson43d70f82009-10-16 05:23:41 +00004800 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004801
Nate Begemanc8961a42009-06-27 22:05:55 +00004802 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4803 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004804 if (SrcTy->isVectorType()) {
4805 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
4806 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4807 << DestTy << SrcTy << R;
John McCalle3027922010-08-25 11:45:40 +00004808 Kind = CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00004809 return false;
4810 }
4811
Nate Begemanbd956c42009-06-28 02:36:38 +00004812 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004813 // conversion will take place first from scalar to elt type, and then
4814 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004815 if (SrcTy->isPointerType())
4816 return Diag(R.getBegin(),
4817 diag::err_invalid_conversion_between_vector_and_scalar)
4818 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004819
4820 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4821 ImpCastExprToType(CastExpr, DestElemTy,
John McCalld7646252010-11-14 08:17:51 +00004822 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004823
John McCalle3027922010-08-25 11:45:40 +00004824 Kind = CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00004825 return false;
4826}
4827
John McCalldadc5752010-08-24 06:29:42 +00004828ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004829Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004830 SourceLocation RParenLoc, Expr *castExpr) {
4831 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004832 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004833
John McCall97513962010-01-15 18:39:57 +00004834 TypeSourceInfo *castTInfo;
4835 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4836 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00004837 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00004838
Nate Begeman5ec4b312009-08-10 23:49:36 +00004839 // If the Expr being casted is a ParenListExpr, handle it specially.
4840 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00004841 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00004842 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00004843
John McCallb268a282010-08-23 23:25:46 +00004844 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004845}
4846
John McCalldadc5752010-08-24 06:29:42 +00004847ExprResult
John McCallebe54742010-01-15 18:56:44 +00004848Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004849 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004850 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004851 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004852 CXXCastPath BasePath;
John McCallebe54742010-01-15 18:56:44 +00004853 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCall7decc9e2010-11-18 06:31:45 +00004854 Kind, VK, BasePath))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004855 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00004856
John McCallcf142162010-08-07 06:22:56 +00004857 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +00004858 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00004859 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00004860 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004861}
4862
Nate Begeman5ec4b312009-08-10 23:49:36 +00004863/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4864/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004865ExprResult
John McCallb268a282010-08-23 23:25:46 +00004866Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004867 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4868 if (!E)
4869 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004870
John McCalldadc5752010-08-24 06:29:42 +00004871 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004872
Nate Begeman5ec4b312009-08-10 23:49:36 +00004873 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004874 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4875 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004876
John McCallb268a282010-08-23 23:25:46 +00004877 if (Result.isInvalid()) return ExprError();
4878
4879 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004880}
4881
John McCalldadc5752010-08-24 06:29:42 +00004882ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00004883Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00004884 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00004885 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00004886 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00004887 QualType Ty = TInfo->getType();
John Thompson781ad172010-06-30 22:55:51 +00004888 bool isAltiVecLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00004889
John Thompson781ad172010-06-30 22:55:51 +00004890 // Check for an altivec literal,
4891 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004892 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4893 if (PE->getNumExprs() == 0) {
4894 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4895 return ExprError();
4896 }
John Thompson781ad172010-06-30 22:55:51 +00004897 if (PE->getNumExprs() == 1) {
4898 if (!PE->getExpr(0)->getType()->isVectorType())
4899 isAltiVecLiteral = true;
4900 }
4901 else
4902 isAltiVecLiteral = true;
4903 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004904
John Thompson781ad172010-06-30 22:55:51 +00004905 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
4906 // then handle it as such.
4907 if (isAltiVecLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004908 llvm::SmallVector<Expr *, 8> initExprs;
4909 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4910 initExprs.push_back(PE->getExpr(i));
4911
4912 // FIXME: This means that pretty-printing the final AST will produce curly
4913 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00004914 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4915 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00004916 initExprs.size(), RParenLoc);
4917 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00004918 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004919 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004920 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00004921 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00004922 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00004923 if (Result.isInvalid()) return ExprError();
4924 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004925 }
4926}
4927
John McCalldadc5752010-08-24 06:29:42 +00004928ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004929 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004930 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00004931 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004932 unsigned nexprs = Val.size();
4933 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004934 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4935 Expr *expr;
4936 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4937 expr = new (Context) ParenExpr(L, R, exprs[0]);
4938 else
4939 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004940 return Owned(expr);
4941}
4942
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004943/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4944/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004945/// C99 6.5.15
4946QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall7decc9e2010-11-18 06:31:45 +00004947 Expr *&SAVE, ExprValueKind &VK,
John McCall4bc41ae2010-11-18 19:01:18 +00004948 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004949 SourceLocation QuestionLoc) {
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004950 // If both LHS and RHS are overloaded functions, try to resolve them.
4951 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
4952 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
4953 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
4954 if (LHSResult.isInvalid())
4955 return QualType();
4956
4957 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
4958 if (RHSResult.isInvalid())
4959 return QualType();
4960
4961 LHS = LHSResult.take();
4962 RHS = RHSResult.take();
4963 }
4964
Sebastian Redl1a99f442009-04-16 17:51:27 +00004965 // C++ is sufficiently different to merit its own checker.
4966 if (getLangOptions().CPlusPlus)
John McCall4bc41ae2010-11-18 19:01:18 +00004967 return CXXCheckConditionalOperands(Cond, LHS, RHS, SAVE,
4968 VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004969
4970 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004971 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004972
Chris Lattner432cff52009-02-18 04:28:32 +00004973 UsualUnaryConversions(Cond);
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00004974 if (SAVE) {
4975 SAVE = LHS = Cond;
4976 }
4977 else
4978 UsualUnaryConversions(LHS);
Chris Lattner432cff52009-02-18 04:28:32 +00004979 UsualUnaryConversions(RHS);
4980 QualType CondTy = Cond->getType();
4981 QualType LHSTy = LHS->getType();
4982 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004983
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004984 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004985 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00004986 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4987 // Throw an error if its not either.
4988 if (getLangOptions().OpenCL) {
4989 if (!CondTy->isVectorType()) {
4990 Diag(Cond->getLocStart(),
4991 diag::err_typecheck_cond_expect_scalar_or_vector)
4992 << CondTy;
4993 return QualType();
4994 }
4995 }
4996 else {
4997 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4998 << CondTy;
4999 return QualType();
5000 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005001 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005002
Chris Lattnere2949f42008-01-06 22:42:25 +00005003 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005004 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5005 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00005006
Nate Begemanabb5a732010-09-20 22:41:17 +00005007 // OpenCL: If the condition is a vector, and both operands are scalar,
5008 // attempt to implicity convert them to the vector type to act like the
5009 // built in select.
5010 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5011 // Both operands should be of scalar type.
5012 if (!LHSTy->isScalarType()) {
5013 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5014 << CondTy;
5015 return QualType();
5016 }
5017 if (!RHSTy->isScalarType()) {
5018 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5019 << CondTy;
5020 return QualType();
5021 }
5022 // Implicity convert these scalars to the type of the condition.
5023 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5024 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5025 }
5026
Chris Lattnere2949f42008-01-06 22:42:25 +00005027 // If both operands have arithmetic type, do the usual arithmetic conversions
5028 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005029 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5030 UsualArithmeticConversions(LHS, RHS);
5031 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005032 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005033
Chris Lattnere2949f42008-01-06 22:42:25 +00005034 // If both operands are the same structure or union type, the result is that
5035 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005036 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5037 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005038 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005039 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005040 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005041 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005042 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005043 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005044
Chris Lattnere2949f42008-01-06 22:42:25 +00005045 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005046 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005047 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5048 if (!LHSTy->isVoidType())
5049 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5050 << RHS->getSourceRange();
5051 if (!RHSTy->isVoidType())
5052 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5053 << LHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005054 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5055 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005056 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005057 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005058 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5059 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005060 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005061 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005062 // promote the null to a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005063 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005064 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005065 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005066 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005067 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00005068 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005069 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005070 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005071
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005072 // All objective-c pointer type analysis is done here.
5073 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5074 QuestionLoc);
5075 if (!compositeType.isNull())
5076 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005077
5078
Steve Naroff05efa972009-07-01 14:36:47 +00005079 // Handle block pointer types.
5080 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5081 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5082 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5083 QualType destType = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005084 ImpCastExprToType(LHS, destType, CK_BitCast);
5085 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005086 return destType;
5087 }
5088 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005089 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005090 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005091 }
Steve Naroff05efa972009-07-01 14:36:47 +00005092 // We have 2 block pointer types.
5093 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5094 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005095 return LHSTy;
5096 }
Steve Naroff05efa972009-07-01 14:36:47 +00005097 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005098 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5099 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005100
Steve Naroff05efa972009-07-01 14:36:47 +00005101 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5102 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005103 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005104 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005105 // In this situation, we assume void* type. No especially good
5106 // reason, but this is what gcc does, and we do have to pick
5107 // to get a consistent AST.
5108 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005109 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5110 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005111 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005112 }
Steve Naroff05efa972009-07-01 14:36:47 +00005113 // The block pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005114 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5115 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005116 return LHSTy;
5117 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005118
Steve Naroff05efa972009-07-01 14:36:47 +00005119 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5120 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5121 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005122 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5123 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005124
5125 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5126 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5127 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005128 QualType destPointee
5129 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005130 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005131 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005132 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005133 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005134 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005135 return destType;
5136 }
5137 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005138 QualType destPointee
5139 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005140 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005141 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005142 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005143 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005144 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005145 return destType;
5146 }
5147
5148 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5149 // Two identical pointer types are always compatible.
5150 return LHSTy;
5151 }
5152 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5153 rhptee.getUnqualifiedType())) {
5154 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5155 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5156 // In this situation, we assume void* type. No especially good
5157 // reason, but this is what gcc does, and we do have to pick
5158 // to get a consistent AST.
5159 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005160 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5161 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005162 return incompatTy;
5163 }
5164 // The pointer types are compatible.
5165 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5166 // differently qualified versions of compatible types, the result type is
5167 // a pointer to an appropriately qualified version of the *composite*
5168 // type.
5169 // FIXME: Need to calculate the composite type.
5170 // FIXME: Need to add qualifiers
John McCalle3027922010-08-25 11:45:40 +00005171 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5172 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005173 return LHSTy;
5174 }
Mike Stump11289f42009-09-09 15:08:12 +00005175
John McCalle84af4e2010-11-13 01:35:44 +00005176 // GCC compatibility: soften pointer/integer mismatch. Note that
5177 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005178 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5179 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5180 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005181 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005182 return RHSTy;
5183 }
5184 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5185 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5186 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005187 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005188 return LHSTy;
5189 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005190
Chris Lattnere2949f42008-01-06 22:42:25 +00005191 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005192 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5193 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005194 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005195}
5196
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005197/// FindCompositeObjCPointerType - Helper method to find composite type of
5198/// two objective-c pointer types of the two input expressions.
5199QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5200 SourceLocation QuestionLoc) {
5201 QualType LHSTy = LHS->getType();
5202 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005203
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005204 // Handle things like Class and struct objc_class*. Here we case the result
5205 // to the pseudo-builtin, because that will be implicitly cast back to the
5206 // redefinition type if an attempt is made to access its fields.
5207 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005208 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005209 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005210 return LHSTy;
5211 }
5212 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005213 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005214 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005215 return RHSTy;
5216 }
5217 // And the same for struct objc_object* / id
5218 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005219 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005220 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005221 return LHSTy;
5222 }
5223 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005224 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005225 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005226 return RHSTy;
5227 }
5228 // And the same for struct objc_selector* / SEL
5229 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005230 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005231 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005232 return LHSTy;
5233 }
5234 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005235 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005236 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005237 return RHSTy;
5238 }
5239 // Check constraints for Objective-C object pointers types.
5240 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005241
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005242 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5243 // Two identical object pointer types are always compatible.
5244 return LHSTy;
5245 }
5246 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5247 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5248 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005249
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005250 // If both operands are interfaces and either operand can be
5251 // assigned to the other, use that type as the composite
5252 // type. This allows
5253 // xxx ? (A*) a : (B*) b
5254 // where B is a subclass of A.
5255 //
5256 // Additionally, as for assignment, if either type is 'id'
5257 // allow silent coercion. Finally, if the types are
5258 // incompatible then make sure to use 'id' as the composite
5259 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005260
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005261 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5262 // It could return the composite type.
5263 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5264 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5265 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5266 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5267 } else if ((LHSTy->isObjCQualifiedIdType() ||
5268 RHSTy->isObjCQualifiedIdType()) &&
5269 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5270 // Need to handle "id<xx>" explicitly.
5271 // GCC allows qualified id and any Objective-C type to devolve to
5272 // id. Currently localizing to here until clear this should be
5273 // part of ObjCQualifiedIdTypesAreCompatible.
5274 compositeType = Context.getObjCIdType();
5275 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5276 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005277 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005278 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5279 ;
5280 else {
5281 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5282 << LHSTy << RHSTy
5283 << LHS->getSourceRange() << RHS->getSourceRange();
5284 QualType incompatTy = Context.getObjCIdType();
John McCalle3027922010-08-25 11:45:40 +00005285 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5286 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005287 return incompatTy;
5288 }
5289 // The object pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005290 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5291 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005292 return compositeType;
5293 }
5294 // Check Objective-C object pointer types and 'void *'
5295 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5296 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5297 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5298 QualType destPointee
5299 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5300 QualType destType = Context.getPointerType(destPointee);
5301 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005302 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005303 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005304 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005305 return destType;
5306 }
5307 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5308 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5309 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5310 QualType destPointee
5311 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5312 QualType destType = Context.getPointerType(destPointee);
5313 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005314 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005315 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005316 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005317 return destType;
5318 }
5319 return QualType();
5320}
5321
Steve Naroff83895f72007-09-16 03:34:24 +00005322/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005323/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005324ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005325 SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +00005326 Expr *CondExpr, Expr *LHSExpr,
5327 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005328 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5329 // was the condition.
5330 bool isLHSNull = LHSExpr == 0;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005331 Expr *SAVEExpr = 0;
5332 if (isLHSNull) {
5333 LHSExpr = SAVEExpr = CondExpr;
5334 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005335
John McCall7decc9e2010-11-18 06:31:45 +00005336 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005337 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00005338 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCall4bc41ae2010-11-18 19:01:18 +00005339 SAVEExpr, VK, OK, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00005340 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005341 return ExprError();
5342
Douglas Gregor7e112b02009-08-26 14:37:04 +00005343 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005344 LHSExpr, ColonLoc,
5345 RHSExpr, SAVEExpr,
John McCall4bc41ae2010-11-18 19:01:18 +00005346 result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005347}
5348
John McCallaba90822011-01-31 23:13:11 +00005349// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005350// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005351// routine is it effectively iqnores the qualifiers on the top level pointee.
5352// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5353// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005354static Sema::AssignConvertType
5355checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5356 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5357 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005358
Steve Naroff1f4d7272007-05-11 04:00:31 +00005359 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005360 const Type *lhptee, *rhptee;
5361 Qualifiers lhq, rhq;
5362 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5363 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005364
John McCallaba90822011-01-31 23:13:11 +00005365 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005366
5367 // C99 6.5.16.1p1: This following citation is common to constraints
5368 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5369 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005370 Qualifiers lq;
5371
5372 if (!lhq.compatiblyIncludes(rhq)) {
5373 // Treat address-space mismatches as fatal. TODO: address subspaces
5374 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5375 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5376
5377 // For GCC compatibility, other qualifier mismatches are treated
5378 // as still compatible in C.
5379 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5380 }
Steve Naroff3f597292007-05-11 22:18:03 +00005381
Mike Stump4e1f26a2009-02-19 03:04:26 +00005382 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5383 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005384 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005385 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005386 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005387 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005388
Chris Lattner0a788432008-01-03 22:56:36 +00005389 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005390 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005391 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005392 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005393
Chris Lattner0a788432008-01-03 22:56:36 +00005394 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005395 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005396 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005397
5398 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005399 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005400 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005401 }
John McCall4fff8f62011-02-01 00:10:29 +00005402
Mike Stump4e1f26a2009-02-19 03:04:26 +00005403 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005404 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005405 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5406 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005407 // Check if the pointee types are compatible ignoring the sign.
5408 // We explicitly check for char so that we catch "char" vs
5409 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005410 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005411 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005412 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005413 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005414
Chris Lattnerec3a1562009-10-17 20:33:28 +00005415 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005416 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005417 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005418 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005419
John McCall4fff8f62011-02-01 00:10:29 +00005420 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005421 // Types are compatible ignoring the sign. Qualifier incompatibility
5422 // takes priority over sign incompatibility because the sign
5423 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005424 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005425 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005426
John McCallaba90822011-01-31 23:13:11 +00005427 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005428 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005429
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005430 // If we are a multi-level pointer, it's possible that our issue is simply
5431 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5432 // the eventual target type is the same and the pointers have the same
5433 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005434 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005435 do {
John McCall4fff8f62011-02-01 00:10:29 +00005436 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5437 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005438 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005439
John McCall4fff8f62011-02-01 00:10:29 +00005440 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005441 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005442 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005443
Eli Friedman80160bd2009-03-22 23:59:44 +00005444 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005445 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005446 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005447 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005448}
5449
John McCallaba90822011-01-31 23:13:11 +00005450/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005451/// block pointer types are compatible or whether a block and normal pointer
5452/// are compatible. It is more restrict than comparing two function pointer
5453// types.
John McCallaba90822011-01-31 23:13:11 +00005454static Sema::AssignConvertType
5455checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5456 QualType rhsType) {
5457 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5458 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5459
Steve Naroff081c7422008-09-04 15:10:53 +00005460 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005461
Steve Naroff081c7422008-09-04 15:10:53 +00005462 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005463 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5464 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005465
John McCallaba90822011-01-31 23:13:11 +00005466 // In C++, the types have to match exactly.
5467 if (S.getLangOptions().CPlusPlus)
5468 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005469
John McCallaba90822011-01-31 23:13:11 +00005470 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005471
Steve Naroff081c7422008-09-04 15:10:53 +00005472 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005473 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5474 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005475
John McCallaba90822011-01-31 23:13:11 +00005476 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5477 return Sema::IncompatibleBlockPointer;
5478
Steve Naroff081c7422008-09-04 15:10:53 +00005479 return ConvTy;
5480}
5481
John McCallaba90822011-01-31 23:13:11 +00005482/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005483/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005484static Sema::AssignConvertType
5485checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5486 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5487 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5488
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005489 if (lhsType->isObjCBuiltinType()) {
5490 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005491 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5492 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005493 return Sema::IncompatiblePointer;
5494 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005495 }
5496 if (rhsType->isObjCBuiltinType()) {
5497 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005498 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5499 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005500 return Sema::IncompatiblePointer;
5501 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005502 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005503 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005504 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005505 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005506 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005507
John McCallaba90822011-01-31 23:13:11 +00005508 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5509 return Sema::CompatiblePointerDiscardsQualifiers;
5510
5511 if (S.Context.typesAreCompatible(lhsType, rhsType))
5512 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005513 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005514 return Sema::IncompatibleObjCQualifiedId;
5515 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005516}
5517
John McCall29600e12010-11-16 02:32:08 +00005518Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005519Sema::CheckAssignmentConstraints(SourceLocation Loc,
5520 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005521 // Fake up an opaque expression. We don't actually care about what
5522 // cast operations are required, so if CheckAssignmentConstraints
5523 // adds casts to this they'll be wasted, but fortunately that doesn't
5524 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00005525 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John McCall29600e12010-11-16 02:32:08 +00005526 Expr *rhsPtr = &rhs;
5527 CastKind K = CK_Invalid;
5528
5529 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5530}
5531
Mike Stump4e1f26a2009-02-19 03:04:26 +00005532/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5533/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005534/// pointers. Here are some objectionable examples that GCC considers warnings:
5535///
5536/// int a, *pint;
5537/// short *pshort;
5538/// struct foo *pfoo;
5539///
5540/// pint = pshort; // warning: assignment from incompatible pointer type
5541/// a = pint; // warning: assignment makes integer from pointer without a cast
5542/// pint = a; // warning: assignment makes pointer from integer without a cast
5543/// pint = pfoo; // warning: assignment from incompatible pointer type
5544///
5545/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005546/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005547///
John McCall8cb679e2010-11-15 09:13:47 +00005548/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005549Sema::AssignConvertType
John McCall29600e12010-11-16 02:32:08 +00005550Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005551 CastKind &Kind) {
John McCall29600e12010-11-16 02:32:08 +00005552 QualType rhsType = rhs->getType();
5553
Chris Lattnera52c2f22008-01-04 23:18:45 +00005554 // Get canonical types. We're not formatting these types, just comparing
5555 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005556 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5557 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005558
John McCalle5255932011-01-31 22:28:28 +00005559 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00005560 if (lhsType == rhsType) {
5561 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005562 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005563 }
5564
Douglas Gregor6b754842008-10-28 00:22:11 +00005565 // If the left-hand side is a reference type, then we are in a
5566 // (rare!) case where we've allowed the use of references in C,
5567 // e.g., as a parameter type in a built-in function. In this case,
5568 // just make sure that the type referenced is compatible with the
5569 // right-hand side type. The caller is responsible for adjusting
5570 // lhsType so that the resulting expression does not have reference
5571 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005572 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005573 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5574 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005575 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005576 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005577 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005578 }
John McCalle5255932011-01-31 22:28:28 +00005579
Nate Begemanbd956c42009-06-28 02:36:38 +00005580 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5581 // to the same ExtVector type.
5582 if (lhsType->isExtVectorType()) {
5583 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005584 return Incompatible;
5585 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005586 // CK_VectorSplat does T -> vector T, so first cast to the
5587 // element type.
5588 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5589 if (elType != rhsType) {
5590 Kind = PrepareScalarCast(*this, rhs, elType);
5591 ImpCastExprToType(rhs, elType, Kind);
5592 }
5593 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005594 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005595 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005596 }
Mike Stump11289f42009-09-09 15:08:12 +00005597
John McCalle5255932011-01-31 22:28:28 +00005598 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00005599 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005600 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005601 // Allow assignments of an AltiVec vector type to an equivalent GCC
5602 // vector type and vice versa
5603 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5604 Kind = CK_BitCast;
5605 return Compatible;
5606 }
5607
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005608 // If we are allowing lax vector conversions, and LHS and RHS are both
5609 // vectors, the total size only needs to be the same. This is a bitcast;
5610 // no bits are changed but the result type is different.
5611 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005612 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005613 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005614 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005615 }
Chris Lattner881a2122008-01-04 23:32:24 +00005616 }
5617 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005618 }
Eli Friedman3360d892008-05-30 18:07:22 +00005619
John McCalle5255932011-01-31 22:28:28 +00005620 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00005621 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005622 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005623 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005624 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005625 }
Eli Friedman3360d892008-05-30 18:07:22 +00005626
John McCalle5255932011-01-31 22:28:28 +00005627 // Conversions to normal pointers.
5628 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5629 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00005630 if (isa<PointerType>(rhsType)) {
5631 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00005632 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005633 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005634
John McCalle5255932011-01-31 22:28:28 +00005635 // int -> T*
5636 if (rhsType->isIntegerType()) {
5637 Kind = CK_IntegralToPointer; // FIXME: null?
5638 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005639 }
John McCalle5255932011-01-31 22:28:28 +00005640
5641 // C pointers are not compatible with ObjC object pointers,
5642 // with two exceptions:
5643 if (isa<ObjCObjectPointerType>(rhsType)) {
5644 // - conversions to void*
5645 if (lhsPointer->getPointeeType()->isVoidType()) {
5646 Kind = CK_AnyPointerToObjCPointerCast;
5647 return Compatible;
5648 }
5649
5650 // - conversions from 'Class' to the redefinition type
5651 if (rhsType->isObjCClassType() &&
5652 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005653 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005654 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005655 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005656
John McCalle5255932011-01-31 22:28:28 +00005657 Kind = CK_BitCast;
5658 return IncompatiblePointer;
5659 }
5660
5661 // U^ -> void*
5662 if (rhsType->getAs<BlockPointerType>()) {
5663 if (lhsPointer->getPointeeType()->isVoidType()) {
5664 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005665 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005666 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005667 }
John McCalle5255932011-01-31 22:28:28 +00005668
Steve Naroff081c7422008-09-04 15:10:53 +00005669 return Incompatible;
5670 }
5671
John McCalle5255932011-01-31 22:28:28 +00005672 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00005673 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005674 // U^ -> T^
5675 if (rhsType->isBlockPointerType()) {
5676 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00005677 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00005678 }
5679
5680 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005681 if (rhsType->isIntegerType()) {
5682 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005683 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005684 }
5685
John McCalle5255932011-01-31 22:28:28 +00005686 // id -> T^
5687 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5688 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005689 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005690 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005691
John McCalle5255932011-01-31 22:28:28 +00005692 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005693 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005694 if (RHSPT->getPointeeType()->isVoidType()) {
5695 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005696 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005697 }
John McCall8cb679e2010-11-15 09:13:47 +00005698
Chris Lattnera52c2f22008-01-04 23:18:45 +00005699 return Incompatible;
5700 }
5701
John McCalle5255932011-01-31 22:28:28 +00005702 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005703 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005704 // A* -> B*
5705 if (rhsType->isObjCObjectPointerType()) {
5706 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00005707 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00005708 }
5709
5710 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00005711 if (rhsType->isIntegerType()) {
5712 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005713 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005714 }
5715
John McCalle5255932011-01-31 22:28:28 +00005716 // In general, C pointers are not compatible with ObjC object pointers,
5717 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00005718 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005719 // - conversions from 'void*'
5720 if (rhsType->isVoidPointerType()) {
5721 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005722 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005723 }
5724
5725 // - conversions to 'Class' from its redefinition type
5726 if (lhsType->isObjCClassType() &&
5727 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
5728 Kind = CK_BitCast;
5729 return Compatible;
5730 }
5731
5732 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005733 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005734 }
John McCalle5255932011-01-31 22:28:28 +00005735
5736 // T^ -> A*
5737 if (rhsType->isBlockPointerType()) {
5738 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005739 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005740 }
5741
Steve Naroff7cae42b2009-07-10 23:34:53 +00005742 return Incompatible;
5743 }
John McCalle5255932011-01-31 22:28:28 +00005744
5745 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00005746 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005747 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005748 if (lhsType == Context.BoolTy) {
5749 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005750 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005751 }
Eli Friedman3360d892008-05-30 18:07:22 +00005752
John McCalle5255932011-01-31 22:28:28 +00005753 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005754 if (lhsType->isIntegerType()) {
5755 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005756 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005757 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005758
Chris Lattnera52c2f22008-01-04 23:18:45 +00005759 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005760 }
John McCalle5255932011-01-31 22:28:28 +00005761
5762 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005763 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005764 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005765 if (lhsType == Context.BoolTy) {
5766 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005767 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005768 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005769
John McCalle5255932011-01-31 22:28:28 +00005770 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005771 if (lhsType->isIntegerType()) {
5772 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005773 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005774 }
5775
Steve Naroff7cae42b2009-07-10 23:34:53 +00005776 return Incompatible;
5777 }
Eli Friedman3360d892008-05-30 18:07:22 +00005778
John McCalle5255932011-01-31 22:28:28 +00005779 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00005780 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005781 if (Context.typesAreCompatible(lhsType, rhsType)) {
5782 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005783 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005784 }
Bill Wendling216423b2007-05-30 06:30:29 +00005785 }
John McCalle5255932011-01-31 22:28:28 +00005786
Steve Naroff98cf3e92007-06-06 18:38:38 +00005787 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005788}
5789
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005790/// \brief Constructs a transparent union from an expression that is
5791/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00005792static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005793 QualType UnionType, FieldDecl *Field) {
5794 // Build an initializer list that designates the appropriate member
5795 // of the transparent union.
Ted Kremenekac034612010-04-13 23:39:13 +00005796 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005797 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005798 SourceLocation());
5799 Initializer->setType(UnionType);
5800 Initializer->setInitializedFieldInUnion(Field);
5801
5802 // Build a compound literal constructing a value of the transparent
5803 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005804 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00005805 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall7decc9e2010-11-18 06:31:45 +00005806 VK_RValue, Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005807}
5808
5809Sema::AssignConvertType
5810Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
5811 QualType FromType = rExpr->getType();
5812
Mike Stump11289f42009-09-09 15:08:12 +00005813 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005814 // transparent_union GCC extension.
5815 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005816 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005817 return Incompatible;
5818
5819 // The field to initialize within the transparent union.
5820 RecordDecl *UD = UT->getDecl();
5821 FieldDecl *InitField = 0;
5822 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005823 for (RecordDecl::field_iterator it = UD->field_begin(),
5824 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005825 it != itend; ++it) {
5826 if (it->getType()->isPointerType()) {
5827 // If the transparent union contains a pointer type, we allow:
5828 // 1) void pointer
5829 // 2) null pointer constant
5830 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005831 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +00005832 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005833 InitField = *it;
5834 break;
5835 }
Mike Stump11289f42009-09-09 15:08:12 +00005836
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005837 if (rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005838 Expr::NPC_ValueDependentIsNull)) {
John McCalle84af4e2010-11-13 01:35:44 +00005839 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005840 InitField = *it;
5841 break;
5842 }
5843 }
5844
John McCall29600e12010-11-16 02:32:08 +00005845 Expr *rhs = rExpr;
John McCall8cb679e2010-11-15 09:13:47 +00005846 CastKind Kind = CK_Invalid;
John McCall29600e12010-11-16 02:32:08 +00005847 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005848 == Compatible) {
John McCall29600e12010-11-16 02:32:08 +00005849 ImpCastExprToType(rhs, it->getType(), Kind);
5850 rExpr = rhs;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005851 InitField = *it;
5852 break;
5853 }
5854 }
5855
5856 if (!InitField)
5857 return Incompatible;
5858
5859 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
5860 return Compatible;
5861}
5862
Chris Lattner9bad62c2008-01-04 18:04:52 +00005863Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005864Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005865 if (getLangOptions().CPlusPlus) {
5866 if (!lhsType->isRecordType()) {
5867 // C++ 5.17p3: If the left operand is not of class type, the
5868 // expression is implicitly converted (C++ 4) to the
5869 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00005870 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005871 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00005872 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00005873 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00005874 }
5875
5876 // FIXME: Currently, we fall through and treat C++ classes like C
5877 // structures.
John McCall34376a62010-12-04 03:47:34 +00005878 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005879
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005880 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5881 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00005882 if ((lhsType->isPointerType() ||
5883 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00005884 lhsType->isBlockPointerType())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005885 && rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005886 Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00005887 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005888 return Compatible;
5889 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005890
Chris Lattnere6dcd502007-10-16 02:55:40 +00005891 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005892 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005893 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005894 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005895 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005896 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00005897 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00005898 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005899
John McCall8cb679e2010-11-15 09:13:47 +00005900 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005901 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00005902 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005903
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005904 // C99 6.5.16.1p2: The value of the right operand is converted to the
5905 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005906 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5907 // so that we can use references in built-in functions even in C.
5908 // The getNonReferenceType() call makes sure that the resulting expression
5909 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005910 if (result != Incompatible && rExpr->getType() != lhsType)
John McCall8cb679e2010-11-15 09:13:47 +00005911 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005912 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005913}
5914
Chris Lattner326f7572008-11-18 01:30:42 +00005915QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005916 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005917 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00005918 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005919 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005920}
5921
Chris Lattnerfaa54172010-01-12 21:23:57 +00005922QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005923 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005924 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00005925 QualType lhsType =
5926 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
5927 QualType rhsType =
5928 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005929
Nate Begeman191a6b12008-07-14 18:02:46 +00005930 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005931 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00005932 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005933
Nate Begeman191a6b12008-07-14 18:02:46 +00005934 // Handle the case of a vector & extvector type of the same size and element
5935 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005936 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00005937 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00005938 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00005939 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005940 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005941 if (lhsType->isExtVectorType()) {
John McCalle3027922010-08-25 11:45:40 +00005942 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005943 return lhsType;
5944 }
5945
John McCalle3027922010-08-25 11:45:40 +00005946 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005947 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00005948 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
5949 // If we are allowing lax vector conversions, and LHS and RHS are both
5950 // vectors, the total size only needs to be the same. This is a
5951 // bitcast; no bits are changed but the result type is different.
5952 ImpCastExprToType(rex, lhsType, CK_BitCast);
5953 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005954 }
Eric Christophera613f562010-08-26 00:42:16 +00005955 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00005956 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005957 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005958
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005959 // Handle the case of equivalent AltiVec and GCC vector types
5960 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5961 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCalle3027922010-08-25 11:45:40 +00005962 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005963 return rhsType;
5964 }
5965
Nate Begemanbd956c42009-06-28 02:36:38 +00005966 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5967 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5968 bool swapped = false;
5969 if (rhsType->isExtVectorType()) {
5970 swapped = true;
5971 std::swap(rex, lex);
5972 std::swap(rhsType, lhsType);
5973 }
Mike Stump11289f42009-09-09 15:08:12 +00005974
Nate Begeman886448d2009-06-28 19:12:57 +00005975 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005976 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005977 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005978 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00005979 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5980 if (order > 0)
5981 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
5982 if (order >= 0) {
5983 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005984 if (swapped) std::swap(rex, lex);
5985 return lhsType;
5986 }
5987 }
5988 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5989 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005990 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5991 if (order > 0)
5992 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
5993 if (order >= 0) {
5994 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005995 if (swapped) std::swap(rex, lex);
5996 return lhsType;
5997 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005998 }
5999 }
Mike Stump11289f42009-09-09 15:08:12 +00006000
Nate Begeman886448d2009-06-28 19:12:57 +00006001 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00006002 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006003 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00006004 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006005 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006006}
6007
Chris Lattnerfaa54172010-01-12 21:23:57 +00006008QualType Sema::CheckMultiplyDivideOperands(
6009 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00006010 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006011 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006012
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006013 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006014
Chris Lattnerfaa54172010-01-12 21:23:57 +00006015 if (!lex->getType()->isArithmeticType() ||
6016 !rex->getType()->isArithmeticType())
6017 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006018
Chris Lattnerfaa54172010-01-12 21:23:57 +00006019 // Check for division by zero.
6020 if (isDiv &&
6021 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006022 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattner70117952010-01-12 21:30:55 +00006023 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006024
Chris Lattnerfaa54172010-01-12 21:23:57 +00006025 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006026}
6027
Chris Lattnerfaa54172010-01-12 21:23:57 +00006028QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00006029 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006030 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006031 if (lex->getType()->hasIntegerRepresentation() &&
6032 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006033 return CheckVectorOperands(Loc, lex, rex);
6034 return InvalidOperands(Loc, lex, rex);
6035 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006036
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006037 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006038
Chris Lattnerfaa54172010-01-12 21:23:57 +00006039 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6040 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006041
Chris Lattnerfaa54172010-01-12 21:23:57 +00006042 // Check for remainder by zero.
6043 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00006044 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
6045 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006046
Chris Lattnerfaa54172010-01-12 21:23:57 +00006047 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006048}
6049
Chris Lattnerfaa54172010-01-12 21:23:57 +00006050QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00006051 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006052 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6053 QualType compType = CheckVectorOperands(Loc, lex, rex);
6054 if (CompLHSTy) *CompLHSTy = compType;
6055 return compType;
6056 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006057
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006058 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006059
Steve Naroffe4718892007-04-27 18:30:00 +00006060 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006061 if (lex->getType()->isArithmeticType() &&
6062 rex->getType()->isArithmeticType()) {
6063 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006064 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006065 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006066
Eli Friedman8e122982008-05-18 18:08:51 +00006067 // Put any potential pointer into PExp
6068 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00006069 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006070 std::swap(PExp, IExp);
6071
Steve Naroff6b712a72009-07-14 18:25:06 +00006072 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006073
Eli Friedman8e122982008-05-18 18:08:51 +00006074 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006075 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006076
Chris Lattner12bdebb2009-04-24 23:50:08 +00006077 // Check for arithmetic on pointers to incomplete types.
6078 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006079 if (getLangOptions().CPlusPlus) {
6080 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00006081 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00006082 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006083 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006084
6085 // GNU extension: arithmetic on pointer to void
6086 Diag(Loc, diag::ext_gnu_void_ptr)
6087 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006088 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006089 if (getLangOptions().CPlusPlus) {
6090 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6091 << lex->getType() << lex->getSourceRange();
6092 return QualType();
6093 }
6094
6095 // GNU extension: arithmetic on pointer to function
6096 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6097 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00006098 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006099 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00006100 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00006101 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006102 PExp->getType()->isObjCObjectPointerType()) &&
6103 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00006104 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6105 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006106 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006107 return QualType();
6108 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00006109 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006110 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006111 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6112 << PointeeTy << PExp->getSourceRange();
6113 return QualType();
6114 }
Mike Stump11289f42009-09-09 15:08:12 +00006115
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006116 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00006117 QualType LHSTy = Context.isPromotableBitField(lex);
6118 if (LHSTy.isNull()) {
6119 LHSTy = lex->getType();
6120 if (LHSTy->isPromotableIntegerType())
6121 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006122 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006123 *CompLHSTy = LHSTy;
6124 }
Eli Friedman8e122982008-05-18 18:08:51 +00006125 return PExp->getType();
6126 }
6127 }
6128
Chris Lattner326f7572008-11-18 01:30:42 +00006129 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006130}
6131
Chris Lattner2a3569b2008-04-07 05:30:13 +00006132// C99 6.5.6
6133QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006134 SourceLocation Loc, QualType* CompLHSTy) {
6135 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6136 QualType compType = CheckVectorOperands(Loc, lex, rex);
6137 if (CompLHSTy) *CompLHSTy = compType;
6138 return compType;
6139 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006140
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006141 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006142
Chris Lattner4d62f422007-12-09 21:53:25 +00006143 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006144
Chris Lattner4d62f422007-12-09 21:53:25 +00006145 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00006146 if (lex->getType()->isArithmeticType()
6147 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006148 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006149 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006150 }
Mike Stump11289f42009-09-09 15:08:12 +00006151
Chris Lattner4d62f422007-12-09 21:53:25 +00006152 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00006153 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00006154 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006155
Douglas Gregorac1fb652009-03-24 19:52:54 +00006156 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006157
Douglas Gregorac1fb652009-03-24 19:52:54 +00006158 bool ComplainAboutVoid = false;
6159 Expr *ComplainAboutFunc = 0;
6160 if (lpointee->isVoidType()) {
6161 if (getLangOptions().CPlusPlus) {
6162 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6163 << lex->getSourceRange() << rex->getSourceRange();
6164 return QualType();
6165 }
6166
6167 // GNU C extension: arithmetic on pointer to void
6168 ComplainAboutVoid = true;
6169 } else if (lpointee->isFunctionType()) {
6170 if (getLangOptions().CPlusPlus) {
6171 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006172 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006173 return QualType();
6174 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006175
6176 // GNU C extension: arithmetic on pointer to function
6177 ComplainAboutFunc = lex;
6178 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00006179 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006180 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00006181 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006182 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006183 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006184
Chris Lattner12bdebb2009-04-24 23:50:08 +00006185 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006186 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006187 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6188 << lpointee << lex->getSourceRange();
6189 return QualType();
6190 }
Mike Stump11289f42009-09-09 15:08:12 +00006191
Chris Lattner4d62f422007-12-09 21:53:25 +00006192 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00006193 if (rex->getType()->isIntegerType()) {
6194 if (ComplainAboutVoid)
6195 Diag(Loc, diag::ext_gnu_void_ptr)
6196 << lex->getSourceRange() << rex->getSourceRange();
6197 if (ComplainAboutFunc)
6198 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006199 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006200 << ComplainAboutFunc->getSourceRange();
6201
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006202 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006203 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006204 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006205
Chris Lattner4d62f422007-12-09 21:53:25 +00006206 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006207 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006208 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006209
Douglas Gregorac1fb652009-03-24 19:52:54 +00006210 // RHS must be a completely-type object type.
6211 // Handle the GNU void* extension.
6212 if (rpointee->isVoidType()) {
6213 if (getLangOptions().CPlusPlus) {
6214 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6215 << lex->getSourceRange() << rex->getSourceRange();
6216 return QualType();
6217 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006218
Douglas Gregorac1fb652009-03-24 19:52:54 +00006219 ComplainAboutVoid = true;
6220 } else if (rpointee->isFunctionType()) {
6221 if (getLangOptions().CPlusPlus) {
6222 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006223 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006224 return QualType();
6225 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006226
6227 // GNU extension: arithmetic on pointer to function
6228 if (!ComplainAboutFunc)
6229 ComplainAboutFunc = rex;
6230 } else if (!rpointee->isDependentType() &&
6231 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006232 PDiag(diag::err_typecheck_sub_ptr_object)
6233 << rex->getSourceRange()
6234 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006235 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006236
Eli Friedman168fe152009-05-16 13:54:38 +00006237 if (getLangOptions().CPlusPlus) {
6238 // Pointee types must be the same: C++ [expr.add]
6239 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6240 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6241 << lex->getType() << rex->getType()
6242 << lex->getSourceRange() << rex->getSourceRange();
6243 return QualType();
6244 }
6245 } else {
6246 // Pointee types must be compatible C99 6.5.6p3
6247 if (!Context.typesAreCompatible(
6248 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6249 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6250 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6251 << lex->getType() << rex->getType()
6252 << lex->getSourceRange() << rex->getSourceRange();
6253 return QualType();
6254 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006255 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006256
Douglas Gregorac1fb652009-03-24 19:52:54 +00006257 if (ComplainAboutVoid)
6258 Diag(Loc, diag::ext_gnu_void_ptr)
6259 << lex->getSourceRange() << rex->getSourceRange();
6260 if (ComplainAboutFunc)
6261 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006262 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006263 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006264
6265 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006266 return Context.getPointerDiffType();
6267 }
6268 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006269
Chris Lattner326f7572008-11-18 01:30:42 +00006270 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006271}
6272
Douglas Gregor0bf31402010-10-08 23:50:27 +00006273static bool isScopedEnumerationType(QualType T) {
6274 if (const EnumType *ET = dyn_cast<EnumType>(T))
6275 return ET->getDecl()->isScoped();
6276 return false;
6277}
6278
Chris Lattner2a3569b2008-04-07 05:30:13 +00006279// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00006280QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00006281 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006282 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006283 if (!lex->getType()->hasIntegerRepresentation() ||
6284 !rex->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006285 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006286
Douglas Gregor0bf31402010-10-08 23:50:27 +00006287 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6288 // hasIntegerRepresentation() above instead of this.
6289 if (isScopedEnumerationType(lex->getType()) ||
6290 isScopedEnumerationType(rex->getType())) {
6291 return InvalidOperands(Loc, lex, rex);
6292 }
6293
Nate Begemane46ee9a2009-10-25 02:26:48 +00006294 // Vector shifts promote their scalar inputs to vector type.
6295 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6296 return CheckVectorOperands(Loc, lex, rex);
6297
Chris Lattner5c11c412007-12-12 05:47:28 +00006298 // Shifts don't perform usual arithmetic conversions, they just do integer
6299 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006300
John McCall57cdd882010-12-16 19:28:59 +00006301 // For the LHS, do usual unary conversions, but then reset them away
6302 // if this is a compound assignment.
6303 Expr *old_lex = lex;
6304 UsualUnaryConversions(lex);
6305 QualType LHSTy = lex->getType();
6306 if (isCompAssign) lex = old_lex;
6307
6308 // The RHS is simpler.
Chris Lattner5c11c412007-12-12 05:47:28 +00006309 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006310
Ryan Flynnf53fab82009-08-07 16:20:20 +00006311 // Sanity-check shift operands
6312 llvm::APSInt Right;
6313 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00006314 if (!rex->isValueDependent() &&
6315 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00006316 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00006317 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6318 else {
6319 llvm::APInt LeftBits(Right.getBitWidth(),
6320 Context.getTypeSize(lex->getType()));
6321 if (Right.uge(LeftBits))
6322 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6323 }
6324 }
6325
Chris Lattner5c11c412007-12-12 05:47:28 +00006326 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006327 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006328}
6329
Chandler Carruth17773fc2010-07-10 12:30:03 +00006330static bool IsWithinTemplateSpecialization(Decl *D) {
6331 if (DeclContext *DC = D->getDeclContext()) {
6332 if (isa<ClassTemplateSpecializationDecl>(DC))
6333 return true;
6334 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6335 return FD->isFunctionTemplateSpecialization();
6336 }
6337 return false;
6338}
6339
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006340// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00006341QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006342 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006343 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006344
Chris Lattner9a152e22009-12-05 05:40:13 +00006345 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00006346 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006347 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006348
Steve Naroff31090012007-07-16 21:54:35 +00006349 QualType lType = lex->getType();
6350 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006351
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006352 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006353 !(lType->isBlockPointerType() && isRelational) &&
6354 !lex->getLocStart().isMacroID() &&
6355 !rex->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006356 // For non-floating point types, check for self-comparisons of the form
6357 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6358 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006359 //
6360 // NOTE: Don't warn about comparison expressions resulting from macro
6361 // expansion. Also don't warn about comparisons which are only self
6362 // comparisons within a template specialization. The warnings should catch
6363 // obvious cases in the definition of the template anyways. The idea is to
6364 // warn when the typed comparison operator will always evaluate to the same
6365 // result.
John McCall34376a62010-12-04 03:47:34 +00006366 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6367 Expr *RHSStripped = rex->IgnoreParenImpCasts();
Chandler Carruth17773fc2010-07-10 12:30:03 +00006368 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006369 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006370 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006371 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006372 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6373 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006374 << (Opc == BO_EQ
6375 || Opc == BO_LE
6376 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006377 } else if (lType->isArrayType() && rType->isArrayType() &&
6378 !DRL->getDecl()->getType()->isReferenceType() &&
6379 !DRR->getDecl()->getType()->isReferenceType()) {
6380 // what is it always going to eval to?
6381 char always_evals_to;
6382 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006383 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006384 always_evals_to = 0; // false
6385 break;
John McCalle3027922010-08-25 11:45:40 +00006386 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006387 always_evals_to = 1; // true
6388 break;
6389 default:
6390 // best we can say is 'a constant'
6391 always_evals_to = 2; // e.g. array1 <= array2
6392 break;
6393 }
6394 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6395 << 1 // array
6396 << always_evals_to);
6397 }
6398 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006399 }
Mike Stump11289f42009-09-09 15:08:12 +00006400
Chris Lattner222b8bd2009-03-08 19:39:53 +00006401 if (isa<CastExpr>(LHSStripped))
6402 LHSStripped = LHSStripped->IgnoreParenCasts();
6403 if (isa<CastExpr>(RHSStripped))
6404 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006405
Chris Lattner222b8bd2009-03-08 19:39:53 +00006406 // Warn about comparisons against a string constant (unless the other
6407 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006408 Expr *literalString = 0;
6409 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006410 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006411 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006412 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006413 literalString = lex;
6414 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006415 } else if ((isa<StringLiteral>(RHSStripped) ||
6416 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006417 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006418 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006419 literalString = rex;
6420 literalStringStripped = RHSStripped;
6421 }
6422
6423 if (literalString) {
6424 std::string resultComparison;
6425 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006426 case BO_LT: resultComparison = ") < 0"; break;
6427 case BO_GT: resultComparison = ") > 0"; break;
6428 case BO_LE: resultComparison = ") <= 0"; break;
6429 case BO_GE: resultComparison = ") >= 0"; break;
6430 case BO_EQ: resultComparison = ") == 0"; break;
6431 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006432 default: assert(false && "Invalid comparison operator");
6433 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006434
Douglas Gregor49862b82010-01-12 23:18:54 +00006435 DiagRuntimeBehavior(Loc,
6436 PDiag(diag::warn_stringcompare)
6437 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006438 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006439 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006440 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006441
Douglas Gregorec170db2010-06-08 19:50:34 +00006442 // C99 6.5.8p3 / C99 6.5.9p4
6443 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6444 UsualArithmeticConversions(lex, rex);
6445 else {
6446 UsualUnaryConversions(lex);
6447 UsualUnaryConversions(rex);
6448 }
6449
6450 lType = lex->getType();
6451 rType = rex->getType();
6452
Douglas Gregorca63811b2008-11-19 03:25:36 +00006453 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00006454 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00006455
Chris Lattnerb620c342007-08-26 01:18:55 +00006456 if (isRelational) {
6457 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006458 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006459 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006460 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006461 if (lType->hasFloatingRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006462 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006463
Chris Lattnerb620c342007-08-26 01:18:55 +00006464 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006465 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006466 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006467
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006468 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006469 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006470 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006471 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006472
Douglas Gregorf267edd2010-06-15 21:38:40 +00006473 // All of the following pointer-related warnings are GCC extensions, except
6474 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006475 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006476 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006477 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006478 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006479 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006480
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006481 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006482 if (LCanPointeeTy == RCanPointeeTy)
6483 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006484 if (!isRelational &&
6485 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6486 // Valid unless comparison between non-null pointer and function pointer
6487 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006488 // In a SFINAE context, we treat this as a hard error to maintain
6489 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006490 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6491 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006492 Diag(Loc,
6493 isSFINAEContext()?
6494 diag::err_typecheck_comparison_of_fptr_to_void
6495 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006496 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006497
6498 if (isSFINAEContext())
6499 return QualType();
6500
John McCalle3027922010-08-25 11:45:40 +00006501 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006502 return ResultTy;
6503 }
6504 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006505
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006506 // C++ [expr.rel]p2:
6507 // [...] Pointer conversions (4.10) and qualification
6508 // conversions (4.4) are performed on pointer operands (or on
6509 // a pointer operand and a null pointer constant) to bring
6510 // them to their composite pointer type. [...]
6511 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006512 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006513 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006514 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006515 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006516 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006517 if (T.isNull()) {
6518 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6519 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6520 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006521 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006522 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006523 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006524 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006525 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006526 }
6527
John McCalle3027922010-08-25 11:45:40 +00006528 ImpCastExprToType(lex, T, CK_BitCast);
6529 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006530 return ResultTy;
6531 }
Eli Friedman16c209612009-08-23 00:27:47 +00006532 // C99 6.5.9p2 and C99 6.5.8p2
6533 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6534 RCanPointeeTy.getUnqualifiedType())) {
6535 // Valid unless a relational comparison of function pointers
6536 if (isRelational && LCanPointeeTy->isFunctionType()) {
6537 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6538 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6539 }
6540 } else if (!isRelational &&
6541 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6542 // Valid unless comparison between non-null pointer and function pointer
6543 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6544 && !LHSIsNull && !RHSIsNull) {
6545 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6546 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6547 }
6548 } else {
6549 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006550 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006551 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006552 }
Eli Friedman16c209612009-08-23 00:27:47 +00006553 if (LCanPointeeTy != RCanPointeeTy)
John McCalle3027922010-08-25 11:45:40 +00006554 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006555 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006556 }
Mike Stump11289f42009-09-09 15:08:12 +00006557
Sebastian Redl576fd422009-05-10 18:38:11 +00006558 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006559 // Comparison of nullptr_t with itself.
6560 if (lType->isNullPtrType() && rType->isNullPtrType())
6561 return ResultTy;
6562
Mike Stump11289f42009-09-09 15:08:12 +00006563 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006564 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006565 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006566 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006567 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006568 ImpCastExprToType(rex, lType,
6569 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006570 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006571 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006572 return ResultTy;
6573 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006574 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006575 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006576 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006577 ImpCastExprToType(lex, rType,
6578 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006579 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006580 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006581 return ResultTy;
6582 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006583
6584 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006585 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006586 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6587 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006588 // In addition, pointers to members can be compared, or a pointer to
6589 // member and a null pointer constant. Pointer to member conversions
6590 // (4.11) and qualification conversions (4.4) are performed to bring
6591 // them to a common type. If one operand is a null pointer constant,
6592 // the common type is the type of the other operand. Otherwise, the
6593 // common type is a pointer to member type similar (4.4) to the type
6594 // of one of the operands, with a cv-qualification signature (4.4)
6595 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006596 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006597 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006598 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006599 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006600 if (T.isNull()) {
6601 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006602 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006603 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006604 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006605 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006606 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006607 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006608 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006609 }
Mike Stump11289f42009-09-09 15:08:12 +00006610
John McCalle3027922010-08-25 11:45:40 +00006611 ImpCastExprToType(lex, T, CK_BitCast);
6612 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006613 return ResultTy;
6614 }
Sebastian Redl576fd422009-05-10 18:38:11 +00006615 }
Mike Stump11289f42009-09-09 15:08:12 +00006616
Steve Naroff081c7422008-09-04 15:10:53 +00006617 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00006618 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006619 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6620 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006621
Steve Naroff081c7422008-09-04 15:10:53 +00006622 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006623 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006624 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006625 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006626 }
John McCalle3027922010-08-25 11:45:40 +00006627 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006628 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006629 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00006630 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006631 if (!isRelational
6632 && ((lType->isBlockPointerType() && rType->isPointerType())
6633 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006634 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006635 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006636 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006637 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006638 ->getPointeeType()->isVoidType())))
6639 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6640 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006641 }
John McCalle3027922010-08-25 11:45:40 +00006642 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006643 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006644 }
Steve Naroff081c7422008-09-04 15:10:53 +00006645
Steve Naroff7cae42b2009-07-10 23:34:53 +00006646 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006647 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006648 const PointerType *LPT = lType->getAs<PointerType>();
6649 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006650 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00006651 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006652 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00006653 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006654
Steve Naroff753567f2008-11-17 19:49:16 +00006655 if (!LPtrToVoid && !RPtrToVoid &&
6656 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006657 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006658 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006659 }
John McCalle3027922010-08-25 11:45:40 +00006660 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006661 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006662 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006663 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006664 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006665 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6666 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006667 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006668 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006669 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006670 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006671 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6672 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006673 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006674 bool isError = false;
6675 if ((LHSIsNull && lType->isIntegerType()) ||
6676 (RHSIsNull && rType->isIntegerType())) {
6677 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006678 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006679 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006680 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006681 else if (getLangOptions().CPlusPlus) {
6682 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6683 isError = true;
6684 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006685 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006686
Chris Lattnerd99bd522009-08-23 00:03:44 +00006687 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006688 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00006689 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006690 if (isError)
6691 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006692 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006693
6694 if (lType->isIntegerType())
John McCalle84af4e2010-11-13 01:35:44 +00006695 ImpCastExprToType(lex, rType,
6696 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006697 else
John McCalle84af4e2010-11-13 01:35:44 +00006698 ImpCastExprToType(rex, lType,
6699 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006700 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006701 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006702
Steve Naroff4b191572008-09-04 16:56:14 +00006703 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006704 if (!isRelational && RHSIsNull
6705 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00006706 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006707 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006708 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006709 if (!isRelational && LHSIsNull
6710 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00006711 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006712 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006713 }
Chris Lattner326f7572008-11-18 01:30:42 +00006714 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006715}
6716
Nate Begeman191a6b12008-07-14 18:02:46 +00006717/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006718/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006719/// like a scalar comparison, a vector comparison produces a vector of integer
6720/// types.
6721QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00006722 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006723 bool isRelational) {
6724 // Check to make sure we're operating on vectors of the same type and width,
6725 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00006726 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00006727 if (vType.isNull())
6728 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006729
Anton Yartsev3f8f2882010-11-18 03:19:30 +00006730 // If AltiVec, the comparison results in a numeric type, i.e.
6731 // bool for C++, int for C
6732 if (getLangOptions().AltiVec)
6733 return (getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy);
6734
Nate Begeman191a6b12008-07-14 18:02:46 +00006735 QualType lType = lex->getType();
6736 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006737
Nate Begeman191a6b12008-07-14 18:02:46 +00006738 // For non-floating point types, check for self-comparisons of the form
6739 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6740 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006741 if (!lType->hasFloatingRepresentation()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006742 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
6743 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
6744 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregorec170db2010-06-08 19:50:34 +00006745 DiagRuntimeBehavior(Loc,
6746 PDiag(diag::warn_comparison_always)
6747 << 0 // self-
6748 << 2 // "a constant"
6749 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006750 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006751
Nate Begeman191a6b12008-07-14 18:02:46 +00006752 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006753 if (!isRelational && lType->hasFloatingRepresentation()) {
6754 assert (rType->hasFloatingRepresentation());
Chris Lattner326f7572008-11-18 01:30:42 +00006755 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00006756 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006757
Nate Begeman191a6b12008-07-14 18:02:46 +00006758 // Return the type for the comparison, which is the same as vector type for
6759 // integer vectors, or an integer type of identical size and number of
6760 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006761 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00006762 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006763
John McCall9dd450b2009-09-21 23:43:11 +00006764 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006765 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006766 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006767 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006768 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006769 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6770
Mike Stump4e1f26a2009-02-19 03:04:26 +00006771 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006772 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006773 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6774}
6775
Steve Naroff218bc2b2007-05-04 21:54:46 +00006776inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00006777 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006778 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6779 if (lex->getType()->hasIntegerRepresentation() &&
6780 rex->getType()->hasIntegerRepresentation())
6781 return CheckVectorOperands(Loc, lex, rex);
6782
6783 return InvalidOperands(Loc, lex, rex);
6784 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006785
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006786 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006787
Douglas Gregor0bf31402010-10-08 23:50:27 +00006788 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
6789 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006790 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00006791 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006792}
6793
Steve Naroff218bc2b2007-05-04 21:54:46 +00006794inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner8406c512010-07-13 19:41:32 +00006795 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
6796
6797 // Diagnose cases where the user write a logical and/or but probably meant a
6798 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6799 // is a constant.
6800 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman6b197e02010-07-27 19:14:53 +00006801 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00006802 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00006803 !Loc.isMacroID()) {
6804 // If the RHS can be constant folded, and if it constant folds to something
6805 // that isn't 0 or 1 (which indicate a potential logical operation that
6806 // happened to fold to true/false) then warn.
6807 Expr::EvalResult Result;
6808 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
6809 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
6810 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6811 << rex->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00006812 << (Opc == BO_LAnd ? "&&" : "||")
6813 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00006814 }
6815 }
Chris Lattner8406c512010-07-13 19:41:32 +00006816
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006817 if (!Context.getLangOptions().CPlusPlus) {
6818 UsualUnaryConversions(lex);
6819 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006820
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006821 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
6822 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006823
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006824 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006825 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006826
John McCall4a2429a2010-06-04 00:29:51 +00006827 // The following is safe because we only use this method for
6828 // non-overloadable operands.
6829
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006830 // C++ [expr.log.and]p1
6831 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006832 // The operands are both contextually converted to type bool.
6833 if (PerformContextuallyConvertToBool(lex) ||
6834 PerformContextuallyConvertToBool(rex))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006835 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006836
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006837 // C++ [expr.log.and]p2
6838 // C++ [expr.log.or]p2
6839 // The result is a bool.
6840 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006841}
6842
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006843/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6844/// is a read-only property; return true if so. A readonly property expression
6845/// depends on various declarations and thus must be treated specially.
6846///
Mike Stump11289f42009-09-09 15:08:12 +00006847static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006848 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6849 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006850 if (PropExpr->isImplicitProperty()) return false;
6851
6852 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6853 QualType BaseType = PropExpr->isSuperReceiver() ?
6854 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006855 PropExpr->getBase()->getType();
6856
John McCallb7bd14f2010-12-02 01:19:52 +00006857 if (const ObjCObjectPointerType *OPT =
6858 BaseType->getAsObjCInterfacePointerType())
6859 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6860 if (S.isPropertyReadonly(PDecl, IFace))
6861 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006862 }
6863 return false;
6864}
6865
Chris Lattner30bd3272008-11-18 01:22:49 +00006866/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6867/// emit an error and return true. If so, return false.
6868static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006869 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006870 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006871 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006872 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6873 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00006874 if (IsLV == Expr::MLV_Valid)
6875 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006876
Chris Lattner30bd3272008-11-18 01:22:49 +00006877 unsigned Diag = 0;
6878 bool NeedType = false;
6879 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00006880 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006881 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006882 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6883 NeedType = true;
6884 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006885 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006886 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6887 NeedType = true;
6888 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006889 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006890 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6891 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006892 case Expr::MLV_Valid:
6893 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006894 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006895 case Expr::MLV_MemberFunction:
6896 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006897 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6898 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006899 case Expr::MLV_IncompleteType:
6900 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006901 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006902 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006903 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006904 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006905 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6906 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006907 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006908 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6909 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006910 case Expr::MLV_ReadonlyProperty:
6911 Diag = diag::error_readonly_property_assignment;
6912 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006913 case Expr::MLV_NoSetterProperty:
6914 Diag = diag::error_nosetter_property_assignment;
6915 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006916 case Expr::MLV_SubObjCPropertySetting:
6917 Diag = diag::error_no_subobject_property_setting;
6918 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006919 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006920
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006921 SourceRange Assign;
6922 if (Loc != OrigLoc)
6923 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006924 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006925 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006926 else
Mike Stump11289f42009-09-09 15:08:12 +00006927 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006928 return true;
6929}
6930
6931
6932
6933// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00006934QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
6935 SourceLocation Loc,
6936 QualType CompoundType) {
6937 // Verify that LHS is a modifiable lvalue, and emit error if not.
6938 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00006939 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00006940
6941 QualType LHSType = LHS->getType();
6942 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006943 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00006944 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006945 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006946 // Simple assignment "x = y".
John McCall34376a62010-12-04 03:47:34 +00006947 if (LHS->getObjectKind() == OK_ObjCProperty)
6948 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006949 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006950 // Special case of NSObject attributes on c-style pointer types.
6951 if (ConvTy == IncompatiblePointer &&
6952 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006953 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006954 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006955 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006956 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006957
John McCall7decc9e2010-11-18 06:31:45 +00006958 if (ConvTy == Compatible &&
6959 getLangOptions().ObjCNonFragileABI &&
6960 LHSType->isObjCObjectType())
6961 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6962 << LHSType;
6963
Chris Lattnerea714382008-08-21 18:04:13 +00006964 // If the RHS is a unary plus or minus, check to see if they = and + are
6965 // right next to each other. If so, the user may have typo'd "x =+ 4"
6966 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00006967 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00006968 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6969 RHSCheck = ICE->getSubExpr();
6970 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00006971 if ((UO->getOpcode() == UO_Plus ||
6972 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00006973 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00006974 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00006975 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6976 // And there is a space or other character before the subexpr of the
6977 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00006978 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6979 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006980 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00006981 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00006982 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00006983 }
Chris Lattnerea714382008-08-21 18:04:13 +00006984 }
6985 } else {
6986 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00006987 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006988 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006989
Chris Lattner326f7572008-11-18 01:30:42 +00006990 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006991 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00006992 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006993
Chris Lattner39561062010-07-07 06:14:23 +00006994
6995 // Check to see if the destination operand is a dereferenced null pointer. If
6996 // so, and if not volatile-qualified, this is undefined behavior that the
6997 // optimizer will delete, so warn about it. People sometimes try to use this
6998 // to get a deterministic trap and are surprised by clang's behavior. This
6999 // only handles the pattern "*null = whatever", which is a very syntactic
7000 // check.
7001 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCalle3027922010-08-25 11:45:40 +00007002 if (UO->getOpcode() == UO_Deref &&
Chris Lattner39561062010-07-07 06:14:23 +00007003 UO->getSubExpr()->IgnoreParenCasts()->
7004 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7005 !UO->getType().isVolatileQualified()) {
7006 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
7007 << UO->getSubExpr()->getSourceRange();
7008 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
7009 }
7010
Steve Naroff98cf3e92007-06-06 18:38:38 +00007011 // C99 6.5.16p3: The type of an assignment expression is the type of the
7012 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007013 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007014 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7015 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007016 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007017 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007018 return (getLangOptions().CPlusPlus
7019 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007020}
7021
Chris Lattner326f7572008-11-18 01:30:42 +00007022// C99 6.5.17
John McCall34376a62010-12-04 03:47:34 +00007023static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007024 SourceLocation Loc) {
7025 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007026
John McCall4bc41ae2010-11-18 19:01:18 +00007027 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007028 if (LHSResult.isInvalid())
7029 return QualType();
7030
John McCall4bc41ae2010-11-18 19:01:18 +00007031 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007032 if (RHSResult.isInvalid())
7033 return QualType();
7034 RHS = RHSResult.take();
7035
John McCall73d36182010-10-12 07:14:40 +00007036 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7037 // operands, but not unary promotions.
7038 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007039
John McCall34376a62010-12-04 03:47:34 +00007040 // So we treat the LHS as a ignored value, and in C++ we allow the
7041 // containing site to determine what should be done with the RHS.
7042 S.IgnoredValueConversions(LHS);
7043
7044 if (!S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007045 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCall73d36182010-10-12 07:14:40 +00007046 if (!RHS->getType()->isVoidType())
John McCall4bc41ae2010-11-18 19:01:18 +00007047 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007048 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007049
Chris Lattner326f7572008-11-18 01:30:42 +00007050 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007051}
7052
Steve Naroff7a5af782007-07-13 16:58:59 +00007053/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7054/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007055static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7056 ExprValueKind &VK,
7057 SourceLocation OpLoc,
7058 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007059 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007060 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007061
Chris Lattner6b0cf142008-11-21 07:05:48 +00007062 QualType ResType = Op->getType();
7063 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007064
John McCall4bc41ae2010-11-18 19:01:18 +00007065 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007066 // Decrement of bool is not allowed.
7067 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007068 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007069 return QualType();
7070 }
7071 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007072 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007073 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007074 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007075 } else if (ResType->isAnyPointerType()) {
7076 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007077
Chris Lattner6b0cf142008-11-21 07:05:48 +00007078 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00007079 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007080 if (S.getLangOptions().CPlusPlus) {
7081 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007082 << Op->getSourceRange();
7083 return QualType();
7084 }
7085
7086 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00007087 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007088 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007089 if (S.getLangOptions().CPlusPlus) {
7090 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007091 << Op->getType() << Op->getSourceRange();
7092 return QualType();
7093 }
7094
John McCall4bc41ae2010-11-18 19:01:18 +00007095 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007096 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007097 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7098 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00007099 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00007100 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00007101 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007102 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00007103 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7104 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007105 << PointeeTy << Op->getSourceRange();
7106 return QualType();
7107 }
Eli Friedman090addd2010-01-03 00:20:48 +00007108 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007109 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007110 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007111 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007112 } else if (ResType->isPlaceholderType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007113 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007114 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007115 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7116 isInc, isPrefix);
Chris Lattner6b0cf142008-11-21 07:05:48 +00007117 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007118 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007119 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007120 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007121 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007122 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007123 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007124 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007125 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007126 // In C++, a prefix increment is the same type as the operand. Otherwise
7127 // (in C or with postfix), the increment is the unqualified type of the
7128 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007129 if (isPrefix && S.getLangOptions().CPlusPlus) {
7130 VK = VK_LValue;
7131 return ResType;
7132 } else {
7133 VK = VK_RValue;
7134 return ResType.getUnqualifiedType();
7135 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007136}
7137
John McCall34376a62010-12-04 03:47:34 +00007138void Sema::ConvertPropertyForRValue(Expr *&E) {
7139 assert(E->getValueKind() == VK_LValue &&
7140 E->getObjectKind() == OK_ObjCProperty);
7141 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7142
7143 ExprValueKind VK = VK_RValue;
7144 if (PRE->isImplicitProperty()) {
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007145 if (const ObjCMethodDecl *GetterMethod =
7146 PRE->getImplicitPropertyGetter()) {
7147 QualType Result = GetterMethod->getResultType();
7148 VK = Expr::getValueKindForType(Result);
7149 }
7150 else {
7151 Diag(PRE->getLocation(), diag::err_getter_not_found)
7152 << PRE->getBase()->getType();
7153 }
John McCall34376a62010-12-04 03:47:34 +00007154 }
7155
7156 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7157 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007158
7159 ExprResult Result = MaybeBindToTemporary(E);
7160 if (!Result.isInvalid())
7161 E = Result.take();
John McCall34376a62010-12-04 03:47:34 +00007162}
7163
7164void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7165 assert(LHS->getValueKind() == VK_LValue &&
7166 LHS->getObjectKind() == OK_ObjCProperty);
7167 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7168
7169 if (PRE->isImplicitProperty()) {
7170 // If using property-dot syntax notation for assignment, and there is a
7171 // setter, RHS expression is being passed to the setter argument. So,
7172 // type conversion (and comparison) is RHS to setter's argument type.
7173 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7174 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7175 LHSTy = (*P)->getType();
7176
7177 // Otherwise, if the getter returns an l-value, just call that.
7178 } else {
7179 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7180 ExprValueKind VK = Expr::getValueKindForType(Result);
7181 if (VK == VK_LValue) {
7182 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7183 CK_GetObjCProperty, LHS, 0, VK);
7184 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007185 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007186 }
John McCall34376a62010-12-04 03:47:34 +00007187 }
7188
7189 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007190 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007191 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007192 Expr *Arg = RHS;
7193 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7194 Owned(Arg));
7195 if (!ArgE.isInvalid())
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007196 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007197 }
7198}
7199
7200
Anders Carlsson806700f2008-02-01 07:15:58 +00007201/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007202/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007203/// where the declaration is needed for type checking. We only need to
7204/// handle cases when the expression references a function designator
7205/// or is an lvalue. Here are some examples:
7206/// - &(x) => x
7207/// - &*****f => f for f a function designator.
7208/// - &s.xx => s
7209/// - &s.zz[1].yy -> s, if zz is an array
7210/// - *(x + 1) -> x, if x is an array
7211/// - &"123"[2] -> 0
7212/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007213static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007214 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007215 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007216 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007217 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007218 // If this is an arrow operator, the address is an offset from
7219 // the base's value, so the object the base refers to is
7220 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007221 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007222 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007223 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007224 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007225 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007226 // FIXME: This code shouldn't be necessary! We should catch the implicit
7227 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007228 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7229 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7230 if (ICE->getSubExpr()->getType()->isArrayType())
7231 return getPrimaryDecl(ICE->getSubExpr());
7232 }
7233 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007234 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007235 case Stmt::UnaryOperatorClass: {
7236 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007237
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007238 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007239 case UO_Real:
7240 case UO_Imag:
7241 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007242 return getPrimaryDecl(UO->getSubExpr());
7243 default:
7244 return 0;
7245 }
7246 }
Steve Naroff47500512007-04-19 23:00:49 +00007247 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007248 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007249 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007250 // If the result of an implicit cast is an l-value, we care about
7251 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007252 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007253 default:
7254 return 0;
7255 }
7256}
7257
7258/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007259/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007260/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007261/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007262/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007263/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007264/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007265static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7266 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007267 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007268 return S.Context.DependentTy;
7269 if (OrigOp->getType() == S.Context.OverloadTy)
7270 return S.Context.OverloadTy;
John McCall8d08b9b2010-08-27 09:08:28 +00007271
John McCall4bc41ae2010-11-18 19:01:18 +00007272 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007273 if (PR.isInvalid()) return QualType();
7274 OrigOp = PR.take();
7275
John McCall8d08b9b2010-08-27 09:08:28 +00007276 // Make sure to ignore parentheses in subsequent checks
7277 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007278
John McCall4bc41ae2010-11-18 19:01:18 +00007279 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007280 // Implement C99-only parts of addressof rules.
7281 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007282 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007283 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7284 // (assuming the deref expression is valid).
7285 return uOp->getSubExpr()->getType();
7286 }
7287 // Technically, there should be a check for array subscript
7288 // expressions here, but the result of one is always an lvalue anyway.
7289 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007290 NamedDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007291 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007292
Chris Lattner9156f1b2010-07-05 19:17:26 +00007293 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007294 bool sfinae = S.isSFINAEContext();
7295 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7296 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007297 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007298 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007299 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007300 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007301 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007302 } else if (lval == Expr::LV_MemberFunction) {
7303 // If it's an instance method, make a member pointer.
7304 // The expression must have exactly the form &A::foo.
7305
7306 // If the underlying expression isn't a decl ref, give up.
7307 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007308 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007309 << OrigOp->getSourceRange();
7310 return QualType();
7311 }
7312 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7313 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7314
7315 // The id-expression was parenthesized.
7316 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007317 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007318 << OrigOp->getSourceRange();
7319
7320 // The method was named without a qualifier.
7321 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007322 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007323 << op->getSourceRange();
7324 }
7325
John McCall4bc41ae2010-11-18 19:01:18 +00007326 return S.Context.getMemberPointerType(op->getType(),
7327 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007328 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007329 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007330 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007331 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007332 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007333 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007334 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007335 return QualType();
7336 }
John McCall086a4642010-11-24 05:12:34 +00007337 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007338 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007339 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007340 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007341 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007342 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007343 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007344 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007345 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007346 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007347 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007348 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007349 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007350 << "property expression" << op->getSourceRange();
7351 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007352 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007353 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007354 // with the register storage-class specifier.
7355 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007356 // in C++ it is not error to take address of a register
7357 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007358 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007359 !S.getLangOptions().CPlusPlus) {
7360 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007361 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007362 return QualType();
7363 }
John McCalld14a8642009-11-21 08:51:07 +00007364 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007365 return S.Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00007366 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007367 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007368 // Could be a pointer to member, though, if there is an explicit
7369 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007370 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007371 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007372 if (Ctx && Ctx->isRecord()) {
7373 if (FD->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007374 S.Diag(OpLoc,
7375 diag::err_cannot_form_pointer_to_member_of_reference_type)
Anders Carlsson0b675f52009-07-08 21:45:58 +00007376 << FD->getDeclName() << FD->getType();
7377 return QualType();
7378 }
Mike Stump11289f42009-09-09 15:08:12 +00007379
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007380 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7381 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007382 return S.Context.getMemberPointerType(op->getType(),
7383 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007384 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007385 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007386 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007387 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007388 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007389
Eli Friedmance7f9002009-05-16 23:27:50 +00007390 if (lval == Expr::LV_IncompleteVoidType) {
7391 // Taking the address of a void variable is technically illegal, but we
7392 // allow it in cases which are otherwise valid.
7393 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007394 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007395 }
7396
Steve Naroff47500512007-04-19 23:00:49 +00007397 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007398 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007399 return S.Context.getObjCObjectPointerType(op->getType());
7400 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007401}
7402
Chris Lattner9156f1b2010-07-05 19:17:26 +00007403/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007404static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7405 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007406 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007407 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007408
John McCall4bc41ae2010-11-18 19:01:18 +00007409 S.UsualUnaryConversions(Op);
Chris Lattner9156f1b2010-07-05 19:17:26 +00007410 QualType OpTy = Op->getType();
7411 QualType Result;
7412
7413 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7414 // is an incomplete type or void. It would be possible to warn about
7415 // dereferencing a void pointer, but it's completely well-defined, and such a
7416 // warning is unlikely to catch any mistakes.
7417 if (const PointerType *PT = OpTy->getAs<PointerType>())
7418 Result = PT->getPointeeType();
7419 else if (const ObjCObjectPointerType *OPT =
7420 OpTy->getAs<ObjCObjectPointerType>())
7421 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007422 else {
John McCall4bc41ae2010-11-18 19:01:18 +00007423 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007424 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007425 if (PR.take() != Op)
7426 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007427 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007428
Chris Lattner9156f1b2010-07-05 19:17:26 +00007429 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007430 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007431 << OpTy << Op->getSourceRange();
7432 return QualType();
7433 }
John McCall4bc41ae2010-11-18 19:01:18 +00007434
7435 // Dereferences are usually l-values...
7436 VK = VK_LValue;
7437
7438 // ...except that certain expressions are never l-values in C.
7439 if (!S.getLangOptions().CPlusPlus &&
7440 IsCForbiddenLValueType(S.Context, Result))
7441 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007442
7443 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007444}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007445
John McCalle3027922010-08-25 11:45:40 +00007446static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007447 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007448 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007449 switch (Kind) {
7450 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007451 case tok::periodstar: Opc = BO_PtrMemD; break;
7452 case tok::arrowstar: Opc = BO_PtrMemI; break;
7453 case tok::star: Opc = BO_Mul; break;
7454 case tok::slash: Opc = BO_Div; break;
7455 case tok::percent: Opc = BO_Rem; break;
7456 case tok::plus: Opc = BO_Add; break;
7457 case tok::minus: Opc = BO_Sub; break;
7458 case tok::lessless: Opc = BO_Shl; break;
7459 case tok::greatergreater: Opc = BO_Shr; break;
7460 case tok::lessequal: Opc = BO_LE; break;
7461 case tok::less: Opc = BO_LT; break;
7462 case tok::greaterequal: Opc = BO_GE; break;
7463 case tok::greater: Opc = BO_GT; break;
7464 case tok::exclaimequal: Opc = BO_NE; break;
7465 case tok::equalequal: Opc = BO_EQ; break;
7466 case tok::amp: Opc = BO_And; break;
7467 case tok::caret: Opc = BO_Xor; break;
7468 case tok::pipe: Opc = BO_Or; break;
7469 case tok::ampamp: Opc = BO_LAnd; break;
7470 case tok::pipepipe: Opc = BO_LOr; break;
7471 case tok::equal: Opc = BO_Assign; break;
7472 case tok::starequal: Opc = BO_MulAssign; break;
7473 case tok::slashequal: Opc = BO_DivAssign; break;
7474 case tok::percentequal: Opc = BO_RemAssign; break;
7475 case tok::plusequal: Opc = BO_AddAssign; break;
7476 case tok::minusequal: Opc = BO_SubAssign; break;
7477 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7478 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7479 case tok::ampequal: Opc = BO_AndAssign; break;
7480 case tok::caretequal: Opc = BO_XorAssign; break;
7481 case tok::pipeequal: Opc = BO_OrAssign; break;
7482 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007483 }
7484 return Opc;
7485}
7486
John McCalle3027922010-08-25 11:45:40 +00007487static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007488 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007489 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007490 switch (Kind) {
7491 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007492 case tok::plusplus: Opc = UO_PreInc; break;
7493 case tok::minusminus: Opc = UO_PreDec; break;
7494 case tok::amp: Opc = UO_AddrOf; break;
7495 case tok::star: Opc = UO_Deref; break;
7496 case tok::plus: Opc = UO_Plus; break;
7497 case tok::minus: Opc = UO_Minus; break;
7498 case tok::tilde: Opc = UO_Not; break;
7499 case tok::exclaim: Opc = UO_LNot; break;
7500 case tok::kw___real: Opc = UO_Real; break;
7501 case tok::kw___imag: Opc = UO_Imag; break;
7502 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007503 }
7504 return Opc;
7505}
7506
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007507/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7508/// This warning is only emitted for builtin assignment operations. It is also
7509/// suppressed in the event of macro expansions.
7510static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7511 SourceLocation OpLoc) {
7512 if (!S.ActiveTemplateInstantiations.empty())
7513 return;
7514 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7515 return;
7516 lhs = lhs->IgnoreParenImpCasts();
7517 rhs = rhs->IgnoreParenImpCasts();
7518 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7519 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7520 if (!LeftDeclRef || !RightDeclRef ||
7521 LeftDeclRef->getLocation().isMacroID() ||
7522 RightDeclRef->getLocation().isMacroID())
7523 return;
7524 const ValueDecl *LeftDecl =
7525 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7526 const ValueDecl *RightDecl =
7527 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7528 if (LeftDecl != RightDecl)
7529 return;
7530 if (LeftDecl->getType().isVolatileQualified())
7531 return;
7532 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7533 if (RefTy->getPointeeType().isVolatileQualified())
7534 return;
7535
7536 S.Diag(OpLoc, diag::warn_self_assignment)
7537 << LeftDeclRef->getType()
7538 << lhs->getSourceRange() << rhs->getSourceRange();
7539}
7540
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007541/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7542/// operator @p Opc at location @c TokLoc. This routine only supports
7543/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007544ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007545 BinaryOperatorKind Opc,
John McCalle3027922010-08-25 11:45:40 +00007546 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007547 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007548 // The following two variables are used for compound assignment operators
7549 QualType CompLHSTy; // Type of LHS after promotions for computation
7550 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007551 ExprValueKind VK = VK_RValue;
7552 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007553
7554 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007555 case BO_Assign:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007556 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007557 if (getLangOptions().CPlusPlus &&
7558 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall4bc41ae2010-11-18 19:01:18 +00007559 VK = lhs->getValueKind();
7560 OK = lhs->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007561 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007562 if (!ResultTy.isNull())
7563 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007564 break;
John McCalle3027922010-08-25 11:45:40 +00007565 case BO_PtrMemD:
7566 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007567 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007568 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007569 break;
John McCalle3027922010-08-25 11:45:40 +00007570 case BO_Mul:
7571 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007572 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007573 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007574 break;
John McCalle3027922010-08-25 11:45:40 +00007575 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007576 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7577 break;
John McCalle3027922010-08-25 11:45:40 +00007578 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007579 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7580 break;
John McCalle3027922010-08-25 11:45:40 +00007581 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007582 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7583 break;
John McCalle3027922010-08-25 11:45:40 +00007584 case BO_Shl:
7585 case BO_Shr:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007586 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
7587 break;
John McCalle3027922010-08-25 11:45:40 +00007588 case BO_LE:
7589 case BO_LT:
7590 case BO_GE:
7591 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007592 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007593 break;
John McCalle3027922010-08-25 11:45:40 +00007594 case BO_EQ:
7595 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007596 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007597 break;
John McCalle3027922010-08-25 11:45:40 +00007598 case BO_And:
7599 case BO_Xor:
7600 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007601 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7602 break;
John McCalle3027922010-08-25 11:45:40 +00007603 case BO_LAnd:
7604 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007605 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007606 break;
John McCalle3027922010-08-25 11:45:40 +00007607 case BO_MulAssign:
7608 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007609 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007610 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007611 CompLHSTy = CompResultTy;
7612 if (!CompResultTy.isNull())
7613 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007614 break;
John McCalle3027922010-08-25 11:45:40 +00007615 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007616 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7617 CompLHSTy = CompResultTy;
7618 if (!CompResultTy.isNull())
7619 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007620 break;
John McCalle3027922010-08-25 11:45:40 +00007621 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007622 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7623 if (!CompResultTy.isNull())
7624 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007625 break;
John McCalle3027922010-08-25 11:45:40 +00007626 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007627 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7628 if (!CompResultTy.isNull())
7629 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007630 break;
John McCalle3027922010-08-25 11:45:40 +00007631 case BO_ShlAssign:
7632 case BO_ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007633 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
7634 CompLHSTy = CompResultTy;
7635 if (!CompResultTy.isNull())
7636 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007637 break;
John McCalle3027922010-08-25 11:45:40 +00007638 case BO_AndAssign:
7639 case BO_XorAssign:
7640 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007641 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7642 CompLHSTy = CompResultTy;
7643 if (!CompResultTy.isNull())
7644 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007645 break;
John McCalle3027922010-08-25 11:45:40 +00007646 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007647 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCall7decc9e2010-11-18 06:31:45 +00007648 if (getLangOptions().CPlusPlus) {
7649 VK = rhs->getValueKind();
7650 OK = rhs->getObjectKind();
7651 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007652 break;
7653 }
7654 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007655 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007656 if (CompResultTy.isNull())
John McCall7decc9e2010-11-18 06:31:45 +00007657 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
7658 VK, OK, OpLoc));
7659
John McCall34376a62010-12-04 03:47:34 +00007660 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007661 VK = VK_LValue;
7662 OK = lhs->getObjectKind();
7663 }
7664 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
7665 VK, OK, CompLHSTy,
7666 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007667}
7668
Sebastian Redl44615072009-10-27 12:10:02 +00007669/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
7670/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007671static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7672 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007673 const PartialDiagnostic &FirstNote,
7674 SourceRange FirstParenRange,
7675 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00007676 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007677 Self.Diag(Loc, PD);
7678
7679 if (!FirstNote.getDiagID())
7680 return;
7681
7682 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
7683 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7684 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007685 return;
7686 }
7687
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007688 Self.Diag(Loc, FirstNote)
7689 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00007690 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007691
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007692 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007693 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007694
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007695 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
7696 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7697 // We can't display the parentheses, so just dig the
7698 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007699 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007700 return;
7701 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007702
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007703 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00007704 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
7705 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007706}
7707
Sebastian Redl44615072009-10-27 12:10:02 +00007708/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7709/// operators are mixed in a way that suggests that the programmer forgot that
7710/// comparison operators have higher precedence. The most typical example of
7711/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007712static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007713 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007714 typedef BinaryOperator BinOp;
7715 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7716 rhsopc = static_cast<BinOp::Opcode>(-1);
7717 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007718 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007719 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007720 rhsopc = BO->getOpcode();
7721
7722 // Subs are not binary operators.
7723 if (lhsopc == -1 && rhsopc == -1)
7724 return;
7725
7726 // Bitwise operations are sometimes used as eager logical ops.
7727 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007728 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7729 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007730 return;
7731
Sebastian Redl44615072009-10-27 12:10:02 +00007732 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007733 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007734 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00007735 << SourceRange(lhs->getLocStart(), OpLoc)
7736 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00007737 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007738 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007739 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
7740 Self.PDiag(diag::note_precedence_bitwise_silence)
7741 << BinOp::getOpcodeStr(lhsopc),
7742 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00007743 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007744 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007745 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00007746 << SourceRange(OpLoc, rhs->getLocEnd())
7747 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00007748 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007749 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007750 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
7751 Self.PDiag(diag::note_precedence_bitwise_silence)
7752 << BinOp::getOpcodeStr(rhsopc),
7753 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00007754}
7755
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007756/// \brief It accepts a '&&' expr that is inside a '||' one.
7757/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7758/// in parentheses.
7759static void
7760EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
7761 Expr *E) {
7762 assert(isa<BinaryOperator>(E) &&
7763 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
7764 SuggestParentheses(Self, OpLoc,
7765 Self.PDiag(diag::warn_logical_and_in_logical_or)
7766 << E->getSourceRange(),
7767 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
7768 E->getSourceRange(),
7769 Self.PDiag(0), SourceRange());
7770}
7771
7772/// \brief Returns true if the given expression can be evaluated as a constant
7773/// 'true'.
7774static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7775 bool Res;
7776 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7777}
7778
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007779/// \brief Returns true if the given expression can be evaluated as a constant
7780/// 'false'.
7781static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7782 bool Res;
7783 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7784}
7785
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007786/// \brief Look for '&&' in the left hand of a '||' expr.
7787static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007788 Expr *OrLHS, Expr *OrRHS) {
7789 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007790 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007791 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7792 if (EvaluatesAsFalse(S, OrRHS))
7793 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007794 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7795 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7796 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7797 } else if (Bop->getOpcode() == BO_LOr) {
7798 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7799 // If it's "a || b && 1 || c" we didn't warn earlier for
7800 // "a || b && 1", but warn now.
7801 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7802 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7803 }
7804 }
7805 }
7806}
7807
7808/// \brief Look for '&&' in the right hand of a '||' expr.
7809static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007810 Expr *OrLHS, Expr *OrRHS) {
7811 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007812 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007813 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7814 if (EvaluatesAsFalse(S, OrLHS))
7815 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007816 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7817 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7818 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007819 }
7820 }
7821}
7822
Sebastian Redl43028242009-10-26 15:24:15 +00007823/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007824/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007825static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007826 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007827 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007828 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007829 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7830
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007831 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7832 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007833 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007834 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7835 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007836 }
Sebastian Redl43028242009-10-26 15:24:15 +00007837}
7838
Steve Naroff218bc2b2007-05-04 21:54:46 +00007839// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007840ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00007841 tok::TokenKind Kind,
7842 Expr *lhs, Expr *rhs) {
7843 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00007844 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7845 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00007846
Sebastian Redl43028242009-10-26 15:24:15 +00007847 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7848 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7849
Douglas Gregor5287f092009-11-05 00:51:44 +00007850 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7851}
7852
John McCalldadc5752010-08-24 06:29:42 +00007853ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007854 BinaryOperatorKind Opc,
7855 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00007856 if (getLangOptions().CPlusPlus) {
7857 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007858
John McCall622114c2010-12-06 05:26:58 +00007859 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7860 UseBuiltinOperator = false;
7861 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7862 UseBuiltinOperator = true;
7863 } else {
7864 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7865 !rhs->getType()->isOverloadableType();
7866 }
7867
7868 if (!UseBuiltinOperator) {
7869 // Find all of the overloaded operators visible from this
7870 // point. We perform both an operator-name lookup from the local
7871 // scope and an argument-dependent lookup based on the types of
7872 // the arguments.
7873 UnresolvedSet<16> Functions;
7874 OverloadedOperatorKind OverOp
7875 = BinaryOperator::getOverloadedOperator(Opc);
7876 if (S && OverOp != OO_None)
7877 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7878 Functions);
7879
7880 // Build the (potentially-overloaded, potentially-dependent)
7881 // binary operation.
7882 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7883 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00007884 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007885
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007886 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00007887 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007888}
7889
John McCalldadc5752010-08-24 06:29:42 +00007890ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007891 UnaryOperatorKind Opc,
John McCall36226622010-10-12 02:09:17 +00007892 Expr *Input) {
John McCall7decc9e2010-11-18 06:31:45 +00007893 ExprValueKind VK = VK_RValue;
7894 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00007895 QualType resultType;
7896 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007897 case UO_PreInc:
7898 case UO_PreDec:
7899 case UO_PostInc:
7900 case UO_PostDec:
John McCall4bc41ae2010-11-18 19:01:18 +00007901 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007902 Opc == UO_PreInc ||
7903 Opc == UO_PostInc,
7904 Opc == UO_PreInc ||
7905 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00007906 break;
John McCalle3027922010-08-25 11:45:40 +00007907 case UO_AddrOf:
John McCall4bc41ae2010-11-18 19:01:18 +00007908 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007909 break;
John McCalle3027922010-08-25 11:45:40 +00007910 case UO_Deref:
Douglas Gregorb92a1562010-02-03 00:27:59 +00007911 DefaultFunctionArrayLvalueConversion(Input);
John McCall4bc41ae2010-11-18 19:01:18 +00007912 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007913 break;
John McCalle3027922010-08-25 11:45:40 +00007914 case UO_Plus:
7915 case UO_Minus:
Steve Naroff31090012007-07-16 21:54:35 +00007916 UsualUnaryConversions(Input);
7917 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007918 if (resultType->isDependentType())
7919 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00007920 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7921 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00007922 break;
7923 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7924 resultType->isEnumeralType())
7925 break;
7926 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00007927 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00007928 resultType->isPointerType())
7929 break;
John McCall36226622010-10-12 02:09:17 +00007930 else if (resultType->isPlaceholderType()) {
7931 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7932 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007933 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00007934 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007935
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007936 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7937 << resultType << Input->getSourceRange());
John McCalle3027922010-08-25 11:45:40 +00007938 case UO_Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00007939 UsualUnaryConversions(Input);
7940 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007941 if (resultType->isDependentType())
7942 break;
Chris Lattner0d707612008-07-25 23:52:49 +00007943 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
7944 if (resultType->isComplexType() || resultType->isComplexIntegerType())
7945 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00007946 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007947 << resultType << Input->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007948 else if (resultType->hasIntegerRepresentation())
7949 break;
7950 else if (resultType->isPlaceholderType()) {
7951 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7952 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007953 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00007954 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007955 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7956 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007957 }
Steve Naroff35d85152007-05-07 00:24:15 +00007958 break;
John McCalle3027922010-08-25 11:45:40 +00007959 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00007960 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00007961 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00007962 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007963 if (resultType->isDependentType())
7964 break;
John McCall36226622010-10-12 02:09:17 +00007965 if (resultType->isScalarType()) { // C99 6.5.3.3p1
7966 // ok, fallthrough
7967 } else if (resultType->isPlaceholderType()) {
7968 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7969 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007970 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00007971 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007972 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7973 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007974 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00007975
Chris Lattnerbe31ed82007-06-02 19:11:33 +00007976 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007977 // In C++, it's bool. C++ 5.3.1p8
7978 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00007979 break;
John McCalle3027922010-08-25 11:45:40 +00007980 case UO_Real:
7981 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00007982 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00007983 // _Real and _Imag map ordinary l-values into ordinary l-values.
7984 if (Input->getValueKind() != VK_RValue &&
7985 Input->getObjectKind() == OK_Ordinary)
7986 VK = Input->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00007987 break;
John McCalle3027922010-08-25 11:45:40 +00007988 case UO_Extension:
Chris Lattner86554282007-06-08 22:32:33 +00007989 resultType = Input->getType();
John McCall7decc9e2010-11-18 06:31:45 +00007990 VK = Input->getValueKind();
7991 OK = Input->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00007992 break;
Steve Naroff35d85152007-05-07 00:24:15 +00007993 }
7994 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007995 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00007996
John McCall7decc9e2010-11-18 06:31:45 +00007997 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
7998 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00007999}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008000
John McCalldadc5752010-08-24 06:29:42 +00008001ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008002 UnaryOperatorKind Opc,
8003 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008004 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008005 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008006 // Find all of the overloaded operators visible from this
8007 // point. We perform both an operator-name lookup from the local
8008 // scope and an argument-dependent lookup based on the types of
8009 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008010 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008011 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008012 if (S && OverOp != OO_None)
8013 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8014 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008015
John McCallb268a282010-08-23 23:25:46 +00008016 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008017 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008018
John McCallb268a282010-08-23 23:25:46 +00008019 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008020}
8021
Douglas Gregor5287f092009-11-05 00:51:44 +00008022// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008023ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008024 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008025 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008026}
8027
Steve Naroff66356bd2007-09-16 14:56:35 +00008028/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
John McCalldadc5752010-08-24 06:29:42 +00008029ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008030 SourceLocation LabLoc,
8031 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00008032 // Look up the record for this label identifier.
John McCallaab3e412010-08-25 08:40:02 +00008033 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00008034
Daniel Dunbar88402ce2008-08-04 16:51:22 +00008035 // If we haven't seen this label yet, create a forward reference. It
8036 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00008037 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00008038 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008039
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00008040 LabelDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008041 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008042 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
8043 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008044}
8045
John McCalldadc5752010-08-24 06:29:42 +00008046ExprResult
John McCallb268a282010-08-23 23:25:46 +00008047Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008048 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008049 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8050 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8051
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008052 bool isFileScope
8053 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008054 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008055 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008056
Chris Lattner366727f2007-07-24 16:58:17 +00008057 // FIXME: there are a variety of strange constraints to enforce here, for
8058 // example, it is not possible to goto into a stmt expression apparently.
8059 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008060
Chris Lattner366727f2007-07-24 16:58:17 +00008061 // If there are sub stmts in the compound stmt, take the type of the last one
8062 // as the type of the stmtexpr.
8063 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008064 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008065 if (!Compound->body_empty()) {
8066 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008067 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008068 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008069 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8070 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008071 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008072 }
8073 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008074 // Do function/array conversion on the last expression, but not
8075 // lvalue-to-rvalue. However, initialize an unqualified type.
8076 DefaultFunctionArrayConversion(LastExpr);
8077 Ty = LastExpr->getType().getUnqualifiedType();
8078
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008079 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8080 ExprResult Res = PerformCopyInitialization(
8081 InitializedEntity::InitializeResult(LPLoc,
8082 Ty,
8083 false),
8084 SourceLocation(),
8085 Owned(LastExpr));
8086 if (Res.isInvalid())
8087 return ExprError();
8088 if ((LastExpr = Res.takeAs<Expr>())) {
8089 if (!LastLabelStmt)
8090 Compound->setLastStmt(LastExpr);
8091 else
8092 LastLabelStmt->setSubStmt(LastExpr);
8093 StmtExprMayBindToTemp = true;
8094 }
8095 }
8096 }
Chris Lattner944d3062008-07-26 19:51:01 +00008097 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008098
Eli Friedmanba961a92009-03-23 00:24:07 +00008099 // FIXME: Check that expression type is complete/non-abstract; statement
8100 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008101 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8102 if (StmtExprMayBindToTemp)
8103 return MaybeBindToTemporary(ResStmtExpr);
8104 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008105}
Steve Naroff78864672007-08-01 22:05:33 +00008106
John McCalldadc5752010-08-24 06:29:42 +00008107ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008108 TypeSourceInfo *TInfo,
8109 OffsetOfComponent *CompPtr,
8110 unsigned NumComponents,
8111 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008112 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008113 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008114 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008115
Chris Lattnerf17bd422007-08-30 17:45:32 +00008116 // We must have at least one component that refers to the type, and the first
8117 // one is known to be a field designator. Verify that the ArgTy represents
8118 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008119 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008120 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8121 << ArgTy << TypeRange);
8122
8123 // Type must be complete per C99 7.17p3 because a declaring a variable
8124 // with an incomplete type would be ill-formed.
8125 if (!Dependent
8126 && RequireCompleteType(BuiltinLoc, ArgTy,
8127 PDiag(diag::err_offsetof_incomplete_type)
8128 << TypeRange))
8129 return ExprError();
8130
Chris Lattner78502cf2007-08-31 21:49:13 +00008131 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8132 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008133 // FIXME: This diagnostic isn't actually visible because the location is in
8134 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008135 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008136 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8137 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008138
8139 bool DidWarnAboutNonPOD = false;
8140 QualType CurrentType = ArgTy;
8141 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8142 llvm::SmallVector<OffsetOfNode, 4> Comps;
8143 llvm::SmallVector<Expr*, 4> Exprs;
8144 for (unsigned i = 0; i != NumComponents; ++i) {
8145 const OffsetOfComponent &OC = CompPtr[i];
8146 if (OC.isBrackets) {
8147 // Offset of an array sub-field. TODO: Should we allow vector elements?
8148 if (!CurrentType->isDependentType()) {
8149 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8150 if(!AT)
8151 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8152 << CurrentType);
8153 CurrentType = AT->getElementType();
8154 } else
8155 CurrentType = Context.DependentTy;
8156
8157 // The expression must be an integral expression.
8158 // FIXME: An integral constant expression?
8159 Expr *Idx = static_cast<Expr*>(OC.U.E);
8160 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8161 !Idx->getType()->isIntegerType())
8162 return ExprError(Diag(Idx->getLocStart(),
8163 diag::err_typecheck_subscript_not_integer)
8164 << Idx->getSourceRange());
8165
8166 // Record this array index.
8167 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8168 Exprs.push_back(Idx);
8169 continue;
8170 }
8171
8172 // Offset of a field.
8173 if (CurrentType->isDependentType()) {
8174 // We have the offset of a field, but we can't look into the dependent
8175 // type. Just record the identifier of the field.
8176 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8177 CurrentType = Context.DependentTy;
8178 continue;
8179 }
8180
8181 // We need to have a complete type to look into.
8182 if (RequireCompleteType(OC.LocStart, CurrentType,
8183 diag::err_offsetof_incomplete_type))
8184 return ExprError();
8185
8186 // Look for the designated field.
8187 const RecordType *RC = CurrentType->getAs<RecordType>();
8188 if (!RC)
8189 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8190 << CurrentType);
8191 RecordDecl *RD = RC->getDecl();
8192
8193 // C++ [lib.support.types]p5:
8194 // The macro offsetof accepts a restricted set of type arguments in this
8195 // International Standard. type shall be a POD structure or a POD union
8196 // (clause 9).
8197 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8198 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8199 DiagRuntimeBehavior(BuiltinLoc,
8200 PDiag(diag::warn_offsetof_non_pod_type)
8201 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8202 << CurrentType))
8203 DidWarnAboutNonPOD = true;
8204 }
8205
8206 // Look for the field.
8207 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8208 LookupQualifiedName(R, RD);
8209 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008210 IndirectFieldDecl *IndirectMemberDecl = 0;
8211 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008212 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008213 MemberDecl = IndirectMemberDecl->getAnonField();
8214 }
8215
Douglas Gregor882211c2010-04-28 22:16:22 +00008216 if (!MemberDecl)
8217 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8218 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8219 OC.LocEnd));
8220
Douglas Gregor10982ea2010-04-28 22:36:06 +00008221 // C99 7.17p3:
8222 // (If the specified member is a bit-field, the behavior is undefined.)
8223 //
8224 // We diagnose this as an error.
8225 if (MemberDecl->getBitWidth()) {
8226 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8227 << MemberDecl->getDeclName()
8228 << SourceRange(BuiltinLoc, RParenLoc);
8229 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8230 return ExprError();
8231 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008232
8233 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008234 if (IndirectMemberDecl)
8235 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008236
Douglas Gregord1702062010-04-29 00:18:15 +00008237 // If the member was found in a base class, introduce OffsetOfNodes for
8238 // the base class indirections.
8239 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8240 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008241 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008242 CXXBasePath &Path = Paths.front();
8243 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8244 B != BEnd; ++B)
8245 Comps.push_back(OffsetOfNode(B->Base));
8246 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008247
Francois Pichet783dd6e2010-11-21 06:08:52 +00008248 if (IndirectMemberDecl) {
8249 for (IndirectFieldDecl::chain_iterator FI =
8250 IndirectMemberDecl->chain_begin(),
8251 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8252 assert(isa<FieldDecl>(*FI));
8253 Comps.push_back(OffsetOfNode(OC.LocStart,
8254 cast<FieldDecl>(*FI), OC.LocEnd));
8255 }
8256 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008257 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008258
Douglas Gregor882211c2010-04-28 22:16:22 +00008259 CurrentType = MemberDecl->getType().getNonReferenceType();
8260 }
8261
8262 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8263 TInfo, Comps.data(), Comps.size(),
8264 Exprs.data(), Exprs.size(), RParenLoc));
8265}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008266
John McCalldadc5752010-08-24 06:29:42 +00008267ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008268 SourceLocation BuiltinLoc,
8269 SourceLocation TypeLoc,
8270 ParsedType argty,
8271 OffsetOfComponent *CompPtr,
8272 unsigned NumComponents,
8273 SourceLocation RPLoc) {
8274
Douglas Gregor882211c2010-04-28 22:16:22 +00008275 TypeSourceInfo *ArgTInfo;
8276 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8277 if (ArgTy.isNull())
8278 return ExprError();
8279
Eli Friedman06dcfd92010-08-05 10:15:45 +00008280 if (!ArgTInfo)
8281 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8282
8283 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8284 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008285}
8286
8287
John McCalldadc5752010-08-24 06:29:42 +00008288ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008289 Expr *CondExpr,
8290 Expr *LHSExpr, Expr *RHSExpr,
8291 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008292 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8293
John McCall7decc9e2010-11-18 06:31:45 +00008294 ExprValueKind VK = VK_RValue;
8295 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008296 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008297 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008298 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008299 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008300 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008301 } else {
8302 // The conditional expression is required to be a constant expression.
8303 llvm::APSInt condEval(32);
8304 SourceLocation ExpLoc;
8305 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008306 return ExprError(Diag(ExpLoc,
8307 diag::err_typecheck_choose_expr_requires_constant)
8308 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008309
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008310 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008311 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8312
8313 resType = ActiveExpr->getType();
8314 ValueDependent = ActiveExpr->isValueDependent();
8315 VK = ActiveExpr->getValueKind();
8316 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008317 }
8318
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008319 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008320 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008321 resType->isDependentType(),
8322 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008323}
8324
Steve Naroffc540d662008-09-03 18:15:37 +00008325//===----------------------------------------------------------------------===//
8326// Clang Extensions.
8327//===----------------------------------------------------------------------===//
8328
8329/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008330void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008331 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8332 PushBlockScope(BlockScope, Block);
8333 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008334 if (BlockScope)
8335 PushDeclContext(BlockScope, Block);
8336 else
8337 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008338}
8339
Mike Stump82f071f2009-02-04 22:31:32 +00008340void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008341 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008342 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008343 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008344
John McCall8cb7bdf2010-06-04 23:28:52 +00008345 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008346 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008347
John McCall3882ace2011-01-05 12:14:39 +00008348 // GetTypeForDeclarator always produces a function type for a block
8349 // literal signature. Furthermore, it is always a FunctionProtoType
8350 // unless the function was written with a typedef.
8351 assert(T->isFunctionType() &&
8352 "GetTypeForDeclarator made a non-function block signature");
8353
8354 // Look for an explicit signature in that function type.
8355 FunctionProtoTypeLoc ExplicitSignature;
8356
8357 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8358 if (isa<FunctionProtoTypeLoc>(tmp)) {
8359 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8360
8361 // Check whether that explicit signature was synthesized by
8362 // GetTypeForDeclarator. If so, don't save that as part of the
8363 // written signature.
8364 if (ExplicitSignature.getLParenLoc() ==
8365 ExplicitSignature.getRParenLoc()) {
8366 // This would be much cheaper if we stored TypeLocs instead of
8367 // TypeSourceInfos.
8368 TypeLoc Result = ExplicitSignature.getResultLoc();
8369 unsigned Size = Result.getFullDataSize();
8370 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8371 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8372
8373 ExplicitSignature = FunctionProtoTypeLoc();
8374 }
John McCalla3ccba02010-06-04 11:21:44 +00008375 }
Mike Stump11289f42009-09-09 15:08:12 +00008376
John McCall3882ace2011-01-05 12:14:39 +00008377 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8378 CurBlock->FunctionType = T;
8379
8380 const FunctionType *Fn = T->getAs<FunctionType>();
8381 QualType RetTy = Fn->getResultType();
8382 bool isVariadic =
8383 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8384
John McCall8e346702010-06-04 19:02:56 +00008385 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008386
John McCalla3ccba02010-06-04 11:21:44 +00008387 // Don't allow returning a objc interface by value.
8388 if (RetTy->isObjCObjectType()) {
8389 Diag(ParamInfo.getSourceRange().getBegin(),
8390 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8391 return;
8392 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008393
John McCalla3ccba02010-06-04 11:21:44 +00008394 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008395 // return type. TODO: what should we do with declarators like:
8396 // ^ * { ... }
8397 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008398 if (RetTy != Context.DependentTy)
8399 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008400
John McCalla3ccba02010-06-04 11:21:44 +00008401 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00008402 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008403 if (ExplicitSignature) {
8404 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8405 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008406 if (Param->getIdentifier() == 0 &&
8407 !Param->isImplicit() &&
8408 !Param->isInvalidDecl() &&
8409 !getLangOptions().CPlusPlus)
8410 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008411 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008412 }
John McCalla3ccba02010-06-04 11:21:44 +00008413
8414 // Fake up parameter variables if we have a typedef, like
8415 // ^ fntype { ... }
8416 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8417 for (FunctionProtoType::arg_type_iterator
8418 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8419 ParmVarDecl *Param =
8420 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8421 ParamInfo.getSourceRange().getBegin(),
8422 *I);
John McCall8e346702010-06-04 19:02:56 +00008423 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008424 }
Steve Naroffc540d662008-09-03 18:15:37 +00008425 }
John McCalla3ccba02010-06-04 11:21:44 +00008426
John McCall8e346702010-06-04 19:02:56 +00008427 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008428 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008429 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008430 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8431 CurBlock->TheDecl->param_end(),
8432 /*CheckParameterNames=*/false);
8433 }
8434
John McCalla3ccba02010-06-04 11:21:44 +00008435 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008436 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008437
John McCall8e346702010-06-04 19:02:56 +00008438 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008439 Diag(ParamInfo.getAttributes()->getLoc(),
8440 diag::warn_attribute_sentinel_not_variadic) << 1;
8441 // FIXME: remove the attribute.
8442 }
8443
8444 // Put the parameter variables in scope. We can bail out immediately
8445 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008446 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008447 return;
8448
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008449 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008450 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8451 (*AI)->setOwningFunction(CurBlock->TheDecl);
8452
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008453 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008454 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008455 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008456
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008457 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008458 }
John McCallf7b2fb52010-01-22 00:28:27 +00008459 }
Steve Naroffc540d662008-09-03 18:15:37 +00008460}
8461
8462/// ActOnBlockError - If there is an error parsing a block, this callback
8463/// is invoked to pop the information about the block from the action impl.
8464void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008465 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008466 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008467 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008468}
8469
8470/// ActOnBlockStmtExpr - This is called when the body of a block statement
8471/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008472ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
John McCallb268a282010-08-23 23:25:46 +00008473 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008474 // If blocks are disabled, emit an error.
8475 if (!LangOpts.Blocks)
8476 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008477
Douglas Gregor9a28e842010-03-01 23:15:13 +00008478 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008479
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008480 PopDeclContext();
8481
Steve Naroffc540d662008-09-03 18:15:37 +00008482 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008483 if (!BSI->ReturnType.isNull())
8484 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008485
Mike Stump3bf1ab42009-07-28 22:04:01 +00008486 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008487 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008488
8489 // If the user wrote a function type in some form, try to use that.
8490 if (!BSI->FunctionType.isNull()) {
8491 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8492
8493 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8494 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8495
8496 // Turn protoless block types into nullary block types.
8497 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008498 FunctionProtoType::ExtProtoInfo EPI;
8499 EPI.ExtInfo = Ext;
8500 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008501
8502 // Otherwise, if we don't need to change anything about the function type,
8503 // preserve its sugar structure.
8504 } else if (FTy->getResultType() == RetTy &&
8505 (!NoReturn || FTy->getNoReturnAttr())) {
8506 BlockTy = BSI->FunctionType;
8507
8508 // Otherwise, make the minimal modifications to the function type.
8509 } else {
8510 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008511 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8512 EPI.TypeQuals = 0; // FIXME: silently?
8513 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008514 BlockTy = Context.getFunctionType(RetTy,
8515 FPT->arg_type_begin(),
8516 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008517 EPI);
John McCall8e346702010-06-04 19:02:56 +00008518 }
8519
8520 // If we don't have a function type, just build one from nothing.
8521 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008522 FunctionProtoType::ExtProtoInfo EPI;
8523 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
8524 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008525 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008526
John McCall8e346702010-06-04 19:02:56 +00008527 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8528 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008529 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008530
Chris Lattner45542ea2009-04-19 05:28:12 +00008531 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00008532 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008533 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008534
John McCallb268a282010-08-23 23:25:46 +00008535 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Mike Stump314825b2010-01-19 23:08:01 +00008536
8537 bool Good = true;
8538 // Check goto/label use.
8539 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
8540 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
8541 LabelStmt *L = I->second;
8542
8543 // Verify that we have no forward references left. If so, there was a goto
8544 // or address of a label taken, but no definition of it.
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00008545 if (L->getSubStmt() != 0) {
8546 if (!L->isUsed())
8547 Diag(L->getIdentLoc(), diag::warn_unused_label) << L->getName();
Mike Stump314825b2010-01-19 23:08:01 +00008548 continue;
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00008549 }
Mike Stump314825b2010-01-19 23:08:01 +00008550
8551 // Emit error.
8552 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
8553 Good = false;
8554 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00008555 if (!Good) {
8556 PopFunctionOrBlockScope();
Mike Stump314825b2010-01-19 23:08:01 +00008557 return ExprError();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008558 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008559
John McCall1d570a72010-08-25 05:56:39 +00008560 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
8561 BSI->hasBlockDeclRefExprs);
8562
Ted Kremenek918fe842010-03-20 21:06:02 +00008563 // Issue any analysis-based warnings.
Ted Kremenek0b405322010-03-23 00:13:23 +00008564 const sema::AnalysisBasedWarnings::Policy &WP =
8565 AnalysisWarnings.getDefaultPolicy();
John McCall1d570a72010-08-25 05:56:39 +00008566 AnalysisWarnings.IssueWarnings(WP, Result);
Ted Kremenek918fe842010-03-20 21:06:02 +00008567
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008568 PopFunctionOrBlockScope();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008569 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008570}
8571
John McCalldadc5752010-08-24 06:29:42 +00008572ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008573 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008574 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008575 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008576 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008577 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008578}
8579
John McCalldadc5752010-08-24 06:29:42 +00008580ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008581 Expr *E, TypeSourceInfo *TInfo,
8582 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008583 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008584
Eli Friedman121ba0c2008-08-09 23:32:40 +00008585 // Get the va_list type
8586 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008587 if (VaListType->isArrayType()) {
8588 // Deal with implicit array decay; for example, on x86-64,
8589 // va_list is an array, but it's supposed to decay to
8590 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008591 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008592 // Make sure the input expression also decays appropriately.
8593 UsualUnaryConversions(E);
8594 } else {
8595 // Otherwise, the va_list argument must be an l-value because
8596 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008597 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008598 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008599 return ExprError();
8600 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008601
Douglas Gregorad3150c2009-05-19 23:10:31 +00008602 if (!E->isTypeDependent() &&
8603 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008604 return ExprError(Diag(E->getLocStart(),
8605 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008606 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008607 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008608
Eli Friedmanba961a92009-03-23 00:24:07 +00008609 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008610 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008611
Abramo Bagnara27db2392010-08-10 10:06:15 +00008612 QualType T = TInfo->getType().getNonLValueExprType(Context);
8613 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008614}
8615
John McCalldadc5752010-08-24 06:29:42 +00008616ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008617 // The type of __null will be int or long, depending on the size of
8618 // pointers on the target.
8619 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008620 unsigned pw = Context.Target.getPointerWidth(0);
8621 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008622 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008623 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008624 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008625 else if (pw == Context.Target.getLongLongWidth())
8626 Ty = Context.LongLongTy;
8627 else {
8628 assert(!"I don't know size of pointer!");
8629 Ty = Context.IntTy;
8630 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008631
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008632 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008633}
8634
Alexis Huntc46382e2010-04-28 23:02:27 +00008635static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008636 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008637 if (!SemaRef.getLangOptions().ObjC1)
8638 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008639
Anders Carlssonace5d072009-11-10 04:46:30 +00008640 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8641 if (!PT)
8642 return;
8643
8644 // Check if the destination is of type 'id'.
8645 if (!PT->isObjCIdType()) {
8646 // Check if the destination is the 'NSString' interface.
8647 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8648 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8649 return;
8650 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008651
Anders Carlssonace5d072009-11-10 04:46:30 +00008652 // Strip off any parens and casts.
8653 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8654 if (!SL || SL->isWide())
8655 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008656
Douglas Gregora771f462010-03-31 17:46:05 +00008657 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008658}
8659
Chris Lattner9bad62c2008-01-04 18:04:52 +00008660bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8661 SourceLocation Loc,
8662 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008663 Expr *SrcExpr, AssignmentAction Action,
8664 bool *Complained) {
8665 if (Complained)
8666 *Complained = false;
8667
Chris Lattner9bad62c2008-01-04 18:04:52 +00008668 // Decode the result (notice that AST's are still created for extensions).
8669 bool isInvalid = false;
8670 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008671 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008672
Chris Lattner9bad62c2008-01-04 18:04:52 +00008673 switch (ConvTy) {
8674 default: assert(0 && "Unknown conversion type");
8675 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008676 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008677 DiagKind = diag::ext_typecheck_convert_pointer_int;
8678 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008679 case IntToPointer:
8680 DiagKind = diag::ext_typecheck_convert_int_pointer;
8681 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008682 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008683 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008684 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
8685 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008686 case IncompatiblePointerSign:
8687 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8688 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008689 case FunctionVoidPointer:
8690 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8691 break;
John McCall4fff8f62011-02-01 00:10:29 +00008692 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00008693 // Perform array-to-pointer decay if necessary.
8694 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8695
John McCall4fff8f62011-02-01 00:10:29 +00008696 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8697 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8698 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8699 DiagKind = diag::err_typecheck_incompatible_address_space;
8700 break;
8701 }
8702
8703 llvm_unreachable("unknown error case for discarding qualifiers!");
8704 // fallthrough
8705 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008706 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008707 // If the qualifiers lost were because we were applying the
8708 // (deprecated) C++ conversion from a string literal to a char*
8709 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8710 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00008711 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008712 // bit of refactoring (so that the second argument is an
8713 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00008714 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008715 // C++ semantics.
8716 if (getLangOptions().CPlusPlus &&
8717 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8718 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008719 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8720 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008721 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008722 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008723 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008724 case IntToBlockPointer:
8725 DiagKind = diag::err_int_to_block_pointer;
8726 break;
8727 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008728 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008729 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008730 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008731 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008732 // it can give a more specific diagnostic.
8733 DiagKind = diag::warn_incompatible_qualified_id;
8734 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008735 case IncompatibleVectors:
8736 DiagKind = diag::warn_incompatible_vectors;
8737 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008738 case Incompatible:
8739 DiagKind = diag::err_typecheck_convert_incompatible;
8740 isInvalid = true;
8741 break;
8742 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008743
Douglas Gregorc68e1402010-04-09 00:35:39 +00008744 QualType FirstType, SecondType;
8745 switch (Action) {
8746 case AA_Assigning:
8747 case AA_Initializing:
8748 // The destination type comes first.
8749 FirstType = DstType;
8750 SecondType = SrcType;
8751 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00008752
Douglas Gregorc68e1402010-04-09 00:35:39 +00008753 case AA_Returning:
8754 case AA_Passing:
8755 case AA_Converting:
8756 case AA_Sending:
8757 case AA_Casting:
8758 // The source type comes first.
8759 FirstType = SrcType;
8760 SecondType = DstType;
8761 break;
8762 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008763
Douglas Gregorc68e1402010-04-09 00:35:39 +00008764 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00008765 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008766 if (Complained)
8767 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008768 return isInvalid;
8769}
Anders Carlssone54e8a12008-11-30 19:50:32 +00008770
Chris Lattnerc71d08b2009-04-25 21:59:05 +00008771bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008772 llvm::APSInt ICEResult;
8773 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8774 if (Result)
8775 *Result = ICEResult;
8776 return false;
8777 }
8778
Anders Carlssone54e8a12008-11-30 19:50:32 +00008779 Expr::EvalResult EvalResult;
8780
Mike Stump4e1f26a2009-02-19 03:04:26 +00008781 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00008782 EvalResult.HasSideEffects) {
8783 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8784
8785 if (EvalResult.Diag) {
8786 // We only show the note if it's not the usual "invalid subexpression"
8787 // or if it's actually in a subexpression.
8788 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8789 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8790 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8791 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008792
Anders Carlssone54e8a12008-11-30 19:50:32 +00008793 return true;
8794 }
8795
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008796 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8797 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00008798
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008799 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008800 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
8801 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008802 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008803
Anders Carlssone54e8a12008-11-30 19:50:32 +00008804 if (Result)
8805 *Result = EvalResult.Val.getInt();
8806 return false;
8807}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008808
Douglas Gregorff790f12009-11-26 00:44:06 +00008809void
Mike Stump11289f42009-09-09 15:08:12 +00008810Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008811 ExprEvalContexts.push_back(
8812 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008813}
8814
Mike Stump11289f42009-09-09 15:08:12 +00008815void
Douglas Gregorff790f12009-11-26 00:44:06 +00008816Sema::PopExpressionEvaluationContext() {
8817 // Pop the current expression evaluation context off the stack.
8818 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8819 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008820
Douglas Gregorfab31f42009-12-12 07:57:52 +00008821 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8822 if (Rec.PotentiallyReferenced) {
8823 // Mark any remaining declarations in the current position of the stack
8824 // as "referenced". If they were not meant to be referenced, semantic
8825 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008826 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00008827 I = Rec.PotentiallyReferenced->begin(),
8828 IEnd = Rec.PotentiallyReferenced->end();
8829 I != IEnd; ++I)
8830 MarkDeclarationReferenced(I->first, I->second);
8831 }
8832
8833 if (Rec.PotentiallyDiagnosed) {
8834 // Emit any pending diagnostics.
8835 for (PotentiallyEmittedDiagnostics::iterator
8836 I = Rec.PotentiallyDiagnosed->begin(),
8837 IEnd = Rec.PotentiallyDiagnosed->end();
8838 I != IEnd; ++I)
8839 Diag(I->first, I->second);
8840 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008841 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008842
8843 // When are coming out of an unevaluated context, clear out any
8844 // temporaries that we may have created as part of the evaluation of
8845 // the expression in that context: they aren't relevant because they
8846 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008847 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00008848 ExprTemporaries.size() > Rec.NumTemporaries)
8849 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
8850 ExprTemporaries.end());
8851
8852 // Destroy the popped expression evaluation record.
8853 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008854}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008855
8856/// \brief Note that the given declaration was referenced in the source code.
8857///
8858/// This routine should be invoke whenever a given declaration is referenced
8859/// in the source code, and where that reference occurred. If this declaration
8860/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
8861/// C99 6.9p3), then the declaration will be marked as used.
8862///
8863/// \param Loc the location where the declaration was referenced.
8864///
8865/// \param D the declaration that has been referenced by the source code.
8866void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
8867 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00008868
Douglas Gregorebada0772010-06-17 23:14:26 +00008869 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00008870 return;
Mike Stump11289f42009-09-09 15:08:12 +00008871
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00008872 // Mark a parameter or variable declaration "used", regardless of whether we're in a
8873 // template or not. The reason for this is that unevaluated expressions
8874 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
8875 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008876 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008877 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00008878 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008879 return;
8880 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008881
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008882 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
8883 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00008884
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008885 // Do not mark anything as "used" within a dependent context; wait for
8886 // an instantiation.
8887 if (CurContext->isDependentContext())
8888 return;
Mike Stump11289f42009-09-09 15:08:12 +00008889
Douglas Gregorff790f12009-11-26 00:44:06 +00008890 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008891 case Unevaluated:
8892 // We are in an expression that is not potentially evaluated; do nothing.
8893 return;
Mike Stump11289f42009-09-09 15:08:12 +00008894
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008895 case PotentiallyEvaluated:
8896 // We are in a potentially-evaluated expression, so this declaration is
8897 // "used"; handle this below.
8898 break;
Mike Stump11289f42009-09-09 15:08:12 +00008899
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008900 case PotentiallyPotentiallyEvaluated:
8901 // We are in an expression that may be potentially evaluated; queue this
8902 // declaration reference until we know whether the expression is
8903 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00008904 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008905 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008906
8907 case PotentiallyEvaluatedIfUsed:
8908 // Referenced declarations will only be used if the construct in the
8909 // containing expression is used.
8910 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008911 }
Mike Stump11289f42009-09-09 15:08:12 +00008912
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008913 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00008914 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008915 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008916 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00008917 if (Constructor->getParent()->hasTrivialConstructor())
8918 return;
8919 if (!Constructor->isUsed(false))
8920 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00008921 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00008922 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008923 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008924 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
8925 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008926
Douglas Gregor88d292c2010-05-13 16:44:06 +00008927 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008928 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008929 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008930 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008931 if (Destructor->isVirtual())
8932 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008933 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
8934 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
8935 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008936 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00008937 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008938 } else if (MethodDecl->isVirtual())
8939 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008940 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00008941 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00008942 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00008943 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00008944 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00008945 bool AlreadyInstantiated = false;
8946 if (FunctionTemplateSpecializationInfo *SpecInfo
8947 = Function->getTemplateSpecializationInfo()) {
8948 if (SpecInfo->getPointOfInstantiation().isInvalid())
8949 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008950 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008951 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008952 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008953 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00008954 = Function->getMemberSpecializationInfo()) {
8955 if (MSInfo->getPointOfInstantiation().isInvalid())
8956 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008957 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008958 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008959 AlreadyInstantiated = true;
8960 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008961
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008962 if (!AlreadyInstantiated) {
8963 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
8964 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
8965 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
8966 Loc));
8967 else
Chandler Carruth54080172010-08-25 08:44:16 +00008968 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008969 }
Gabor Greifb6aba3e2010-08-28 00:16:06 +00008970 } else // Walk redefinitions, as some of them may be instantiable.
8971 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
8972 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00008973 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00008974 MarkDeclarationReferenced(Loc, *i);
8975 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008976
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008977 // FIXME: keep track of references to static functions
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00008978
8979 // Recursive functions should be marked when used from another function.
8980 if (CurContext != Function)
8981 Function->setUsed(true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008982
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008983 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00008984 }
Mike Stump11289f42009-09-09 15:08:12 +00008985
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008986 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008987 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00008988 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00008989 Var->getInstantiatedFromStaticDataMember()) {
8990 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
8991 assert(MSInfo && "Missing member specialization information?");
8992 if (MSInfo->getPointOfInstantiation().isInvalid() &&
8993 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
8994 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +00008995 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00008996 }
8997 }
Mike Stump11289f42009-09-09 15:08:12 +00008998
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008999 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009000
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009001 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009002 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009003 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009004}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009005
Douglas Gregor5597ab42010-05-07 23:12:07 +00009006namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009007 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009008 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009009 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009010 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9011 Sema &S;
9012 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009013
Douglas Gregor5597ab42010-05-07 23:12:07 +00009014 public:
9015 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009016
Douglas Gregor5597ab42010-05-07 23:12:07 +00009017 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009018
9019 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9020 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009021 };
9022}
9023
Chandler Carruthaf80f662010-06-09 08:17:30 +00009024bool MarkReferencedDecls::TraverseTemplateArgument(
9025 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009026 if (Arg.getKind() == TemplateArgument::Declaration) {
9027 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9028 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009029
9030 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009031}
9032
Chandler Carruthaf80f662010-06-09 08:17:30 +00009033bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009034 if (ClassTemplateSpecializationDecl *Spec
9035 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9036 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009037 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009038 }
9039
Chandler Carruthc65667c2010-06-10 10:31:57 +00009040 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009041}
9042
9043void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9044 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009045 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009046}
9047
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009048namespace {
9049 /// \brief Helper class that marks all of the declarations referenced by
9050 /// potentially-evaluated subexpressions as "referenced".
9051 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9052 Sema &S;
9053
9054 public:
9055 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9056
9057 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9058
9059 void VisitDeclRefExpr(DeclRefExpr *E) {
9060 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9061 }
9062
9063 void VisitMemberExpr(MemberExpr *E) {
9064 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009065 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009066 }
9067
9068 void VisitCXXNewExpr(CXXNewExpr *E) {
9069 if (E->getConstructor())
9070 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9071 if (E->getOperatorNew())
9072 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9073 if (E->getOperatorDelete())
9074 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009075 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009076 }
9077
9078 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9079 if (E->getOperatorDelete())
9080 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009081 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9082 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9083 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9084 S.MarkDeclarationReferenced(E->getLocStart(),
9085 S.LookupDestructor(Record));
9086 }
9087
Douglas Gregor32b3de52010-09-11 23:32:50 +00009088 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009089 }
9090
9091 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9092 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009093 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009094 }
9095
9096 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9097 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9098 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009099
9100 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9101 Visit(E->getExpr());
9102 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009103 };
9104}
9105
9106/// \brief Mark any declarations that appear within this expression or any
9107/// potentially-evaluated subexpressions as "referenced".
9108void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9109 EvaluatedExprMarker(*this).Visit(E);
9110}
9111
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009112/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9113/// of the program being compiled.
9114///
9115/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009116/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009117/// possibility that the code will actually be executable. Code in sizeof()
9118/// expressions, code used only during overload resolution, etc., are not
9119/// potentially evaluated. This routine will suppress such diagnostics or,
9120/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009121/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009122/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009123///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009124/// This routine should be used for all diagnostics that describe the run-time
9125/// behavior of a program, such as passing a non-POD value through an ellipsis.
9126/// Failure to do so will likely result in spurious diagnostics or failures
9127/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009128bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009129 const PartialDiagnostic &PD) {
9130 switch (ExprEvalContexts.back().Context ) {
9131 case Unevaluated:
9132 // The argument will never be evaluated, so don't complain.
9133 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009134
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009135 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009136 case PotentiallyEvaluatedIfUsed:
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009137 Diag(Loc, PD);
9138 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009139
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009140 case PotentiallyPotentiallyEvaluated:
9141 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9142 break;
9143 }
9144
9145 return false;
9146}
9147
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009148bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9149 CallExpr *CE, FunctionDecl *FD) {
9150 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9151 return false;
9152
9153 PartialDiagnostic Note =
9154 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9155 << FD->getDeclName() : PDiag();
9156 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009157
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009158 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009159 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009160 PDiag(diag::err_call_function_incomplete_return)
9161 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009162 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009163 << CE->getSourceRange(),
9164 std::make_pair(NoteLoc, Note)))
9165 return true;
9166
9167 return false;
9168}
9169
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009170// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009171// will prevent this condition from triggering, which is what we want.
9172void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9173 SourceLocation Loc;
9174
John McCall0506e4a2009-11-11 02:41:58 +00009175 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009176 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009177
John McCalld5707ab2009-10-12 21:59:07 +00009178 if (isa<BinaryOperator>(E)) {
9179 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009180 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009181 return;
9182
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009183 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9184
John McCallb0e419e2009-11-12 00:06:05 +00009185 // Greylist some idioms by putting them into a warning subcategory.
9186 if (ObjCMessageExpr *ME
9187 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9188 Selector Sel = ME->getSelector();
9189
John McCallb0e419e2009-11-12 00:06:05 +00009190 // self = [<foo> init...]
9191 if (isSelfExpr(Op->getLHS())
9192 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
9193 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9194
9195 // <foo> = [<bar> nextObject]
9196 else if (Sel.isUnarySelector() &&
9197 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
9198 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9199 }
John McCall0506e4a2009-11-11 02:41:58 +00009200
John McCalld5707ab2009-10-12 21:59:07 +00009201 Loc = Op->getOperatorLoc();
9202 } else if (isa<CXXOperatorCallExpr>(E)) {
9203 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009204 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009205 return;
9206
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009207 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009208 Loc = Op->getOperatorLoc();
9209 } else {
9210 // Not an assignment.
9211 return;
9212 }
9213
John McCalld5707ab2009-10-12 21:59:07 +00009214 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00009215 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009216
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009217 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009218
9219 if (IsOrAssign)
9220 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9221 << FixItHint::CreateReplacement(Loc, "!=");
9222 else
9223 Diag(Loc, diag::note_condition_assign_to_comparison)
9224 << FixItHint::CreateReplacement(Loc, "==");
9225
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009226 Diag(Loc, diag::note_condition_assign_silence)
9227 << FixItHint::CreateInsertion(Open, "(")
9228 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +00009229}
9230
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009231/// \brief Redundant parentheses over an equality comparison can indicate
9232/// that the user intended an assignment used as condition.
9233void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009234 // Don't warn if the parens came from a macro.
9235 SourceLocation parenLoc = parenE->getLocStart();
9236 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9237 return;
9238
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009239 Expr *E = parenE->IgnoreParens();
9240
9241 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009242 if (opE->getOpcode() == BO_EQ &&
9243 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9244 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009245 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009246
9247 // Don't emit a warning if the operation occurs within a macro.
9248 // Sometimes extra parentheses are used within macros to make the
9249 // instantiation of the macro less error prone.
9250 if (!Loc.isMacroID()) {
9251 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9252 Diag(Loc, diag::note_equality_comparison_to_assign)
9253 << FixItHint::CreateReplacement(Loc, "=");
9254 Diag(Loc, diag::note_equality_comparison_silence)
9255 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9256 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
9257 }
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009258 }
9259}
9260
John McCalld5707ab2009-10-12 21:59:07 +00009261bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9262 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009263 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9264 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009265
9266 if (!E->isTypeDependent()) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009267 if (E->isBoundMemberFunction(Context))
9268 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9269 << E->getSourceRange();
9270
John McCall34376a62010-12-04 03:47:34 +00009271 if (getLangOptions().CPlusPlus)
9272 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9273
9274 DefaultFunctionArrayLvalueConversion(E);
John McCall29cb2fd2010-12-04 06:09:13 +00009275
9276 QualType T = E->getType();
John McCall34376a62010-12-04 03:47:34 +00009277 if (!T->isScalarType()) // C99 6.8.4.1p1
9278 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9279 << T << E->getSourceRange();
John McCalld5707ab2009-10-12 21:59:07 +00009280 }
9281
9282 return false;
9283}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009284
John McCalldadc5752010-08-24 06:29:42 +00009285ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9286 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009287 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009288 return ExprError();
9289
Douglas Gregorb412e172010-07-25 18:17:45 +00009290 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00009291 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00009292
9293 return Owned(Sub);
9294}
John McCall36e7fe32010-10-12 00:20:44 +00009295
9296/// Check for operands with placeholder types and complain if found.
9297/// Returns true if there was an error and no recovery was possible.
9298ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9299 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9300 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9301
9302 // If this is overload, check for a single overload.
9303 if (BT->getKind() == BuiltinType::Overload) {
9304 if (FunctionDecl *Specialization
9305 = ResolveSingleFunctionTemplateSpecialization(E)) {
9306 // The access doesn't really matter in this case.
9307 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9308 Specialization->getAccess());
9309 E = FixOverloadedFunctionReference(E, Found, Specialization);
9310 if (!E) return ExprError();
9311 return Owned(E);
9312 }
9313
John McCall36226622010-10-12 02:09:17 +00009314 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
John McCall36e7fe32010-10-12 00:20:44 +00009315 return ExprError();
9316 }
9317
9318 // Otherwise it's a use of undeduced auto.
9319 assert(BT->getKind() == BuiltinType::UndeducedAuto);
9320
9321 DeclRefExpr *DRE = cast<DeclRefExpr>(E->IgnoreParens());
9322 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
9323 << DRE->getDecl() << E->getSourceRange();
9324 return ExprError();
9325}