blob: 3c073181583ea4228383a905fb8e8da6bf217dd6 [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
John McCallc63de662011-02-02 13:00:07 +0000736enum CaptureResult {
737 /// No capture is required.
738 CR_NoCapture,
739
740 /// A capture is required.
741 CR_Capture,
742
John McCall351762c2011-02-07 10:33:21 +0000743 /// A by-ref capture is required.
744 CR_CaptureByRef,
745
John McCallc63de662011-02-02 13:00:07 +0000746 /// An error occurred when trying to capture the given variable.
747 CR_Error
748};
749
750/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +0000751///
John McCallc63de662011-02-02 13:00:07 +0000752/// \param var - the variable referenced
753/// \param DC - the context which we couldn't capture through
754static CaptureResult
John McCall351762c2011-02-07 10:33:21 +0000755diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000756 VarDecl *var, DeclContext *DC) {
757 switch (S.ExprEvalContexts.back().Context) {
758 case Sema::Unevaluated:
759 // The argument will never be evaluated, so don't complain.
760 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +0000761
John McCallc63de662011-02-02 13:00:07 +0000762 case Sema::PotentiallyEvaluated:
763 case Sema::PotentiallyEvaluatedIfUsed:
764 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +0000765
John McCallc63de662011-02-02 13:00:07 +0000766 case Sema::PotentiallyPotentiallyEvaluated:
767 // FIXME: delay these!
768 break;
Chris Lattner497d7b02009-04-21 22:26:47 +0000769 }
Mike Stump11289f42009-09-09 15:08:12 +0000770
John McCallc63de662011-02-02 13:00:07 +0000771 // Don't diagnose about capture if we're not actually in code right
772 // now; in general, there are more appropriate places that will
773 // diagnose this.
774 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
775
776 // This particular madness can happen in ill-formed default
777 // arguments; claim it's okay and let downstream code handle it.
778 if (isa<ParmVarDecl>(var) &&
779 S.CurContext == var->getDeclContext()->getParent())
780 return CR_NoCapture;
781
782 DeclarationName functionName;
783 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
784 functionName = fn->getDeclName();
785 // FIXME: variable from enclosing block that we couldn't capture from!
786
787 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
788 << var->getIdentifier() << functionName;
789 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
790 << var->getIdentifier();
791
792 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +0000793}
794
John McCall351762c2011-02-07 10:33:21 +0000795/// There is a well-formed capture at a particular scope level;
796/// propagate it through all the nested blocks.
797static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
798 const BlockDecl::Capture &capture) {
799 VarDecl *var = capture.getVariable();
800
801 // Update all the inner blocks with the capture information.
802 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
803 i != e; ++i) {
804 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
805 innerBlock->Captures.push_back(
806 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
807 /*nested*/ true, capture.getCopyExpr()));
808 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
809 }
810
811 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
812}
813
814/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +0000815/// given value in the current context requires a variable capture.
816///
817/// This also keeps the captures set in the BlockScopeInfo records
818/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +0000819static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000820 ValueDecl *value) {
821 // Only variables ever require capture.
822 VarDecl *var = dyn_cast<VarDecl>(value);
823 if (!var || isa<NonTypeTemplateParmDecl>(var)) return CR_NoCapture;
824
825 // Fast path: variables from the current context never require capture.
826 DeclContext *DC = S.CurContext;
827 if (var->getDeclContext() == DC) return CR_NoCapture;
828
829 // Only variables with local storage require capture.
830 // FIXME: What about 'const' variables in C++?
831 if (!var->hasLocalStorage()) return CR_NoCapture;
832
833 // Otherwise, we need to capture.
834
835 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +0000836 do {
837 // Only blocks (and eventually C++0x closures) can capture; other
838 // scopes don't work.
839 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +0000840 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +0000841
842 BlockScopeInfo *blockScope =
843 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
844 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
845
John McCall351762c2011-02-07 10:33:21 +0000846 // Check whether we've already captured it in this block. If so,
847 // we're done.
848 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
849 return propagateCapture(S, functionScopesIndex,
850 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +0000851
852 functionScopesIndex--;
853 DC = cast<BlockDecl>(DC)->getDeclContext();
854 } while (var->getDeclContext() != DC);
855
John McCall351762c2011-02-07 10:33:21 +0000856 // Okay, we descended all the way to the block that defines the variable.
857 // Actually try to capture it.
858 QualType type = var->getType();
859
860 // Prohibit variably-modified types.
861 if (type->isVariablyModifiedType()) {
862 S.Diag(loc, diag::err_ref_vm_type);
863 S.Diag(var->getLocation(), diag::note_declared_at);
864 return CR_Error;
865 }
866
867 // Prohibit arrays, even in __block variables, but not references to
868 // them.
869 if (type->isArrayType()) {
870 S.Diag(loc, diag::err_ref_array_type);
871 S.Diag(var->getLocation(), diag::note_declared_at);
872 return CR_Error;
873 }
874
875 S.MarkDeclarationReferenced(loc, var);
876
877 // The BlocksAttr indicates the variable is bound by-reference.
878 bool byRef = var->hasAttr<BlocksAttr>();
879
880 // Build a copy expression.
881 Expr *copyExpr = 0;
882 if (!byRef && S.getLangOptions().CPlusPlus &&
883 !type->isDependentType() && type->isStructureOrClassType()) {
884 // According to the blocks spec, the capture of a variable from
885 // the stack requires a const copy constructor. This is not true
886 // of the copy/move done to move a __block variable to the heap.
887 type.addConst();
888
889 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
890 ExprResult result =
891 S.PerformCopyInitialization(
892 InitializedEntity::InitializeBlock(var->getLocation(),
893 type, false),
894 loc, S.Owned(declRef));
895
896 // Build a full-expression copy expression if initialization
897 // succeeded and used a non-trivial constructor. Recover from
898 // errors by pretending that the copy isn't necessary.
899 if (!result.isInvalid() &&
900 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
901 result = S.MaybeCreateExprWithCleanups(result);
902 copyExpr = result.take();
903 }
904 }
905
906 // We're currently at the declarer; go back to the closure.
907 functionScopesIndex++;
908 BlockScopeInfo *blockScope =
909 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
910
911 // Build a valid capture in this scope.
912 blockScope->Captures.push_back(
913 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
914 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
915
916 // Propagate that to inner captures if necessary.
917 return propagateCapture(S, functionScopesIndex,
918 blockScope->Captures.back());
919}
920
921static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
922 const DeclarationNameInfo &NameInfo,
923 bool byRef) {
924 assert(isa<VarDecl>(vd) && "capturing non-variable");
925
926 VarDecl *var = cast<VarDecl>(vd);
927 assert(var->hasLocalStorage() && "capturing non-local");
928 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
929
930 QualType exprType = var->getType().getNonReferenceType();
931
932 BlockDeclRefExpr *BDRE;
933 if (!byRef) {
934 // The variable will be bound by copy; make it const within the
935 // closure, but record that this was done in the expression.
936 bool constAdded = !exprType.isConstQualified();
937 exprType.addConst();
938
939 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
940 NameInfo.getLoc(), false,
941 constAdded);
942 } else {
943 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
944 NameInfo.getLoc(), true);
945 }
946
947 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +0000948}
Chris Lattner2a9d9892008-10-20 05:16:36 +0000949
John McCalldadc5752010-08-24 06:29:42 +0000950ExprResult
John McCall7decc9e2010-11-18 06:31:45 +0000951Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
952 SourceLocation Loc, const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000953 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +0000954 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000955}
956
957/// BuildDeclRefExpr - Build a DeclRefExpr.
John McCalldadc5752010-08-24 06:29:42 +0000958ExprResult
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000959Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +0000960 ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000961 const DeclarationNameInfo &NameInfo,
962 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000963 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000964 Diag(NameInfo.getLoc(),
Mike Stump11289f42009-09-09 15:08:12 +0000965 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000966 << D->getDeclName();
967 return ExprError();
968 }
Mike Stump11289f42009-09-09 15:08:12 +0000969
Anders Carlsson946b86d2009-06-24 00:10:43 +0000970 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Douglas Gregor15243332010-04-27 21:10:04 +0000971 if (isa<NonTypeTemplateParmDecl>(VD)) {
972 // Non-type template parameters can be referenced anywhere they are
973 // visible.
Douglas Gregora8a089b2010-07-13 18:40:04 +0000974 Ty = Ty.getNonLValueExprType(Context);
John McCall4bc41ae2010-11-18 19:01:18 +0000975
976 // This ridiculousness brought to you by 'extern void x;' and the
977 // GNU compiler collection.
978 } else if (!getLangOptions().CPlusPlus && !Ty.hasQualifiers() &&
979 Ty->isVoidType()) {
980 VK = VK_RValue;
Anders Carlsson946b86d2009-06-24 00:10:43 +0000981 }
982 }
Mike Stump11289f42009-09-09 15:08:12 +0000983
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000984 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +0000985
John McCall086a4642010-11-24 05:12:34 +0000986 Expr *E = DeclRefExpr::Create(Context,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000987 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
John McCall086a4642010-11-24 05:12:34 +0000988 SS? SS->getRange() : SourceRange(),
989 D, NameInfo, Ty, VK);
990
991 // Just in case we're building an illegal pointer-to-member.
992 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
993 E->setObjectKind(OK_BitField);
994
995 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000996}
997
John McCallfeb624a2010-11-23 20:48:44 +0000998static ExprResult
999BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1000 const CXXScopeSpec &SS, FieldDecl *Field,
1001 DeclAccessPair FoundDecl,
1002 const DeclarationNameInfo &MemberNameInfo);
1003
John McCalldadc5752010-08-24 06:29:42 +00001004ExprResult
John McCallf3a88602011-02-03 08:15:49 +00001005Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1006 SourceLocation loc,
1007 IndirectFieldDecl *indirectField,
1008 Expr *baseObjectExpr,
1009 SourceLocation opLoc) {
1010 // First, build the expression that refers to the base object.
1011
1012 bool baseObjectIsPointer = false;
1013 Qualifiers baseQuals;
1014
1015 // Case 1: the base of the indirect field is not a field.
1016 VarDecl *baseVariable = indirectField->getVarDecl();
1017 if (baseVariable) {
1018 assert(baseVariable->getType()->isRecordType());
1019
1020 // In principle we could have a member access expression that
1021 // accesses an anonymous struct/union that's a static member of
1022 // the base object's class. However, under the current standard,
1023 // static data members cannot be anonymous structs or unions.
1024 // Supporting this is as easy as building a MemberExpr here.
1025 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1026
1027 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1028
1029 ExprResult result =
1030 BuildDeclarationNameExpr(SS, baseNameInfo, baseVariable);
1031 if (result.isInvalid()) return ExprError();
1032
1033 baseObjectExpr = result.take();
1034 baseObjectIsPointer = false;
1035 baseQuals = baseObjectExpr->getType().getQualifiers();
1036
1037 // Case 2: the base of the indirect field is a field and the user
1038 // wrote a member expression.
1039 } else if (baseObjectExpr) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001040 // The caller provided the base object expression. Determine
1041 // whether its a pointer and whether it adds any qualifiers to the
1042 // anonymous struct/union fields we're looking into.
John McCallf3a88602011-02-03 08:15:49 +00001043 QualType objectType = baseObjectExpr->getType();
1044
1045 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1046 baseObjectIsPointer = true;
1047 objectType = ptr->getPointeeType();
1048 } else {
1049 baseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001050 }
John McCallf3a88602011-02-03 08:15:49 +00001051 baseQuals = objectType.getQualifiers();
1052
1053 // Case 3: the base of the indirect field is a field and we should
1054 // build an implicit member access.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001055 } else {
1056 // We've found a member of an anonymous struct/union that is
1057 // inside a non-anonymous struct/union, so in a well-formed
1058 // program our base object expression is "this".
John McCallf3a88602011-02-03 08:15:49 +00001059 CXXMethodDecl *method = tryCaptureCXXThis();
1060 if (!method) {
1061 Diag(loc, diag::err_invalid_member_use_in_static_method)
1062 << indirectField->getDeclName();
1063 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001064 }
1065
John McCallf3a88602011-02-03 08:15:49 +00001066 // Our base object expression is "this".
1067 baseObjectExpr =
1068 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1069 /*isImplicit=*/ true);
1070 baseObjectIsPointer = true;
1071 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001072 }
1073
1074 // Build the implicit member references to the field of the
1075 // anonymous struct/union.
John McCallf3a88602011-02-03 08:15:49 +00001076 Expr *result = baseObjectExpr;
1077 IndirectFieldDecl::chain_iterator
1078 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +00001079
John McCallf3a88602011-02-03 08:15:49 +00001080 // Build the first member access in the chain with full information.
1081 if (!baseVariable) {
1082 FieldDecl *field = cast<FieldDecl>(*FI);
John McCallfeb624a2010-11-23 20:48:44 +00001083
John McCallf3a88602011-02-03 08:15:49 +00001084 // FIXME: use the real found-decl info!
1085 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +00001086
John McCallf3a88602011-02-03 08:15:49 +00001087 // Make a nameInfo that properly uses the anonymous name.
1088 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall8ccfcb52009-09-24 19:53:00 +00001089
John McCallf3a88602011-02-03 08:15:49 +00001090 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
1091 SS, field, foundDecl,
1092 memberNameInfo).take();
1093 baseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +00001094
John McCallf3a88602011-02-03 08:15:49 +00001095 // FIXME: check qualified member access
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001096 }
1097
John McCallf3a88602011-02-03 08:15:49 +00001098 // In all cases, we should now skip the first declaration in the chain.
1099 ++FI;
1100
1101 for (; FI != FEnd; FI++) {
1102 FieldDecl *field = cast<FieldDecl>(*FI);
1103
1104 // FIXME: these are somewhat meaningless
1105 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1106 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
1107 CXXScopeSpec memberSS;
1108
1109 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
1110 memberSS, field, foundDecl, memberNameInfo)
1111 .take();
1112 }
1113
1114 return Owned(result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001115}
1116
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001117/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001118/// possibly a list of template arguments.
1119///
1120/// If this produces template arguments, it is permitted to call
1121/// DecomposeTemplateName.
1122///
1123/// This actually loses a lot of source location information for
1124/// non-standard name kinds; we should consider preserving that in
1125/// some way.
1126static void DecomposeUnqualifiedId(Sema &SemaRef,
1127 const UnqualifiedId &Id,
1128 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001129 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00001130 const TemplateArgumentListInfo *&TemplateArgs) {
1131 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1132 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1133 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1134
1135 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1136 Id.TemplateId->getTemplateArgs(),
1137 Id.TemplateId->NumArgs);
1138 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1139 TemplateArgsPtr.release();
1140
John McCall3e56fd42010-08-23 07:28:44 +00001141 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001142 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1143 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001144 TemplateArgs = &Buffer;
1145 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001146 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001147 TemplateArgs = 0;
1148 }
1149}
1150
John McCall2d74de92009-12-01 22:10:20 +00001151/// Determines if the given class is provably not derived from all of
1152/// the prospective base classes.
1153static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1154 CXXRecordDecl *Record,
1155 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001156 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001157 return false;
1158
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001159 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001160 if (!RD) return false;
1161 Record = cast<CXXRecordDecl>(RD);
1162
John McCall2d74de92009-12-01 22:10:20 +00001163 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1164 E = Record->bases_end(); I != E; ++I) {
1165 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1166 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1167 if (!BaseRT) return false;
1168
1169 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001170 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1171 return false;
1172 }
1173
1174 return true;
1175}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001176
John McCall2d74de92009-12-01 22:10:20 +00001177enum IMAKind {
1178 /// The reference is definitely not an instance member access.
1179 IMA_Static,
1180
1181 /// The reference may be an implicit instance member access.
1182 IMA_Mixed,
1183
1184 /// The reference may be to an instance member, but it is invalid if
1185 /// so, because the context is not an instance method.
1186 IMA_Mixed_StaticContext,
1187
1188 /// The reference may be to an instance member, but it is invalid if
1189 /// so, because the context is from an unrelated class.
1190 IMA_Mixed_Unrelated,
1191
1192 /// The reference is definitely an implicit instance member access.
1193 IMA_Instance,
1194
1195 /// The reference may be to an unresolved using declaration.
1196 IMA_Unresolved,
1197
1198 /// The reference may be to an unresolved using declaration and the
1199 /// context is not an instance method.
1200 IMA_Unresolved_StaticContext,
1201
John McCall2d74de92009-12-01 22:10:20 +00001202 /// All possible referrents are instance members and the current
1203 /// context is not an instance method.
1204 IMA_Error_StaticContext,
1205
1206 /// All possible referrents are instance members of an unrelated
1207 /// class.
1208 IMA_Error_Unrelated
1209};
1210
1211/// The given lookup names class member(s) and is not being used for
1212/// an address-of-member expression. Classify the type of access
1213/// according to whether it's possible that this reference names an
1214/// instance member. This is best-effort; it is okay to
1215/// conservatively answer "yes", in which case some errors will simply
1216/// not be caught until template-instantiation.
1217static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1218 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001219 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001220
John McCall87fe5d52010-05-20 01:18:31 +00001221 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001222 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001223 (!isa<CXXMethodDecl>(DC) ||
1224 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001225
1226 if (R.isUnresolvableResult())
1227 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1228
1229 // Collect all the declaring classes of instance members we find.
1230 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001231 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001232 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1233 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001234 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001235
John McCalla8ae2222010-04-06 21:38:20 +00001236 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001237 if (dyn_cast<FieldDecl>(D))
1238 hasField = true;
1239
John McCall2d74de92009-12-01 22:10:20 +00001240 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001241 Classes.insert(R->getCanonicalDecl());
1242 }
1243 else
1244 hasNonInstance = true;
1245 }
1246
1247 // If we didn't find any instance members, it can't be an implicit
1248 // member reference.
1249 if (Classes.empty())
1250 return IMA_Static;
1251
1252 // If the current context is not an instance method, it can't be
1253 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001254 if (isStaticContext) {
1255 if (hasNonInstance)
1256 return IMA_Mixed_StaticContext;
1257
1258 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1259 // C++0x [expr.prim.general]p10:
1260 // An id-expression that denotes a non-static data member or non-static
1261 // member function of a class can only be used:
1262 // (...)
1263 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1264 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1265 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1266 if (isUnevaluatedExpression)
1267 return IMA_Mixed_StaticContext;
1268 }
1269
1270 return IMA_Error_StaticContext;
1271 }
John McCall2d74de92009-12-01 22:10:20 +00001272
1273 // If we can prove that the current context is unrelated to all the
1274 // declaring classes, it can't be an implicit member reference (in
1275 // which case it's an error if any of those members are selected).
1276 if (IsProvablyNotDerivedFrom(SemaRef,
John McCall87fe5d52010-05-20 01:18:31 +00001277 cast<CXXMethodDecl>(DC)->getParent(),
John McCall2d74de92009-12-01 22:10:20 +00001278 Classes))
1279 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1280
1281 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1282}
1283
1284/// Diagnose a reference to a field with no object available.
1285static void DiagnoseInstanceReference(Sema &SemaRef,
1286 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00001287 NamedDecl *rep,
1288 const DeclarationNameInfo &nameInfo) {
1289 SourceLocation Loc = nameInfo.getLoc();
John McCall2d74de92009-12-01 22:10:20 +00001290 SourceRange Range(Loc);
1291 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1292
John McCallf3a88602011-02-03 08:15:49 +00001293 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCall2d74de92009-12-01 22:10:20 +00001294 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1295 if (MD->isStatic()) {
1296 // "invalid use of member 'x' in static member function"
1297 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallf3a88602011-02-03 08:15:49 +00001298 << Range << nameInfo.getName();
John McCall2d74de92009-12-01 22:10:20 +00001299 return;
1300 }
1301 }
1302
1303 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallf3a88602011-02-03 08:15:49 +00001304 << nameInfo.getName() << Range;
John McCall2d74de92009-12-01 22:10:20 +00001305 return;
1306 }
1307
1308 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001309}
1310
John McCalld681c392009-12-16 08:11:27 +00001311/// Diagnose an empty lookup.
1312///
1313/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001314bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1315 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001316 DeclarationName Name = R.getLookupName();
1317
John McCalld681c392009-12-16 08:11:27 +00001318 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001319 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001320 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1321 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001322 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001323 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001324 diagnostic_suggest = diag::err_undeclared_use_suggest;
1325 }
John McCalld681c392009-12-16 08:11:27 +00001326
Douglas Gregor598b08f2009-12-31 05:20:13 +00001327 // If the original lookup was an unqualified lookup, fake an
1328 // unqualified lookup. This is useful when (for example) the
1329 // original lookup would not have found something because it was a
1330 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001331 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001332 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001333 if (isa<CXXRecordDecl>(DC)) {
1334 LookupQualifiedName(R, DC);
1335
1336 if (!R.empty()) {
1337 // Don't give errors about ambiguities in this lookup.
1338 R.suppressDiagnostics();
1339
1340 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1341 bool isInstance = CurMethod &&
1342 CurMethod->isInstance() &&
1343 DC == CurMethod->getParent();
1344
1345 // Give a code modification hint to insert 'this->'.
1346 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1347 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001348 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001349 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1350 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001351 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001352 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001353 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001354 Diag(R.getNameLoc(), diagnostic) << Name
1355 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1356 QualType DepThisType = DepMethod->getThisType(Context);
1357 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1358 R.getNameLoc(), DepThisType, false);
1359 TemplateArgumentListInfo TList;
1360 if (ULE->hasExplicitTemplateArgs())
1361 ULE->copyTemplateArgumentsInto(TList);
1362 CXXDependentScopeMemberExpr *DepExpr =
1363 CXXDependentScopeMemberExpr::Create(
1364 Context, DepThis, DepThisType, true, SourceLocation(),
1365 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
1366 R.getLookupNameInfo(), &TList);
1367 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001368 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001369 // FIXME: we should be able to handle this case too. It is correct
1370 // to add this-> here. This is a workaround for PR7947.
1371 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001372 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001373 } else {
John McCalld681c392009-12-16 08:11:27 +00001374 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001375 }
John McCalld681c392009-12-16 08:11:27 +00001376
1377 // Do we really want to note all of these?
1378 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1379 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1380
1381 // Tell the callee to try to recover.
1382 return false;
1383 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001384
1385 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001386 }
1387 }
1388
Douglas Gregor598b08f2009-12-31 05:20:13 +00001389 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001390 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001391 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001392 if (!R.empty()) {
1393 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1394 if (SS.isEmpty())
1395 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1396 << FixItHint::CreateReplacement(R.getNameLoc(),
1397 R.getLookupName().getAsString());
1398 else
1399 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1400 << Name << computeDeclContext(SS, false) << R.getLookupName()
1401 << SS.getRange()
1402 << FixItHint::CreateReplacement(R.getNameLoc(),
1403 R.getLookupName().getAsString());
1404 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1405 Diag(ND->getLocation(), diag::note_previous_decl)
1406 << ND->getDeclName();
1407
1408 // Tell the callee to try to recover.
1409 return false;
1410 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001411
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001412 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1413 // FIXME: If we ended up with a typo for a type name or
1414 // Objective-C class name, we're in trouble because the parser
1415 // is in the wrong place to recover. Suggest the typo
1416 // correction, but don't make it a fix-it since we're not going
1417 // to recover well anyway.
1418 if (SS.isEmpty())
1419 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1420 else
1421 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1422 << Name << computeDeclContext(SS, false) << R.getLookupName()
1423 << SS.getRange();
1424
1425 // Don't try to recover; it won't work.
1426 return true;
1427 }
1428 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001429 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001430 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001431 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001432 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001433 else
Douglas Gregor25363982010-01-01 00:15:04 +00001434 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001435 << Name << computeDeclContext(SS, false) << Corrected
1436 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001437 return true;
1438 }
Douglas Gregor25363982010-01-01 00:15:04 +00001439 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001440 }
1441
1442 // Emit a special diagnostic for failed member lookups.
1443 // FIXME: computing the declaration context might fail here (?)
1444 if (!SS.isEmpty()) {
1445 Diag(R.getNameLoc(), diag::err_no_member)
1446 << Name << computeDeclContext(SS, false)
1447 << SS.getRange();
1448 return true;
1449 }
1450
John McCalld681c392009-12-16 08:11:27 +00001451 // Give up, we can't recover.
1452 Diag(R.getNameLoc(), diagnostic) << Name;
1453 return true;
1454}
1455
Douglas Gregor05fcf842010-11-02 20:36:02 +00001456ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1457 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001458 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1459 if (!IDecl)
1460 return 0;
1461 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1462 if (!ClassImpDecl)
1463 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001464 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001465 if (!property)
1466 return 0;
1467 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001468 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1469 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001470 return 0;
1471 return property;
1472}
1473
Douglas Gregor05fcf842010-11-02 20:36:02 +00001474bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1475 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1476 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1477 if (!IDecl)
1478 return false;
1479 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1480 if (!ClassImpDecl)
1481 return false;
1482 if (ObjCPropertyImplDecl *PIDecl
1483 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1484 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1485 PIDecl->getPropertyIvarDecl())
1486 return false;
1487
1488 return true;
1489}
1490
Fariborz Jahanian18722982010-07-17 00:59:30 +00001491static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001492 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001493 IdentifierInfo *II,
1494 SourceLocation NameLoc) {
1495 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001496 bool LookForIvars;
1497 if (Lookup.empty())
1498 LookForIvars = true;
1499 else if (CurMeth->isClassMethod())
1500 LookForIvars = false;
1501 else
1502 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001503 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1504 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001505 if (!LookForIvars)
1506 return 0;
1507
Fariborz Jahanian18722982010-07-17 00:59:30 +00001508 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1509 if (!IDecl)
1510 return 0;
1511 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001512 if (!ClassImpDecl)
1513 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001514 bool DynamicImplSeen = false;
1515 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1516 if (!property)
1517 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001518 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001519 DynamicImplSeen =
1520 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001521 // property implementation has a designated ivar. No need to assume a new
1522 // one.
1523 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1524 return 0;
1525 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001526 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001527 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1528 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001529 NameLoc,
1530 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001531 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001532 (Expr *)0, true);
1533 ClassImpDecl->addDecl(Ivar);
1534 IDecl->makeDeclVisibleInContext(Ivar, false);
1535 property->setPropertyIvarDecl(Ivar);
1536 return Ivar;
1537 }
1538 return 0;
1539}
1540
John McCalldadc5752010-08-24 06:29:42 +00001541ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001542 CXXScopeSpec &SS,
1543 UnqualifiedId &Id,
1544 bool HasTrailingLParen,
1545 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001546 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1547 "cannot be direct & operand and have a trailing lparen");
1548
1549 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001550 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001551
John McCall10eae182009-11-30 22:42:35 +00001552 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001553
1554 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001555 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001556 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001557 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001558
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001559 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001560 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001561 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001562
John McCalle66edc12009-11-24 19:00:30 +00001563 // C++ [temp.dep.expr]p3:
1564 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001565 // -- an identifier that was declared with a dependent type,
1566 // (note: handled after lookup)
1567 // -- a template-id that is dependent,
1568 // (note: handled in BuildTemplateIdExpr)
1569 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001570 // -- a nested-name-specifier that contains a class-name that
1571 // names a dependent type.
1572 // Determine whether this is a member of an unknown specialization;
1573 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001574 bool DependentID = false;
1575 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1576 Name.getCXXNameType()->isDependentType()) {
1577 DependentID = true;
1578 } else if (SS.isSet()) {
1579 DeclContext *DC = computeDeclContext(SS, false);
1580 if (DC) {
1581 if (RequireCompleteDeclContext(SS, DC))
1582 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001583 } else {
1584 DependentID = true;
1585 }
1586 }
1587
1588 if (DependentID) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001589 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001590 TemplateArgs);
1591 }
Fariborz Jahanian86151342010-07-22 23:33:21 +00001592 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001593 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001594 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001595 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001596 // Lookup the template name again to correctly establish the context in
1597 // which it was found. This is really unfortunate as we already did the
1598 // lookup to determine that it was a template name in the first place. If
1599 // this becomes a performance hit, we can work harder to preserve those
1600 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001601 bool MemberOfUnknownSpecialization;
1602 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1603 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001604
1605 if (MemberOfUnknownSpecialization ||
1606 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1607 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1608 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001609 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001610 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001611 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001612
Douglas Gregora5226932011-02-04 13:35:07 +00001613 // If the result might be in a dependent base class, this is a dependent
1614 // id-expression.
1615 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1616 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1617 TemplateArgs);
1618
John McCalle66edc12009-11-24 19:00:30 +00001619 // If this reference is in an Objective-C method, then we need to do
1620 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001621 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001622 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001623 if (E.isInvalid())
1624 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001625
John McCalle66edc12009-11-24 19:00:30 +00001626 Expr *Ex = E.takeAs<Expr>();
1627 if (Ex) return Owned(Ex);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001628 // Synthesize ivars lazily
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001629 if (getLangOptions().ObjCDefaultSynthProperties &&
1630 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001631 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1632 if (const ObjCPropertyDecl *Property =
1633 canSynthesizeProvisionalIvar(II)) {
1634 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1635 Diag(Property->getLocation(), diag::note_property_declare);
1636 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001637 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1638 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001639 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001640 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001641 // for further use, this must be set to false if in class method.
1642 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001643 }
Chris Lattner59a25942008-03-31 00:36:02 +00001644 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001645
John McCalle66edc12009-11-24 19:00:30 +00001646 if (R.isAmbiguous())
1647 return ExprError();
1648
Douglas Gregor171c45a2009-02-18 21:56:37 +00001649 // Determine whether this name might be a candidate for
1650 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001651 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001652
John McCalle66edc12009-11-24 19:00:30 +00001653 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001654 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001655 // in C90, extension in C99, forbidden in C++).
1656 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1657 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1658 if (D) R.addDecl(D);
1659 }
1660
1661 // If this name wasn't predeclared and if this is not a function
1662 // call, diagnose the problem.
1663 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001664 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001665 return ExprError();
1666
1667 assert(!R.empty() &&
1668 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001669
1670 // If we found an Objective-C instance variable, let
1671 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001672 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001673 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1674 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001675 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001676 assert(E.isInvalid() || E.get());
1677 return move(E);
1678 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001679 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001680 }
Mike Stump11289f42009-09-09 15:08:12 +00001681
John McCalle66edc12009-11-24 19:00:30 +00001682 // This is guaranteed from this point on.
1683 assert(!R.empty() || ADL);
1684
1685 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001686 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001687 !(getLangOptions().ObjCDefaultSynthProperties &&
1688 getLangOptions().ObjCNonFragileABI2) &&
Fariborz Jahanianc15dfd82010-07-29 16:53:53 +00001689 Var->isFileVarDecl()) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001690 ObjCPropertyDecl *Property = canSynthesizeProvisionalIvar(II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001691 if (Property) {
1692 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1693 Diag(Property->getLocation(), diag::note_property_declare);
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001694 Diag(Var->getLocation(), diag::note_global_declared_at);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001695 }
1696 }
John McCalle66edc12009-11-24 19:00:30 +00001697 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001698 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1699 // C99 DR 316 says that, if a function type comes from a
1700 // function definition (without a prototype), that type is only
1701 // used for checking compatibility. Therefore, when referencing
1702 // the function, we pretend that we don't have the full function
1703 // type.
John McCalle66edc12009-11-24 19:00:30 +00001704 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001705 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001706
Douglas Gregor3256d042009-06-30 15:47:41 +00001707 QualType T = Func->getType();
1708 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001709 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Eli Friedmanb41ad0f2010-05-17 02:50:18 +00001710 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(),
1711 Proto->getExtInfo());
John McCall7decc9e2010-11-18 06:31:45 +00001712 // Note that functions are r-values in C.
1713 return BuildDeclRefExpr(Func, NoProtoType, VK_RValue, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001714 }
1715 }
Mike Stump11289f42009-09-09 15:08:12 +00001716
John McCall2d74de92009-12-01 22:10:20 +00001717 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001718 // C++ [class.mfct.non-static]p3:
1719 // When an id-expression that is not part of a class member access
1720 // syntax and not used to form a pointer to member is used in the
1721 // body of a non-static member function of class X, if name lookup
1722 // resolves the name in the id-expression to a non-static non-type
1723 // member of some class C, the id-expression is transformed into a
1724 // class member access expression using (*this) as the
1725 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001726 //
1727 // But we don't actually need to do this for '&' operands if R
1728 // resolved to a function or overloaded function set, because the
1729 // expression is ill-formed if it actually works out to be a
1730 // non-static member function:
1731 //
1732 // C++ [expr.ref]p4:
1733 // Otherwise, if E1.E2 refers to a non-static member function. . .
1734 // [t]he expression can be used only as the left-hand operand of a
1735 // member function call.
1736 //
1737 // There are other safeguards against such uses, but it's important
1738 // to get this right here so that we don't end up making a
1739 // spuriously dependent expression if we're inside a dependent
1740 // instance method.
John McCall57500772009-12-16 12:17:52 +00001741 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001742 bool MightBeImplicitMember;
1743 if (!isAddressOfOperand)
1744 MightBeImplicitMember = true;
1745 else if (!SS.isEmpty())
1746 MightBeImplicitMember = false;
1747 else if (R.isOverloadedResult())
1748 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001749 else if (R.isUnresolvableResult())
1750 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001751 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001752 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1753 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001754
1755 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001756 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001757 }
1758
John McCalle66edc12009-11-24 19:00:30 +00001759 if (TemplateArgs)
1760 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001761
John McCalle66edc12009-11-24 19:00:30 +00001762 return BuildDeclarationNameExpr(SS, R, ADL);
1763}
1764
John McCall57500772009-12-16 12:17:52 +00001765/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001766ExprResult
John McCall57500772009-12-16 12:17:52 +00001767Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1768 LookupResult &R,
1769 const TemplateArgumentListInfo *TemplateArgs) {
1770 switch (ClassifyImplicitMemberAccess(*this, R)) {
1771 case IMA_Instance:
1772 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1773
John McCall57500772009-12-16 12:17:52 +00001774 case IMA_Mixed:
1775 case IMA_Mixed_Unrelated:
1776 case IMA_Unresolved:
1777 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1778
1779 case IMA_Static:
1780 case IMA_Mixed_StaticContext:
1781 case IMA_Unresolved_StaticContext:
1782 if (TemplateArgs)
1783 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1784 return BuildDeclarationNameExpr(SS, R, false);
1785
1786 case IMA_Error_StaticContext:
1787 case IMA_Error_Unrelated:
John McCallf3a88602011-02-03 08:15:49 +00001788 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1789 R.getLookupNameInfo());
John McCall57500772009-12-16 12:17:52 +00001790 return ExprError();
1791 }
1792
1793 llvm_unreachable("unexpected instance member access kind");
1794 return ExprError();
1795}
1796
John McCall10eae182009-11-30 22:42:35 +00001797/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1798/// declaration name, generally during template instantiation.
1799/// There's a large number of things which don't need to be done along
1800/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001801ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001802Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001803 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001804 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001805 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001806 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001807
John McCall0b66eb32010-05-01 00:40:08 +00001808 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001809 return ExprError();
1810
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001811 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001812 LookupQualifiedName(R, DC);
1813
1814 if (R.isAmbiguous())
1815 return ExprError();
1816
1817 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001818 Diag(NameInfo.getLoc(), diag::err_no_member)
1819 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001820 return ExprError();
1821 }
1822
1823 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1824}
1825
1826/// LookupInObjCMethod - The parser has read a name in, and Sema has
1827/// detected that we're currently inside an ObjC method. Perform some
1828/// additional lookup.
1829///
1830/// Ideally, most of this would be done by lookup, but there's
1831/// actually quite a lot of extra work involved.
1832///
1833/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001834ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001835Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001836 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001837 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001838 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001839
John McCalle66edc12009-11-24 19:00:30 +00001840 // There are two cases to handle here. 1) scoped lookup could have failed,
1841 // in which case we should look for an ivar. 2) scoped lookup could have
1842 // found a decl, but that decl is outside the current instance method (i.e.
1843 // a global variable). In these two cases, we do a lookup for an ivar with
1844 // this name, if the lookup sucedes, we replace it our current decl.
1845
1846 // If we're in a class method, we don't normally want to look for
1847 // ivars. But if we don't find anything else, and there's an
1848 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001849 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001850
1851 bool LookForIvars;
1852 if (Lookup.empty())
1853 LookForIvars = true;
1854 else if (IsClassMethod)
1855 LookForIvars = false;
1856 else
1857 LookForIvars = (Lookup.isSingleResult() &&
1858 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001859 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001860 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001861 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001862 ObjCInterfaceDecl *ClassDeclared;
1863 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1864 // Diagnose using an ivar in a class method.
1865 if (IsClassMethod)
1866 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1867 << IV->getDeclName());
1868
1869 // If we're referencing an invalid decl, just return this as a silent
1870 // error node. The error diagnostic was already emitted on the decl.
1871 if (IV->isInvalidDecl())
1872 return ExprError();
1873
1874 // Check if referencing a field with __attribute__((deprecated)).
1875 if (DiagnoseUseOfDecl(IV, Loc))
1876 return ExprError();
1877
1878 // Diagnose the use of an ivar outside of the declaring class.
1879 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1880 ClassDeclared != IFace)
1881 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1882
1883 // FIXME: This should use a new expr for a direct reference, don't
1884 // turn this into Self->ivar, just return a BareIVarExpr or something.
1885 IdentifierInfo &II = Context.Idents.get("self");
1886 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001887 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001888 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001889 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001890 SelfName, false, false);
1891 if (SelfExpr.isInvalid())
1892 return ExprError();
1893
John McCall27584242010-12-06 20:48:59 +00001894 Expr *SelfE = SelfExpr.take();
1895 DefaultLvalueConversion(SelfE);
1896
John McCalle66edc12009-11-24 19:00:30 +00001897 MarkDeclarationReferenced(Loc, IV);
1898 return Owned(new (Context)
1899 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall27584242010-12-06 20:48:59 +00001900 SelfE, true, true));
John McCalle66edc12009-11-24 19:00:30 +00001901 }
Chris Lattner87313662010-04-12 05:10:17 +00001902 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001903 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001904 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001905 ObjCInterfaceDecl *ClassDeclared;
1906 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1907 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1908 IFace == ClassDeclared)
1909 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1910 }
1911 }
1912
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001913 if (Lookup.empty() && II && AllowBuiltinCreation) {
1914 // FIXME. Consolidate this with similar code in LookupName.
1915 if (unsigned BuiltinID = II->getBuiltinID()) {
1916 if (!(getLangOptions().CPlusPlus &&
1917 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1918 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1919 S, Lookup.isForRedeclaration(),
1920 Lookup.getNameLoc());
1921 if (D) Lookup.addDecl(D);
1922 }
1923 }
1924 }
John McCalle66edc12009-11-24 19:00:30 +00001925 // Sentinel value saying that we didn't do anything special.
1926 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001927}
John McCalld14a8642009-11-21 08:51:07 +00001928
John McCall16df1e52010-03-30 21:47:33 +00001929/// \brief Cast a base object to a member's actual type.
1930///
1931/// Logically this happens in three phases:
1932///
1933/// * First we cast from the base type to the naming class.
1934/// The naming class is the class into which we were looking
1935/// when we found the member; it's the qualifier type if a
1936/// qualifier was provided, and otherwise it's the base type.
1937///
1938/// * Next we cast from the naming class to the declaring class.
1939/// If the member we found was brought into a class's scope by
1940/// a using declaration, this is that class; otherwise it's
1941/// the class declaring the member.
1942///
1943/// * Finally we cast from the declaring class to the "true"
1944/// declaring class of the member. This conversion does not
1945/// obey access control.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001946bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001947Sema::PerformObjectMemberConversion(Expr *&From,
1948 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001949 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001950 NamedDecl *Member) {
1951 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1952 if (!RD)
1953 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001954
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001955 QualType DestRecordType;
1956 QualType DestType;
1957 QualType FromRecordType;
1958 QualType FromType = From->getType();
1959 bool PointerConversions = false;
1960 if (isa<FieldDecl>(Member)) {
1961 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001962
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001963 if (FromType->getAs<PointerType>()) {
1964 DestType = Context.getPointerType(DestRecordType);
1965 FromRecordType = FromType->getPointeeType();
1966 PointerConversions = true;
1967 } else {
1968 DestType = DestRecordType;
1969 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001970 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001971 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1972 if (Method->isStatic())
1973 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001974
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001975 DestType = Method->getThisType(Context);
1976 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001977
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001978 if (FromType->getAs<PointerType>()) {
1979 FromRecordType = FromType->getPointeeType();
1980 PointerConversions = true;
1981 } else {
1982 FromRecordType = FromType;
1983 DestType = DestRecordType;
1984 }
1985 } else {
1986 // No conversion necessary.
1987 return false;
1988 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001989
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001990 if (DestType->isDependentType() || FromType->isDependentType())
1991 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001992
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001993 // If the unqualified types are the same, no conversion is necessary.
1994 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1995 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001996
John McCall16df1e52010-03-30 21:47:33 +00001997 SourceRange FromRange = From->getSourceRange();
1998 SourceLocation FromLoc = FromRange.getBegin();
1999
John McCall2536c6d2010-08-25 10:28:54 +00002000 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002001
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002002 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002003 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002004 // class name.
2005 //
2006 // If the member was a qualified name and the qualified referred to a
2007 // specific base subobject type, we'll cast to that intermediate type
2008 // first and then to the object in which the member is declared. That allows
2009 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2010 //
2011 // class Base { public: int x; };
2012 // class Derived1 : public Base { };
2013 // class Derived2 : public Base { };
2014 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2015 //
2016 // void VeryDerived::f() {
2017 // x = 17; // error: ambiguous base subobjects
2018 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2019 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002020 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002021 QualType QType = QualType(Qualifier->getAsType(), 0);
2022 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2023 assert(QType->isRecordType() && "lookup done with non-record type");
2024
2025 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2026
2027 // In C++98, the qualifier type doesn't actually have to be a base
2028 // type of the object type, in which case we just ignore it.
2029 // Otherwise build the appropriate casts.
2030 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002031 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002032 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002033 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00002034 return true;
2035
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002036 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002037 QType = Context.getPointerType(QType);
John McCall2536c6d2010-08-25 10:28:54 +00002038 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2039 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00002040
2041 FromType = QType;
2042 FromRecordType = QRecordType;
2043
2044 // If the qualifier type was the same as the destination type,
2045 // we're done.
2046 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2047 return false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002048 }
2049 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002050
John McCall16df1e52010-03-30 21:47:33 +00002051 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002052
John McCall16df1e52010-03-30 21:47:33 +00002053 // If we actually found the member through a using declaration, cast
2054 // down to the using declaration's type.
2055 //
2056 // Pointer equality is fine here because only one declaration of a
2057 // class ever has member declarations.
2058 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2059 assert(isa<UsingShadowDecl>(FoundDecl));
2060 QualType URecordType = Context.getTypeDeclType(
2061 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2062
2063 // We only need to do this if the naming-class to declaring-class
2064 // conversion is non-trivial.
2065 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2066 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002067 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002068 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002069 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00002070 return true;
Alexis Huntc46382e2010-04-28 23:02:27 +00002071
John McCall16df1e52010-03-30 21:47:33 +00002072 QualType UType = URecordType;
2073 if (PointerConversions)
2074 UType = Context.getPointerType(UType);
John McCalle3027922010-08-25 11:45:40 +00002075 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00002076 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00002077 FromType = UType;
2078 FromRecordType = URecordType;
2079 }
2080
2081 // We don't do access control for the conversion from the
2082 // declaring class to the true declaring class.
2083 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002084 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002085
John McCallcf142162010-08-07 06:22:56 +00002086 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002087 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2088 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002089 IgnoreAccess))
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002090 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002091
John McCalle3027922010-08-25 11:45:40 +00002092 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00002093 VK, &BasePath);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00002094 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002095}
Douglas Gregor3256d042009-06-30 15:47:41 +00002096
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002097/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00002098static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00002099 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00002100 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002101 const DeclarationNameInfo &MemberNameInfo,
2102 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00002103 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00002104 const TemplateArgumentListInfo *TemplateArgs = 0) {
2105 NestedNameSpecifier *Qualifier = 0;
2106 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00002107 if (SS.isSet()) {
2108 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
2109 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002110 }
Mike Stump11289f42009-09-09 15:08:12 +00002111
John McCalle66edc12009-11-24 19:00:30 +00002112 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002113 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002114 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00002115}
2116
John McCallfeb624a2010-11-23 20:48:44 +00002117static ExprResult
2118BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2119 const CXXScopeSpec &SS, FieldDecl *Field,
2120 DeclAccessPair FoundDecl,
2121 const DeclarationNameInfo &MemberNameInfo) {
2122 // x.a is an l-value if 'a' has a reference type. Otherwise:
2123 // x.a is an l-value/x-value/pr-value if the base is (and note
2124 // that *x is always an l-value), except that if the base isn't
2125 // an ordinary object then we must have an rvalue.
2126 ExprValueKind VK = VK_LValue;
2127 ExprObjectKind OK = OK_Ordinary;
2128 if (!IsArrow) {
2129 if (BaseExpr->getObjectKind() == OK_Ordinary)
2130 VK = BaseExpr->getValueKind();
2131 else
2132 VK = VK_RValue;
2133 }
2134 if (VK != VK_RValue && Field->isBitField())
2135 OK = OK_BitField;
2136
2137 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2138 QualType MemberType = Field->getType();
2139 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2140 MemberType = Ref->getPointeeType();
2141 VK = VK_LValue;
2142 } else {
2143 QualType BaseType = BaseExpr->getType();
2144 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2145
2146 Qualifiers BaseQuals = BaseType.getQualifiers();
2147
2148 // GC attributes are never picked up by members.
2149 BaseQuals.removeObjCGCAttr();
2150
2151 // CVR attributes from the base are picked up by members,
2152 // except that 'mutable' members don't pick up 'const'.
2153 if (Field->isMutable()) BaseQuals.removeConst();
2154
2155 Qualifiers MemberQuals
2156 = S.Context.getCanonicalType(MemberType).getQualifiers();
2157
2158 // TR 18037 does not allow fields to be declared with address spaces.
2159 assert(!MemberQuals.hasAddressSpace());
2160
2161 Qualifiers Combined = BaseQuals + MemberQuals;
2162 if (Combined != MemberQuals)
2163 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2164 }
2165
2166 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2167 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2168 FoundDecl, Field))
2169 return ExprError();
2170 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2171 Field, FoundDecl, MemberNameInfo,
2172 MemberType, VK, OK));
2173}
2174
John McCall2d74de92009-12-01 22:10:20 +00002175/// Builds an implicit member access expression. The current context
2176/// is known to be an instance method, and the given unqualified lookup
2177/// set is known to contain only instance members, at least one of which
2178/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002179ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002180Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2181 LookupResult &R,
2182 const TemplateArgumentListInfo *TemplateArgs,
2183 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002184 assert(!R.empty() && !R.isAmbiguous());
2185
John McCallf3a88602011-02-03 08:15:49 +00002186 SourceLocation loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002187
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002188 // We may have found a field within an anonymous union or struct
2189 // (C++ [class.union]).
John McCalle66edc12009-11-24 19:00:30 +00002190 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002191 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCallf3a88602011-02-03 08:15:49 +00002192 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002193
John McCallf3a88602011-02-03 08:15:49 +00002194 // If this is known to be an instance access, go ahead and build an
2195 // implicit 'this' expression now.
John McCall2d74de92009-12-01 22:10:20 +00002196 // 'this' expression now.
John McCallf3a88602011-02-03 08:15:49 +00002197 CXXMethodDecl *method = tryCaptureCXXThis();
2198 assert(method && "didn't correctly pre-flight capture of 'this'");
2199
2200 QualType thisType = method->getThisType(Context);
2201 Expr *baseExpr = 0; // null signifies implicit access
John McCall2d74de92009-12-01 22:10:20 +00002202 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002203 SourceLocation Loc = R.getNameLoc();
2204 if (SS.getRange().isValid())
2205 Loc = SS.getRange().getBegin();
John McCallf3a88602011-02-03 08:15:49 +00002206 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002207 }
2208
John McCallf3a88602011-02-03 08:15:49 +00002209 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCall2d74de92009-12-01 22:10:20 +00002210 /*OpLoc*/ SourceLocation(),
2211 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002212 SS,
2213 /*FirstQualifierInScope*/ 0,
2214 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002215}
2216
John McCalle66edc12009-11-24 19:00:30 +00002217bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002218 const LookupResult &R,
2219 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002220 // Only when used directly as the postfix-expression of a call.
2221 if (!HasTrailingLParen)
2222 return false;
2223
2224 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002225 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002226 return false;
2227
2228 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002229 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002230 return false;
2231
2232 // Turn off ADL when we find certain kinds of declarations during
2233 // normal lookup:
2234 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2235 NamedDecl *D = *I;
2236
2237 // C++0x [basic.lookup.argdep]p3:
2238 // -- a declaration of a class member
2239 // Since using decls preserve this property, we check this on the
2240 // original decl.
John McCall57500772009-12-16 12:17:52 +00002241 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002242 return false;
2243
2244 // C++0x [basic.lookup.argdep]p3:
2245 // -- a block-scope function declaration that is not a
2246 // using-declaration
2247 // NOTE: we also trigger this for function templates (in fact, we
2248 // don't check the decl type at all, since all other decl types
2249 // turn off ADL anyway).
2250 if (isa<UsingShadowDecl>(D))
2251 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2252 else if (D->getDeclContext()->isFunctionOrMethod())
2253 return false;
2254
2255 // C++0x [basic.lookup.argdep]p3:
2256 // -- a declaration that is neither a function or a function
2257 // template
2258 // And also for builtin functions.
2259 if (isa<FunctionDecl>(D)) {
2260 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2261
2262 // But also builtin functions.
2263 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2264 return false;
2265 } else if (!isa<FunctionTemplateDecl>(D))
2266 return false;
2267 }
2268
2269 return true;
2270}
2271
2272
John McCalld14a8642009-11-21 08:51:07 +00002273/// Diagnoses obvious problems with the use of the given declaration
2274/// as an expression. This is only actually called for lookups that
2275/// were not overloaded, and it doesn't promise that the declaration
2276/// will in fact be used.
2277static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2278 if (isa<TypedefDecl>(D)) {
2279 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2280 return true;
2281 }
2282
2283 if (isa<ObjCInterfaceDecl>(D)) {
2284 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2285 return true;
2286 }
2287
2288 if (isa<NamespaceDecl>(D)) {
2289 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2290 return true;
2291 }
2292
2293 return false;
2294}
2295
John McCalldadc5752010-08-24 06:29:42 +00002296ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002297Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002298 LookupResult &R,
2299 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002300 // If this is a single, fully-resolved result and we don't need ADL,
2301 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002302 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002303 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2304 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002305
2306 // We only need to check the declaration if there's exactly one
2307 // result, because in the overloaded case the results can only be
2308 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002309 if (R.isSingleResult() &&
2310 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002311 return ExprError();
2312
John McCall58cc69d2010-01-27 01:50:18 +00002313 // Otherwise, just build an unresolved lookup expression. Suppress
2314 // any lookup-related diagnostics; we'll hash these out later, when
2315 // we've picked a target.
2316 R.suppressDiagnostics();
2317
John McCalld14a8642009-11-21 08:51:07 +00002318 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002319 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00002320 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002321 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002322 NeedsADL, R.isOverloadedResult(),
2323 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002324
2325 return Owned(ULE);
2326}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002327
John McCall7decc9e2010-11-18 06:31:45 +00002328static ExprValueKind getValueKindForDecl(ASTContext &Context,
2329 const ValueDecl *D) {
John McCall4bc41ae2010-11-18 19:01:18 +00002330 // FIXME: It's not clear to me why NonTypeTemplateParmDecl is a VarDecl.
2331 if (isa<VarDecl>(D) && !isa<NonTypeTemplateParmDecl>(D)) return VK_LValue;
2332 if (isa<FieldDecl>(D)) return VK_LValue;
John McCallf3a88602011-02-03 08:15:49 +00002333 if (isa<IndirectFieldDecl>(D)) return VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00002334 if (!Context.getLangOptions().CPlusPlus) return VK_RValue;
2335 if (isa<FunctionDecl>(D)) {
2336 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
2337 return VK_RValue;
2338 return VK_LValue;
2339 }
2340 return Expr::getValueKindForType(D->getType());
2341}
2342
John McCalld14a8642009-11-21 08:51:07 +00002343/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002344ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002345Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002346 const DeclarationNameInfo &NameInfo,
2347 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002348 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002349 assert(!isa<FunctionTemplateDecl>(D) &&
2350 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002351
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002352 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002353 if (CheckDeclInExpr(*this, Loc, D))
2354 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002355
Douglas Gregore7488b92009-12-01 16:58:18 +00002356 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2357 // Specifically diagnose references to class templates that are missing
2358 // a template argument list.
2359 Diag(Loc, diag::err_template_decl_ref)
2360 << Template << SS.getRange();
2361 Diag(Template->getLocation(), diag::note_template_decl_here);
2362 return ExprError();
2363 }
2364
2365 // Make sure that we're referring to a value.
2366 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2367 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002368 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002369 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002370 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002371 return ExprError();
2372 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002373
Douglas Gregor171c45a2009-02-18 21:56:37 +00002374 // Check whether this declaration can be used. Note that we suppress
2375 // this check when we're going to perform argument-dependent lookup
2376 // on this function name, because this might not be the function
2377 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002378 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002379 return ExprError();
2380
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002381 // Only create DeclRefExpr's for valid Decl's.
2382 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002383 return ExprError();
2384
John McCallf3a88602011-02-03 08:15:49 +00002385 // Handle members of anonymous structs and unions. If we got here,
2386 // and the reference is to a class member indirect field, then this
2387 // must be the subject of a pointer-to-member expression.
2388 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2389 if (!indirectField->isCXXClassMember())
2390 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2391 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002392
Chris Lattner2a9d9892008-10-20 05:16:36 +00002393 // If the identifier reference is inside a block, and it refers to a value
2394 // that is outside the block, create a BlockDeclRefExpr instead of a
2395 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2396 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002397 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002398 // We do not do this for things like enum constants, global variables, etc,
2399 // as they do not get snapshotted.
2400 //
John McCall351762c2011-02-07 10:33:21 +00002401 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002402 case CR_Error:
2403 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002404
John McCall351762c2011-02-07 10:33:21 +00002405 case CR_NoCapture: {
2406 ExprValueKind VK = getValueKindForDecl(Context, VD);
2407
John McCallc63de662011-02-02 13:00:07 +00002408 // If this reference is not in a block or if the referenced
2409 // variable is within the block, create a normal DeclRefExpr.
2410 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), VK,
2411 NameInfo, &SS);
John McCall351762c2011-02-07 10:33:21 +00002412 }
Mike Stump8971a862010-01-05 03:10:36 +00002413
John McCallc63de662011-02-02 13:00:07 +00002414 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002415 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2416 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2417
2418 case CR_CaptureByRef:
2419 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2420 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallc63de662011-02-02 13:00:07 +00002421 }
John McCall7decc9e2010-11-18 06:31:45 +00002422
John McCall351762c2011-02-07 10:33:21 +00002423 llvm_unreachable("unknown capture result");
2424 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002425}
Chris Lattnere168f762006-11-10 05:29:30 +00002426
John McCalldadc5752010-08-24 06:29:42 +00002427ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlffbcf962009-01-18 18:53:16 +00002428 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002429 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002430
Chris Lattnere168f762006-11-10 05:29:30 +00002431 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002432 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002433 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2434 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2435 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002436 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002437
Chris Lattnera81a0272008-01-12 08:14:25 +00002438 // Pre-defined identifiers are of type char[x], where x is the length of the
2439 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002440
Anders Carlsson2fb08242009-09-08 18:24:21 +00002441 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002442 if (!currentDecl && getCurBlock())
2443 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002444 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002445 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002446 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002447 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002448
Anders Carlsson0b209a82009-09-11 01:22:35 +00002449 QualType ResTy;
2450 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2451 ResTy = Context.DependentTy;
2452 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002453 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002454
Anders Carlsson0b209a82009-09-11 01:22:35 +00002455 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002456 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002457 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2458 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002459 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002460}
2461
John McCalldadc5752010-08-24 06:29:42 +00002462ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002463 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002464 bool Invalid = false;
2465 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2466 if (Invalid)
2467 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002468
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002469 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2470 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002471 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002472 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002473
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002474 QualType Ty;
2475 if (!getLangOptions().CPlusPlus)
2476 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2477 else if (Literal.isWide())
2478 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002479 else if (Literal.isMultiChar())
2480 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002481 else
2482 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002483
Sebastian Redl20614a72009-01-20 22:23:13 +00002484 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2485 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002486 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002487}
2488
John McCalldadc5752010-08-24 06:29:42 +00002489ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002490 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002491 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2492 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002493 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002494 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002495 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002496 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002497 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002498
Chris Lattner23b7eb62007-06-15 23:05:46 +00002499 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002500 // Add padding so that NumericLiteralParser can overread by one character.
2501 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002502 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002503
Chris Lattner67ca9252007-05-21 01:08:44 +00002504 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002505 bool Invalid = false;
2506 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2507 if (Invalid)
2508 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002509
Mike Stump11289f42009-09-09 15:08:12 +00002510 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002511 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002512 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002513 return ExprError();
2514
Chris Lattner1c20a172007-08-26 03:42:43 +00002515 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002516
Chris Lattner1c20a172007-08-26 03:42:43 +00002517 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002518 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002519 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002520 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002521 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002522 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002523 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002524 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002525
2526 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2527
John McCall53b93a02009-12-24 09:08:04 +00002528 using llvm::APFloat;
2529 APFloat Val(Format);
2530
2531 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002532
2533 // Overflow is always an error, but underflow is only an error if
2534 // we underflowed to zero (APFloat reports denormals as underflow).
2535 if ((result & APFloat::opOverflow) ||
2536 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002537 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002538 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002539 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002540 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002541 APFloat::getLargest(Format).toString(buffer);
2542 } else {
John McCall62abc942010-02-26 23:35:57 +00002543 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002544 APFloat::getSmallest(Format).toString(buffer);
2545 }
2546
2547 Diag(Tok.getLocation(), diagnostic)
2548 << Ty
2549 << llvm::StringRef(buffer.data(), buffer.size());
2550 }
2551
2552 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002553 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002554
Peter Collingbourne0b69e1a2010-12-04 01:50:56 +00002555 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2556 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2557
Chris Lattner1c20a172007-08-26 03:42:43 +00002558 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002559 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002560 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002561 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002562
Neil Boothac582c52007-08-29 22:00:19 +00002563 // long long is a C99 feature.
2564 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002565 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002566 Diag(Tok.getLocation(), diag::ext_longlong);
2567
Chris Lattner67ca9252007-05-21 01:08:44 +00002568 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002569 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002570
Chris Lattner67ca9252007-05-21 01:08:44 +00002571 if (Literal.GetIntegerValue(ResultVal)) {
2572 // If this value didn't fit into uintmax_t, warn and force to ull.
2573 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002574 Ty = Context.UnsignedLongLongTy;
2575 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002576 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002577 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002578 // If this value fits into a ULL, try to figure out what else it fits into
2579 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002580
Chris Lattner67ca9252007-05-21 01:08:44 +00002581 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2582 // be an unsigned int.
2583 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2584
2585 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002586 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002587 if (!Literal.isLong && !Literal.isLongLong) {
2588 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002589 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002590
Chris Lattner67ca9252007-05-21 01:08:44 +00002591 // Does it fit in a unsigned int?
2592 if (ResultVal.isIntN(IntSize)) {
2593 // Does it fit in a signed int?
2594 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002595 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002596 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002597 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002598 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002599 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002600 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002601
Chris Lattner67ca9252007-05-21 01:08:44 +00002602 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002603 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002604 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002605
Chris Lattner67ca9252007-05-21 01:08:44 +00002606 // Does it fit in a unsigned long?
2607 if (ResultVal.isIntN(LongSize)) {
2608 // Does it fit in a signed long?
2609 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002610 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002611 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002612 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002613 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002614 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002615 }
2616
Chris Lattner67ca9252007-05-21 01:08:44 +00002617 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002618 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002619 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002620
Chris Lattner67ca9252007-05-21 01:08:44 +00002621 // Does it fit in a unsigned long long?
2622 if (ResultVal.isIntN(LongLongSize)) {
2623 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002624 // To be compatible with MSVC, hex integer literals ending with the
2625 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002626 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2627 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002628 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002629 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002630 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002631 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002632 }
2633 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002634
Chris Lattner67ca9252007-05-21 01:08:44 +00002635 // If we still couldn't decide a type, we probably have something that
2636 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002637 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002638 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002639 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002640 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002641 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002642
Chris Lattner55258cf2008-05-09 05:59:00 +00002643 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002644 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002645 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002646 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002647 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002648
Chris Lattner1c20a172007-08-26 03:42:43 +00002649 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2650 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002651 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002652 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002653
2654 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002655}
2656
John McCalldadc5752010-08-24 06:29:42 +00002657ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002658 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002659 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002660 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002661}
2662
Steve Naroff71b59a92007-06-04 22:22:31 +00002663/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002664/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002665bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00002666 SourceLocation OpLoc,
John McCall36e7fe32010-10-12 00:20:44 +00002667 SourceRange ExprRange,
Sebastian Redl6f282892008-11-11 17:56:53 +00002668 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002669 if (exprType->isDependentType())
2670 return false;
2671
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002672 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2673 // the result is the size of the referenced type."
2674 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2675 // result shall be the alignment of the referenced type."
2676 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2677 exprType = Ref->getPointeeType();
2678
Steve Naroff043d45d2007-05-15 02:32:35 +00002679 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002680 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002681 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002682 if (isSizeof)
2683 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2684 return false;
2685 }
Mike Stump11289f42009-09-09 15:08:12 +00002686
Chris Lattner62975a72009-04-24 00:30:45 +00002687 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002688 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002689 Diag(OpLoc, diag::ext_sizeof_void_type)
2690 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002691 return false;
2692 }
Mike Stump11289f42009-09-09 15:08:12 +00002693
Chris Lattner62975a72009-04-24 00:30:45 +00002694 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002695 PDiag(diag::err_sizeof_alignof_incomplete_type)
2696 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002697 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002698
Chris Lattner62975a72009-04-24 00:30:45 +00002699 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002700 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002701 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002702 << exprType << isSizeof << ExprRange;
2703 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002704 }
Mike Stump11289f42009-09-09 15:08:12 +00002705
Chris Lattner62975a72009-04-24 00:30:45 +00002706 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002707}
2708
John McCall36e7fe32010-10-12 00:20:44 +00002709static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2710 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002711 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002712
Mike Stump11289f42009-09-09 15:08:12 +00002713 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002714 if (isa<DeclRefExpr>(E))
2715 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002716
2717 // Cannot know anything else if the expression is dependent.
2718 if (E->isTypeDependent())
2719 return false;
2720
Douglas Gregor71235ec2009-05-02 02:18:30 +00002721 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00002722 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00002723 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002724 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002725
2726 // Alignment of a field access is always okay, so long as it isn't a
2727 // bit-field.
2728 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002729 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002730 return false;
2731
John McCall36e7fe32010-10-12 00:20:44 +00002732 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
Chris Lattner8dff0172009-01-24 20:17:12 +00002733}
2734
Douglas Gregor0950e412009-03-13 21:01:28 +00002735/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002736ExprResult
John McCallbcd03502009-12-07 02:54:59 +00002737Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00002738 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002739 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002740 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002741 return ExprError();
2742
John McCallbcd03502009-12-07 02:54:59 +00002743 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002744
Douglas Gregor0950e412009-03-13 21:01:28 +00002745 if (!T->isDependentType() &&
2746 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2747 return ExprError();
2748
2749 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00002750 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00002751 Context.getSizeType(), OpLoc,
2752 R.getEnd()));
2753}
2754
2755/// \brief Build a sizeof or alignof expression given an expression
2756/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002757ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00002758Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002759 bool isSizeOf, SourceRange R) {
2760 // Verify that the operand is valid.
2761 bool isInvalid = false;
2762 if (E->isTypeDependent()) {
2763 // Delay type-checking for type-dependent expressions.
2764 } else if (!isSizeOf) {
John McCall36e7fe32010-10-12 00:20:44 +00002765 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002766 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002767 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2768 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00002769 } else if (E->getType()->isPlaceholderType()) {
2770 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2771 if (PE.isInvalid()) return ExprError();
2772 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00002773 } else {
2774 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2775 }
2776
2777 if (isInvalid)
2778 return ExprError();
2779
2780 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2781 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2782 Context.getSizeType(), OpLoc,
2783 R.getEnd()));
2784}
2785
Sebastian Redl6f282892008-11-11 17:56:53 +00002786/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2787/// the same for @c alignof and @c __alignof
2788/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002789ExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00002790Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2791 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002792 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002793 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002794
Sebastian Redl6f282892008-11-11 17:56:53 +00002795 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002796 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002797 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
John McCallbcd03502009-12-07 02:54:59 +00002798 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002799 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002800
Douglas Gregor0950e412009-03-13 21:01:28 +00002801 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00002802 ExprResult Result
Douglas Gregor0950e412009-03-13 21:01:28 +00002803 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2804
Douglas Gregor0950e412009-03-13 21:01:28 +00002805 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002806}
2807
John McCall4bc41ae2010-11-18 19:01:18 +00002808static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2809 bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002810 if (V->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002811 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002812
John McCall34376a62010-12-04 03:47:34 +00002813 // _Real and _Imag are only l-values for normal l-values.
2814 if (V->getObjectKind() != OK_Ordinary)
John McCall27584242010-12-06 20:48:59 +00002815 S.DefaultLvalueConversion(V);
John McCall34376a62010-12-04 03:47:34 +00002816
Chris Lattnere267f5d2007-08-26 05:39:26 +00002817 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00002818 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002819 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002820
Chris Lattnere267f5d2007-08-26 05:39:26 +00002821 // Otherwise they pass through real integer and floating point types here.
2822 if (V->getType()->isArithmeticType())
2823 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002824
John McCall36226622010-10-12 02:09:17 +00002825 // Test for placeholders.
John McCall4bc41ae2010-11-18 19:01:18 +00002826 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall36226622010-10-12 02:09:17 +00002827 if (PR.isInvalid()) return QualType();
2828 if (PR.take() != V) {
2829 V = PR.take();
John McCall4bc41ae2010-11-18 19:01:18 +00002830 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002831 }
2832
Chris Lattnere267f5d2007-08-26 05:39:26 +00002833 // Reject anything else.
John McCall4bc41ae2010-11-18 19:01:18 +00002834 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002835 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002836 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002837}
2838
2839
Chris Lattnere168f762006-11-10 05:29:30 +00002840
John McCalldadc5752010-08-24 06:29:42 +00002841ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002842Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002843 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002844 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002845 switch (Kind) {
2846 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002847 case tok::plusplus: Opc = UO_PostInc; break;
2848 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002849 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002850
John McCallb268a282010-08-23 23:25:46 +00002851 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002852}
2853
John McCall4bc41ae2010-11-18 19:01:18 +00002854/// Expressions of certain arbitrary types are forbidden by C from
2855/// having l-value type. These are:
2856/// - 'void', but not qualified void
2857/// - function types
2858///
2859/// The exact rule here is C99 6.3.2.1:
2860/// An lvalue is an expression with an object type or an incomplete
2861/// type other than void.
2862static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2863 return ((T->isVoidType() && !T.hasQualifiers()) ||
2864 T->isFunctionType());
2865}
2866
John McCalldadc5752010-08-24 06:29:42 +00002867ExprResult
John McCallb268a282010-08-23 23:25:46 +00002868Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2869 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002870 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002871 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002872 if (Result.isInvalid()) return ExprError();
2873 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002874
John McCallb268a282010-08-23 23:25:46 +00002875 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002876
Douglas Gregor40412ac2008-11-19 17:17:41 +00002877 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002878 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002879 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002880 Context.DependentTy,
2881 VK_LValue, OK_Ordinary,
2882 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002883 }
2884
Mike Stump11289f42009-09-09 15:08:12 +00002885 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002886 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002887 LHSExp->getType()->isEnumeralType() ||
2888 RHSExp->getType()->isRecordType() ||
2889 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002890 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002891 }
2892
John McCallb268a282010-08-23 23:25:46 +00002893 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002894}
2895
2896
John McCalldadc5752010-08-24 06:29:42 +00002897ExprResult
John McCallb268a282010-08-23 23:25:46 +00002898Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2899 Expr *Idx, SourceLocation RLoc) {
2900 Expr *LHSExp = Base;
2901 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002902
Chris Lattner36d572b2007-07-16 00:14:47 +00002903 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002904 if (!LHSExp->getType()->getAs<VectorType>())
2905 DefaultFunctionArrayLvalueConversion(LHSExp);
2906 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002907
Chris Lattner36d572b2007-07-16 00:14:47 +00002908 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00002909 ExprValueKind VK = VK_LValue;
2910 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00002911
Steve Naroffc1aadb12007-03-28 21:49:40 +00002912 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002913 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002914 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002915 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002916 Expr *BaseExpr, *IndexExpr;
2917 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002918 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2919 BaseExpr = LHSExp;
2920 IndexExpr = RHSExp;
2921 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002922 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002923 BaseExpr = LHSExp;
2924 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002925 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002926 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002927 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002928 BaseExpr = RHSExp;
2929 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002930 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002931 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002932 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002933 BaseExpr = LHSExp;
2934 IndexExpr = RHSExp;
2935 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002936 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002937 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002938 // Handle the uncommon case of "123[Ptr]".
2939 BaseExpr = RHSExp;
2940 IndexExpr = LHSExp;
2941 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00002942 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00002943 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00002944 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00002945 VK = LHSExp->getValueKind();
2946 if (VK != VK_RValue)
2947 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00002948
Chris Lattner36d572b2007-07-16 00:14:47 +00002949 // FIXME: need to deal with const...
2950 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002951 } else if (LHSTy->isArrayType()) {
2952 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00002953 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00002954 // wasn't promoted because of the C90 rule that doesn't
2955 // allow promoting non-lvalue arrays. Warn, then
2956 // force the promotion here.
2957 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2958 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002959 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCalle3027922010-08-25 11:45:40 +00002960 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002961 LHSTy = LHSExp->getType();
2962
2963 BaseExpr = LHSExp;
2964 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002965 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002966 } else if (RHSTy->isArrayType()) {
2967 // Same as previous, except for 123[f().a] case
2968 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2969 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002970 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCalle3027922010-08-25 11:45:40 +00002971 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002972 RHSTy = RHSExp->getType();
2973
2974 BaseExpr = RHSExp;
2975 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002976 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00002977 } else {
Chris Lattner003af242009-04-25 22:50:55 +00002978 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2979 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002980 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00002981 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002982 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00002983 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2984 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00002985
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002986 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00002987 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2988 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00002989 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2990
Douglas Gregorac1fb652009-03-24 19:52:54 +00002991 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00002992 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2993 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00002994 // incomplete types are not object types.
2995 if (ResultType->isFunctionType()) {
2996 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2997 << ResultType << BaseExpr->getSourceRange();
2998 return ExprError();
2999 }
Mike Stump11289f42009-09-09 15:08:12 +00003000
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003001 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3002 // GNU extension: subscripting on pointer to void
3003 Diag(LLoc, diag::ext_gnu_void_ptr)
3004 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003005
3006 // C forbids expressions of unqualified void type from being l-values.
3007 // See IsCForbiddenLValueType.
3008 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003009 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003010 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003011 PDiag(diag::err_subscript_incomplete_type)
3012 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003013 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003014
Chris Lattner62975a72009-04-24 00:30:45 +00003015 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003016 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003017 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3018 << ResultType << BaseExpr->getSourceRange();
3019 return ExprError();
3020 }
Mike Stump11289f42009-09-09 15:08:12 +00003021
John McCall4bc41ae2010-11-18 19:01:18 +00003022 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3023 !IsCForbiddenLValueType(Context, ResultType));
3024
Mike Stump4e1f26a2009-02-19 03:04:26 +00003025 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003026 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003027}
3028
John McCall4bc41ae2010-11-18 19:01:18 +00003029/// Check an ext-vector component access expression.
3030///
3031/// VK should be set in advance to the value kind of the base
3032/// expression.
3033static QualType
3034CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3035 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00003036 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00003037 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3038 // see FIXME there.
3039 //
3040 // FIXME: This logic can be greatly simplified by splitting it along
3041 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00003042 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00003043
Steve Narofff8fd09e2007-07-27 22:15:19 +00003044 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003045 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003046
Mike Stump4e1f26a2009-02-19 03:04:26 +00003047 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00003048 // special names that indicate a subset of exactly half the elements are
3049 // to be selected.
3050 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003051
Nate Begemanbb70bf62009-01-18 01:47:54 +00003052 // This flag determines whether or not CompName has an 's' char prefix,
3053 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00003054 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00003055
John McCall4bc41ae2010-11-18 19:01:18 +00003056 bool HasRepeated = false;
3057 bool HasIndex[16] = {};
3058
3059 int Idx;
3060
Nate Begemanf322eab2008-05-09 06:41:27 +00003061 // Check that we've found one of the special components, or that the component
3062 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003063 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00003064 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3065 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00003066 } else if (!HexSwizzle &&
3067 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3068 do {
3069 if (HasIndex[Idx]) HasRepeated = true;
3070 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003071 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003072 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3073 } else {
3074 if (HexSwizzle) compStr++;
3075 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3076 if (HasIndex[Idx]) HasRepeated = true;
3077 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003078 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003079 }
Chris Lattner7e152db2007-08-02 22:33:49 +00003080 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00003081
Mike Stump4e1f26a2009-02-19 03:04:26 +00003082 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00003083 // We didn't get to the end of the string. This means the component names
3084 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00003085 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003086 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00003087 return QualType();
3088 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003089
Nate Begemanbb70bf62009-01-18 01:47:54 +00003090 // Ensure no component accessor exceeds the width of the vector type it
3091 // operates on.
3092 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003093 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003094
3095 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00003096 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00003097
3098 while (*compStr) {
3099 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00003100 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00003101 << baseType << SourceRange(CompLoc);
3102 return QualType();
3103 }
3104 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00003105 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003106
Steve Narofff8fd09e2007-07-27 22:15:19 +00003107 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003108 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00003109 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00003110 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00003111 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00003112 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00003113 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003114 if (HexSwizzle)
3115 CompSize--;
3116
Steve Narofff8fd09e2007-07-27 22:15:19 +00003117 if (CompSize == 1)
3118 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003119
John McCall4bc41ae2010-11-18 19:01:18 +00003120 if (HasRepeated) VK = VK_RValue;
3121
3122 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003123 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003124 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003125 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3126 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3127 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003128 }
3129 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003130}
3131
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003132static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003133 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003134 const Selector &Sel,
3135 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003136 if (Member)
3137 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3138 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003139 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003140 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003141
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003142 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3143 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003144 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3145 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003146 return D;
3147 }
3148 return 0;
3149}
3150
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003151static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3152 IdentifierInfo *Member,
3153 const Selector &Sel,
3154 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003155 // Check protocols on qualified interfaces.
3156 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003157 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003158 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003159 if (Member)
3160 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3161 GDecl = PD;
3162 break;
3163 }
3164 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003165 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003166 GDecl = OMD;
3167 break;
3168 }
3169 }
3170 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003171 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003172 E = QIdTy->qual_end(); I != E; ++I) {
3173 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003174 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3175 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003176 if (GDecl)
3177 return GDecl;
3178 }
3179 }
3180 return GDecl;
3181}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003182
John McCalldadc5752010-08-24 06:29:42 +00003183ExprResult
John McCallb268a282010-08-23 23:25:46 +00003184Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003185 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003186 const CXXScopeSpec &SS,
3187 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003188 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003189 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003190 // Even in dependent contexts, try to diagnose base expressions with
3191 // obviously wrong types, e.g.:
3192 //
3193 // T* t;
3194 // t.f;
3195 //
3196 // In Obj-C++, however, the above expression is valid, since it could be
3197 // accessing the 'f' property if T is an Obj-C interface. The extra check
3198 // allows this, while still reporting an error if T is a struct pointer.
3199 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003200 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003201 if (PT && (!getLangOptions().ObjC1 ||
3202 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003203 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003204 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003205 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003206 return ExprError();
3207 }
3208 }
3209
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003210 assert(BaseType->isDependentType() ||
3211 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003212 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003213
3214 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3215 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003216 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003217 IsArrow, OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003218 SS.getScopeRep(),
John McCall10eae182009-11-30 22:42:35 +00003219 SS.getRange(),
3220 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003221 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003222}
3223
3224/// We know that the given qualified member reference points only to
3225/// declarations which do not belong to the static type of the base
3226/// expression. Diagnose the problem.
3227static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3228 Expr *BaseExpr,
3229 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003230 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00003231 NamedDecl *rep,
3232 const DeclarationNameInfo &nameInfo) {
John McCallcd4b4772009-12-02 03:53:29 +00003233 // If this is an implicit member access, use a different set of
3234 // diagnostics.
3235 if (!BaseExpr)
John McCallf3a88602011-02-03 08:15:49 +00003236 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall10eae182009-11-30 22:42:35 +00003237
John McCallf3a88602011-02-03 08:15:49 +00003238 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3239 << SS.getRange() << rep << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003240}
3241
3242// Check whether the declarations we found through a nested-name
3243// specifier in a member expression are actually members of the base
3244// type. The restriction here is:
3245//
3246// C++ [expr.ref]p2:
3247// ... In these cases, the id-expression shall name a
3248// member of the class or of one of its base classes.
3249//
3250// So it's perfectly legitimate for the nested-name specifier to name
3251// an unrelated class, and for us to find an overload set including
3252// decls from classes which are not superclasses, as long as the decl
3253// we actually pick through overload resolution is from a superclass.
3254bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3255 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003256 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003257 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003258 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3259 if (!BaseRT) {
3260 // We can't check this yet because the base type is still
3261 // dependent.
3262 assert(BaseType->isDependentType());
3263 return false;
3264 }
3265 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003266
3267 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003268 // If this is an implicit member reference and we find a
3269 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003270 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003271 return false;
John McCall10eae182009-11-30 22:42:35 +00003272
John McCall2d74de92009-12-01 22:10:20 +00003273 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003274 DeclContext *DC = (*I)->getDeclContext();
3275 while (DC->isTransparentContext())
3276 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003277
Douglas Gregora9c3e822010-07-28 22:27:52 +00003278 if (!DC->isRecord())
3279 continue;
3280
John McCall2d74de92009-12-01 22:10:20 +00003281 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003282 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003283
3284 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3285 return false;
3286 }
3287
John McCallf3a88602011-02-03 08:15:49 +00003288 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3289 R.getRepresentativeDecl(),
3290 R.getLookupNameInfo());
John McCall2d74de92009-12-01 22:10:20 +00003291 return true;
3292}
3293
3294static bool
3295LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3296 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003297 SourceLocation OpLoc, CXXScopeSpec &SS,
3298 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003299 RecordDecl *RDecl = RTy->getDecl();
3300 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003301 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003302 << BaseRange))
3303 return true;
3304
John McCalle9cccd82010-06-16 08:42:20 +00003305 if (HasTemplateArgs) {
3306 // LookupTemplateName doesn't expect these both to exist simultaneously.
3307 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3308
3309 bool MOUS;
3310 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3311 return false;
3312 }
3313
John McCall2d74de92009-12-01 22:10:20 +00003314 DeclContext *DC = RDecl;
3315 if (SS.isSet()) {
3316 // If the member name was a qualified-id, look into the
3317 // nested-name-specifier.
3318 DC = SemaRef.computeDeclContext(SS, false);
3319
John McCall0b66eb32010-05-01 00:40:08 +00003320 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003321 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3322 << SS.getRange() << DC;
3323 return true;
3324 }
3325
John McCall2d74de92009-12-01 22:10:20 +00003326 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003327
John McCall2d74de92009-12-01 22:10:20 +00003328 if (!isa<TypeDecl>(DC)) {
3329 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3330 << DC << SS.getRange();
3331 return true;
John McCall10eae182009-11-30 22:42:35 +00003332 }
3333 }
3334
John McCall2d74de92009-12-01 22:10:20 +00003335 // The record definition is complete, now look up the member.
3336 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003337
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003338 if (!R.empty())
3339 return false;
3340
3341 // We didn't find anything with the given name, so try to correct
3342 // for typos.
3343 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003344 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003345 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003346 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3347 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3348 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003349 << FixItHint::CreateReplacement(R.getNameLoc(),
3350 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003351 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3352 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3353 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003354 return false;
3355 } else {
3356 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003357 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003358 }
3359
John McCall10eae182009-11-30 22:42:35 +00003360 return false;
3361}
3362
John McCalldadc5752010-08-24 06:29:42 +00003363ExprResult
John McCallb268a282010-08-23 23:25:46 +00003364Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003365 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003366 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003367 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003368 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003369 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003370 if (BaseType->isDependentType() ||
3371 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003372 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003373 IsArrow, OpLoc,
3374 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003375 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003376
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003377 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003378
John McCall2d74de92009-12-01 22:10:20 +00003379 // Implicit member accesses.
3380 if (!Base) {
3381 QualType RecordTy = BaseType;
3382 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3383 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3384 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003385 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003386 return ExprError();
3387
3388 // Explicit member accesses.
3389 } else {
John McCalldadc5752010-08-24 06:29:42 +00003390 ExprResult Result =
John McCall2d74de92009-12-01 22:10:20 +00003391 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003392 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003393
3394 if (Result.isInvalid()) {
3395 Owned(Base);
3396 return ExprError();
3397 }
3398
3399 if (Result.get())
3400 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003401
3402 // LookupMemberExpr can modify Base, and thus change BaseType
3403 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003404 }
3405
John McCallb268a282010-08-23 23:25:46 +00003406 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003407 OpLoc, IsArrow, SS, FirstQualifierInScope,
3408 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003409}
3410
John McCalldadc5752010-08-24 06:29:42 +00003411ExprResult
John McCallb268a282010-08-23 23:25:46 +00003412Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003413 SourceLocation OpLoc, bool IsArrow,
3414 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003415 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003416 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003417 const TemplateArgumentListInfo *TemplateArgs,
3418 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003419 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003420 if (IsArrow) {
3421 assert(BaseType->isPointerType());
3422 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3423 }
John McCalla8ae2222010-04-06 21:38:20 +00003424 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003425
John McCallb268a282010-08-23 23:25:46 +00003426 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003427 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3428 DeclarationName MemberName = MemberNameInfo.getName();
3429 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003430
3431 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003432 return ExprError();
3433
John McCall10eae182009-11-30 22:42:35 +00003434 if (R.empty()) {
3435 // Rederive where we looked up.
3436 DeclContext *DC = (SS.isSet()
3437 ? computeDeclContext(SS, false)
3438 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003439
John McCall10eae182009-11-30 22:42:35 +00003440 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003441 << MemberName << DC
3442 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003443 return ExprError();
3444 }
3445
John McCall38836f02010-01-15 08:34:02 +00003446 // Diagnose lookups that find only declarations from a non-base
3447 // type. This is possible for either qualified lookups (which may
3448 // have been qualified with an unrelated type) or implicit member
3449 // expressions (which were found with unqualified lookup and thus
3450 // may have come from an enclosing scope). Note that it's okay for
3451 // lookup to find declarations from a non-base type as long as those
3452 // aren't the ones picked by overload resolution.
3453 if ((SS.isSet() || !BaseExpr ||
3454 (isa<CXXThisExpr>(BaseExpr) &&
3455 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003456 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003457 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003458 return ExprError();
3459
3460 // Construct an unresolved result if we in fact got an unresolved
3461 // result.
3462 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003463 // Suppress any lookup-related diagnostics; we'll do these when we
3464 // pick a member.
3465 R.suppressDiagnostics();
3466
John McCall10eae182009-11-30 22:42:35 +00003467 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003468 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003469 BaseExpr, BaseExprType,
3470 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003471 Qualifier, SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003472 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003473 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003474
3475 return Owned(MemExpr);
3476 }
3477
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003478 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003479 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003480 NamedDecl *MemberDecl = R.getFoundDecl();
3481
3482 // FIXME: diagnose the presence of template arguments now.
3483
3484 // If the decl being referenced had an error, return an error for this
3485 // sub-expr without emitting another error, in order to avoid cascading
3486 // error cases.
3487 if (MemberDecl->isInvalidDecl())
3488 return ExprError();
3489
John McCall2d74de92009-12-01 22:10:20 +00003490 // Handle the implicit-member-access case.
3491 if (!BaseExpr) {
3492 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003493 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003494 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003495
Douglas Gregorb15af892010-01-07 23:12:05 +00003496 SourceLocation Loc = R.getNameLoc();
3497 if (SS.getRange().isValid())
3498 Loc = SS.getRange().getBegin();
3499 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003500 }
3501
John McCall10eae182009-11-30 22:42:35 +00003502 bool ShouldCheckUse = true;
3503 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3504 // Don't diagnose the use of a virtual member function unless it's
3505 // explicitly qualified.
3506 if (MD->isVirtual() && !SS.isSet())
3507 ShouldCheckUse = false;
3508 }
3509
3510 // Check the use of this member.
3511 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3512 Owned(BaseExpr);
3513 return ExprError();
3514 }
3515
John McCall34376a62010-12-04 03:47:34 +00003516 // Perform a property load on the base regardless of whether we
3517 // actually need it for the declaration.
3518 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3519 ConvertPropertyForRValue(BaseExpr);
3520
John McCallfeb624a2010-11-23 20:48:44 +00003521 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3522 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3523 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003524
Francois Pichet783dd6e2010-11-21 06:08:52 +00003525 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3526 // We may have found a field within an anonymous union or struct
3527 // (C++ [class.union]).
John McCallf3a88602011-02-03 08:15:49 +00003528 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00003529 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003530
John McCall10eae182009-11-30 22:42:35 +00003531 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3532 MarkDeclarationReferenced(MemberLoc, Var);
3533 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003534 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003535 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003536 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003537 }
3538
John McCall7decc9e2010-11-18 06:31:45 +00003539 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall10eae182009-11-30 22:42:35 +00003540 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3541 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003542 MemberFn, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003543 MemberFn->getType(),
3544 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3545 OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003546 }
John McCall7decc9e2010-11-18 06:31:45 +00003547 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003548
3549 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3550 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3551 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003552 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003553 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003554 }
3555
3556 Owned(BaseExpr);
3557
Douglas Gregor861eb802010-04-25 20:55:08 +00003558 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003559 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003560 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003561 << MemberName << BaseType << int(IsArrow);
3562 else
3563 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3564 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003565
Douglas Gregor861eb802010-04-25 20:55:08 +00003566 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3567 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003568 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003569 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003570}
3571
John McCall68fc88ec2010-12-15 16:46:44 +00003572/// Given that normal member access failed on the given expression,
3573/// and given that the expression's type involves builtin-id or
3574/// builtin-Class, decide whether substituting in the redefinition
3575/// types would be profitable. The redefinition type is whatever
3576/// this translation unit tried to typedef to id/Class; we store
3577/// it to the side and then re-use it in places like this.
3578static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3579 const ObjCObjectPointerType *opty
3580 = base->getType()->getAs<ObjCObjectPointerType>();
3581 if (!opty) return false;
3582
3583 const ObjCObjectType *ty = opty->getObjectType();
3584
3585 QualType redef;
3586 if (ty->isObjCId()) {
3587 redef = S.Context.ObjCIdRedefinitionType;
3588 } else if (ty->isObjCClass()) {
3589 redef = S.Context.ObjCClassRedefinitionType;
3590 } else {
3591 return false;
3592 }
3593
3594 // Do the substitution as long as the redefinition type isn't just a
3595 // possibly-qualified pointer to builtin-id or builtin-Class again.
3596 opty = redef->getAs<ObjCObjectPointerType>();
3597 if (opty && !opty->getObjectType()->getInterface() != 0)
3598 return false;
3599
3600 S.ImpCastExprToType(base, redef, CK_BitCast);
3601 return true;
3602}
3603
John McCall10eae182009-11-30 22:42:35 +00003604/// Look up the given member of the given non-type-dependent
3605/// expression. This can return in one of two ways:
3606/// * If it returns a sentinel null-but-valid result, the caller will
3607/// assume that lookup was performed and the results written into
3608/// the provided structure. It will take over from there.
3609/// * Otherwise, the returned expression will be produced in place of
3610/// an ordinary member expression.
3611///
3612/// The ObjCImpDecl bit is a gross hack that will need to be properly
3613/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00003614ExprResult
John McCall10eae182009-11-30 22:42:35 +00003615Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00003616 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003617 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00003618 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003619 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00003620
Steve Naroffeaaae462007-12-16 21:42:28 +00003621 // Perform default conversions.
3622 DefaultFunctionArrayConversion(BaseExpr);
John McCall15317a22010-12-15 04:42:30 +00003623 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003624
Steve Naroff185616f2007-07-26 03:11:44 +00003625 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00003626 assert(!BaseType->isDependentType());
3627
3628 DeclarationName MemberName = R.getLookupName();
3629 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00003630
John McCall68fc88ec2010-12-15 16:46:44 +00003631 // For later type-checking purposes, turn arrow accesses into dot
3632 // accesses. The only access type we support that doesn't follow
3633 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3634 // and those never use arrows, so this is unaffected.
3635 if (IsArrow) {
3636 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3637 BaseType = Ptr->getPointeeType();
3638 else if (const ObjCObjectPointerType *Ptr
3639 = BaseType->getAs<ObjCObjectPointerType>())
3640 BaseType = Ptr->getPointeeType();
3641 else if (BaseType->isRecordType()) {
3642 // Recover from arrow accesses to records, e.g.:
3643 // struct MyRecord foo;
3644 // foo->bar
3645 // This is actually well-formed in C++ if MyRecord has an
3646 // overloaded operator->, but that should have been dealt with
3647 // by now.
3648 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3649 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3650 << FixItHint::CreateReplacement(OpLoc, ".");
3651 IsArrow = false;
3652 } else {
3653 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3654 << BaseType << BaseExpr->getSourceRange();
3655 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00003656 }
3657 }
3658
John McCall68fc88ec2010-12-15 16:46:44 +00003659 // Handle field access to simple records.
3660 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3661 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3662 RTy, OpLoc, SS, HasTemplateArgs))
3663 return ExprError();
3664
3665 // Returning valid-but-null is how we indicate to the caller that
3666 // the lookup result was filled in.
3667 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00003668 }
John McCall10eae182009-11-30 22:42:35 +00003669
John McCall68fc88ec2010-12-15 16:46:44 +00003670 // Handle ivar access to Objective-C objects.
3671 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003672 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00003673
3674 // There are three cases for the base type:
3675 // - builtin id (qualified or unqualified)
3676 // - builtin Class (qualified or unqualified)
3677 // - an interface
3678 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3679 if (!IDecl) {
3680 // There's an implicit 'isa' ivar on all objects.
3681 // But we only actually find it this way on objects of type 'id',
3682 // apparently.
3683 if (OTy->isObjCId() && Member->isStr("isa"))
3684 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3685 Context.getObjCClassType()));
3686
3687 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3688 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3689 ObjCImpDecl, HasTemplateArgs);
3690 goto fail;
3691 }
3692
3693 ObjCInterfaceDecl *ClassDeclared;
3694 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3695
3696 if (!IV) {
3697 // Attempt to correct for typos in ivar names.
3698 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3699 LookupMemberName);
3700 if (CorrectTypo(Res, 0, 0, IDecl, false,
3701 IsArrow ? CTC_ObjCIvarLookup
3702 : CTC_ObjCPropertyLookup) &&
3703 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3704 Diag(R.getNameLoc(),
3705 diag::err_typecheck_member_reference_ivar_suggest)
3706 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3707 << FixItHint::CreateReplacement(R.getNameLoc(),
3708 IV->getNameAsString());
3709 Diag(IV->getLocation(), diag::note_previous_decl)
3710 << IV->getDeclName();
3711 } else {
3712 Res.clear();
3713 Res.setLookupName(Member);
3714
3715 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3716 << IDecl->getDeclName() << MemberName
3717 << BaseExpr->getSourceRange();
3718 return ExprError();
3719 }
3720 }
3721
3722 // If the decl being referenced had an error, return an error for this
3723 // sub-expr without emitting another error, in order to avoid cascading
3724 // error cases.
3725 if (IV->isInvalidDecl())
3726 return ExprError();
3727
3728 // Check whether we can reference this field.
3729 if (DiagnoseUseOfDecl(IV, MemberLoc))
3730 return ExprError();
3731 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3732 IV->getAccessControl() != ObjCIvarDecl::Package) {
3733 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3734 if (ObjCMethodDecl *MD = getCurMethodDecl())
3735 ClassOfMethodDecl = MD->getClassInterface();
3736 else if (ObjCImpDecl && getCurFunctionDecl()) {
3737 // Case of a c-function declared inside an objc implementation.
3738 // FIXME: For a c-style function nested inside an objc implementation
3739 // class, there is no implementation context available, so we pass
3740 // down the context as argument to this routine. Ideally, this context
3741 // need be passed down in the AST node and somehow calculated from the
3742 // AST for a function decl.
3743 if (ObjCImplementationDecl *IMPD =
3744 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3745 ClassOfMethodDecl = IMPD->getClassInterface();
3746 else if (ObjCCategoryImplDecl* CatImplClass =
3747 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3748 ClassOfMethodDecl = CatImplClass->getClassInterface();
3749 }
3750
3751 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3752 if (ClassDeclared != IDecl ||
3753 ClassOfMethodDecl != ClassDeclared)
3754 Diag(MemberLoc, diag::error_private_ivar_access)
3755 << IV->getDeclName();
3756 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3757 // @protected
3758 Diag(MemberLoc, diag::error_protected_ivar_access)
3759 << IV->getDeclName();
3760 }
3761
3762 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3763 MemberLoc, BaseExpr,
3764 IsArrow));
3765 }
3766
3767 // Objective-C property access.
3768 const ObjCObjectPointerType *OPT;
3769 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3770 // This actually uses the base as an r-value.
3771 DefaultLvalueConversion(BaseExpr);
3772 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3773
3774 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3775
3776 const ObjCObjectType *OT = OPT->getObjectType();
3777
3778 // id, with and without qualifiers.
3779 if (OT->isObjCId()) {
3780 // Check protocols on qualified interfaces.
3781 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3782 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3783 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3784 // Check the use of this declaration
3785 if (DiagnoseUseOfDecl(PD, MemberLoc))
3786 return ExprError();
3787
3788 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3789 VK_LValue,
3790 OK_ObjCProperty,
3791 MemberLoc,
3792 BaseExpr));
3793 }
3794
3795 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3796 // Check the use of this method.
3797 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3798 return ExprError();
3799 Selector SetterSel =
3800 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3801 PP.getSelectorTable(), Member);
3802 ObjCMethodDecl *SMD = 0;
3803 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3804 SetterSel, Context))
3805 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3806 QualType PType = OMD->getSendResultType();
3807
3808 ExprValueKind VK = VK_LValue;
3809 if (!getLangOptions().CPlusPlus &&
3810 IsCForbiddenLValueType(Context, PType))
3811 VK = VK_RValue;
3812 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3813
3814 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3815 VK, OK,
3816 MemberLoc, BaseExpr));
3817 }
3818 }
3819
3820 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3821 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3822 ObjCImpDecl, HasTemplateArgs);
3823
3824 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3825 << MemberName << BaseType);
3826 }
3827
3828 // 'Class', unqualified only.
3829 if (OT->isObjCClass()) {
3830 // Only works in a method declaration (??!).
3831 ObjCMethodDecl *MD = getCurMethodDecl();
3832 if (!MD) {
3833 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3834 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3835 ObjCImpDecl, HasTemplateArgs);
3836
3837 goto fail;
3838 }
3839
3840 // Also must look for a getter name which uses property syntax.
3841 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003842 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3843 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003844 if ((Getter = IFace->lookupClassMethod(Sel))) {
3845 // Check the use of this method.
3846 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3847 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00003848 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003849 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003850 // If we found a getter then this may be a valid dot-reference, we
3851 // will look for the matching setter, in case it is needed.
3852 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00003853 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3854 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003855 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3856 if (!Setter) {
3857 // If this reference is in an @implementation, also check for 'private'
3858 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003859 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003860 }
3861 // Look through local category implementations associated with the class.
3862 if (!Setter)
3863 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003864
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003865 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3866 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003867
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003868 if (Getter || Setter) {
3869 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003870
John McCall4bc41ae2010-11-18 19:01:18 +00003871 ExprValueKind VK = VK_LValue;
3872 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00003873 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00003874 if (!getLangOptions().CPlusPlus &&
3875 IsCForbiddenLValueType(Context, PType))
3876 VK = VK_RValue;
3877 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003878 // Get the expression type from Setter's incoming parameter.
3879 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00003880 }
3881 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3882
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003883 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00003884 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3885 PType, VK, OK,
3886 MemberLoc, BaseExpr));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003887 }
John McCall68fc88ec2010-12-15 16:46:44 +00003888
3889 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3890 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3891 ObjCImpDecl, HasTemplateArgs);
3892
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003893 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00003894 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003895 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003896
John McCall68fc88ec2010-12-15 16:46:44 +00003897 // Normal property access.
3898 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3899 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003900 }
Alexis Huntc46382e2010-04-28 23:02:27 +00003901
Chris Lattnerb63a7452008-07-21 04:28:12 +00003902 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003903 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00003904 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00003905 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall15317a22010-12-15 04:42:30 +00003906 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00003907 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3908 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00003909 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003910 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00003911
3912 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3913 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003914 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003915
John McCall68fc88ec2010-12-15 16:46:44 +00003916 // Adjust builtin-sel to the appropriate redefinition type if that's
3917 // not just a pointer to builtin-sel again.
3918 if (IsArrow &&
3919 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
3920 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
3921 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
3922 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3923 ObjCImpDecl, HasTemplateArgs);
3924 }
3925
3926 // Failure cases.
3927 fail:
3928
3929 // There's a possible road to recovery for function types.
3930 const FunctionType *Fun = 0;
3931
3932 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
3933 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
3934 // fall out, handled below.
3935
3936 // Recover from dot accesses to pointers, e.g.:
3937 // type *foo;
3938 // foo.bar
3939 // This is actually well-formed in two cases:
3940 // - 'type' is an Objective C type
3941 // - 'bar' is a pseudo-destructor name which happens to refer to
3942 // the appropriate pointer type
Argyrios Kyrtzidiscd81fe02011-01-25 23:16:36 +00003943 } else if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
John McCall68fc88ec2010-12-15 16:46:44 +00003944 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3945 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3946 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3947 << FixItHint::CreateReplacement(OpLoc, "->");
3948
3949 // Recurse as an -> access.
3950 IsArrow = true;
3951 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3952 ObjCImpDecl, HasTemplateArgs);
3953 }
3954 } else {
3955 Fun = BaseType->getAs<FunctionType>();
3956 }
3957
3958 // If the user is trying to apply -> or . to a function pointer
3959 // type, it's probably because they forgot parentheses to call that
3960 // function. Suggest the addition of those parentheses, build the
3961 // call, and continue on.
3962 if (Fun || BaseType == Context.OverloadTy) {
3963 bool TryCall;
3964 if (BaseType == Context.OverloadTy) {
3965 TryCall = true;
3966 } else {
3967 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
3968 TryCall = (FPT->getNumArgs() == 0);
3969 } else {
3970 TryCall = true;
3971 }
3972
3973 if (TryCall) {
3974 QualType ResultTy = Fun->getResultType();
3975 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
3976 (IsArrow && ResultTy->isPointerType() &&
3977 ResultTy->getAs<PointerType>()->getPointeeType()->isRecordType());
3978 }
3979 }
3980
3981
3982 if (TryCall) {
3983 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
3984 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
3985 << QualType(Fun, 0)
3986 << FixItHint::CreateInsertion(Loc, "()");
3987
3988 ExprResult NewBase
3989 = ActOnCallExpr(0, BaseExpr, Loc, MultiExprArg(*this, 0, 0), Loc);
3990 if (NewBase.isInvalid())
3991 return ExprError();
3992 BaseExpr = NewBase.takeAs<Expr>();
3993
3994
3995 DefaultFunctionArrayConversion(BaseExpr);
3996 BaseType = BaseExpr->getType();
3997
3998 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3999 ObjCImpDecl, HasTemplateArgs);
4000 }
4001 }
4002
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004003 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
4004 << BaseType << BaseExpr->getSourceRange();
4005
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004006 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00004007}
4008
John McCall10eae182009-11-30 22:42:35 +00004009/// The main callback when the parser finds something like
4010/// expression . [nested-name-specifier] identifier
4011/// expression -> [nested-name-specifier] identifier
4012/// where 'identifier' encompasses a fairly broad spectrum of
4013/// possibilities, including destructor and operator references.
4014///
4015/// \param OpKind either tok::arrow or tok::period
4016/// \param HasTrailingLParen whether the next token is '(', which
4017/// is used to diagnose mis-uses of special members that can
4018/// only be called
4019/// \param ObjCImpDecl the current ObjC @implementation decl;
4020/// this is an ugly hack around the fact that ObjC @implementations
4021/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00004022ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00004023 SourceLocation OpLoc,
4024 tok::TokenKind OpKind,
4025 CXXScopeSpec &SS,
4026 UnqualifiedId &Id,
4027 Decl *ObjCImpDecl,
4028 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00004029 if (SS.isSet() && SS.isInvalid())
4030 return ExprError();
4031
Francois Pichet64225792011-01-18 05:04:39 +00004032 // Warn about the explicit constructor calls Microsoft extension.
4033 if (getLangOptions().Microsoft &&
4034 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4035 Diag(Id.getSourceRange().getBegin(),
4036 diag::ext_ms_explicit_constructor_call);
4037
John McCall10eae182009-11-30 22:42:35 +00004038 TemplateArgumentListInfo TemplateArgsBuffer;
4039
4040 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004041 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00004042 const TemplateArgumentListInfo *TemplateArgs;
4043 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004044 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004045
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004046 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00004047 bool IsArrow = (OpKind == tok::arrow);
4048
4049 NamedDecl *FirstQualifierInScope
4050 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4051 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4052
4053 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004054 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004055 if (Result.isInvalid()) return ExprError();
4056 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00004057
Douglas Gregor41f90302010-04-12 20:54:26 +00004058 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4059 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00004060 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00004061 IsArrow, OpLoc,
4062 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004063 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004064 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004065 LookupResult R(*this, NameInfo, LookupMemberName);
John McCalle9cccd82010-06-16 08:42:20 +00004066 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
4067 SS, ObjCImpDecl, TemplateArgs != 0);
Alexis Huntc46382e2010-04-28 23:02:27 +00004068
John McCalle9cccd82010-06-16 08:42:20 +00004069 if (Result.isInvalid()) {
4070 Owned(Base);
4071 return ExprError();
4072 }
John McCall10eae182009-11-30 22:42:35 +00004073
John McCalle9cccd82010-06-16 08:42:20 +00004074 if (Result.get()) {
4075 // The only way a reference to a destructor can be used is to
4076 // immediately call it, which falls into this case. If the
4077 // next token is not a '(', produce a diagnostic and build the
4078 // call now.
4079 if (!HasTrailingLParen &&
4080 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00004081 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00004082
John McCalle9cccd82010-06-16 08:42:20 +00004083 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00004084 }
4085
John McCallb268a282010-08-23 23:25:46 +00004086 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00004087 OpLoc, IsArrow, SS, FirstQualifierInScope,
4088 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004089 }
4090
4091 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00004092}
4093
John McCalldadc5752010-08-24 06:29:42 +00004094ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004095 FunctionDecl *FD,
4096 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004097 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004098 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004099 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004100 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004101 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004102 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004103 return ExprError();
4104 }
4105
4106 if (Param->hasUninstantiatedDefaultArg()) {
4107 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004108
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004109 // Instantiate the expression.
4110 MultiLevelTemplateArgumentList ArgList
4111 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004112
Nico Weber44887f62010-11-29 18:19:25 +00004113 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004114 = ArgList.getInnermost();
4115 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4116 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00004117
Nico Weber44887f62010-11-29 18:19:25 +00004118 ExprResult Result;
4119 {
4120 // C++ [dcl.fct.default]p5:
4121 // The names in the [default argument] expression are bound, and
4122 // the semantic constraints are checked, at the point where the
4123 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004124 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004125 Result = SubstExpr(UninstExpr, ArgList);
4126 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004127 if (Result.isInvalid())
4128 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004129
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004130 // Check the expression as an initializer for the parameter.
4131 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004132 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004133 InitializationKind Kind
4134 = InitializationKind::CreateCopy(Param->getLocation(),
4135 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4136 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004137
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004138 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4139 Result = InitSeq.Perform(*this, Entity, Kind,
4140 MultiExprArg(*this, &ResultE, 1));
4141 if (Result.isInvalid())
4142 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004143
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004144 // Build the default argument expression.
4145 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4146 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004147 }
4148
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004149 // If the default expression creates temporaries, we need to
4150 // push them to the current stack of expression temporaries so they'll
4151 // be properly destroyed.
4152 // FIXME: We should really be rebuilding the default argument with new
4153 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004154 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4155 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4156 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4157 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4158 ExprTemporaries.push_back(Temporary);
4159 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004160
4161 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004162 // Just mark all of the declarations in this potentially-evaluated expression
4163 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004164 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004165 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004166}
4167
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004168/// ConvertArgumentsForCall - Converts the arguments specified in
4169/// Args/NumArgs to the parameter types of the function FDecl with
4170/// function prototype Proto. Call is the call expression itself, and
4171/// Fn is the function expression. For a C++ member function, this
4172/// routine does not attempt to convert the object argument. Returns
4173/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004174bool
4175Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004176 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004177 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004178 Expr **Args, unsigned NumArgs,
4179 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004180 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004181 // assignment, to the types of the corresponding parameter, ...
4182 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004183 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004184
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004185 // If too few arguments are available (and we don't have default
4186 // arguments for the remaining parameters), don't make the call.
4187 if (NumArgs < NumArgsInProto) {
4188 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4189 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004190 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004191 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004192 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004193 }
4194
4195 // If too many are passed and not variadic, error on the extras and drop
4196 // them.
4197 if (NumArgs > NumArgsInProto) {
4198 if (!Proto->isVariadic()) {
4199 Diag(Args[NumArgsInProto]->getLocStart(),
4200 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004201 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004202 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004203 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4204 Args[NumArgs-1]->getLocEnd());
4205 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004206 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004207 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004208 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004209 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004210 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004211 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004212 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4213 if (Fn->getType()->isBlockPointerType())
4214 CallType = VariadicBlock; // Block
4215 else if (isa<MemberExpr>(Fn))
4216 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004217 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004218 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004219 if (Invalid)
4220 return true;
4221 unsigned TotalNumArgs = AllArgs.size();
4222 for (unsigned i = 0; i < TotalNumArgs; ++i)
4223 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004224
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004225 return false;
4226}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004227
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004228bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4229 FunctionDecl *FDecl,
4230 const FunctionProtoType *Proto,
4231 unsigned FirstProtoArg,
4232 Expr **Args, unsigned NumArgs,
4233 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004234 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004235 unsigned NumArgsInProto = Proto->getNumArgs();
4236 unsigned NumArgsToCheck = NumArgs;
4237 bool Invalid = false;
4238 if (NumArgs != NumArgsInProto)
4239 // Use default arguments for missing arguments
4240 NumArgsToCheck = NumArgsInProto;
4241 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004242 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004243 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004244 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004245
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004246 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004247 if (ArgIx < NumArgs) {
4248 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004249
Eli Friedman3164fb12009-03-22 22:00:50 +00004250 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4251 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004252 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004253 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004254 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004255
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004256 // Pass the argument
4257 ParmVarDecl *Param = 0;
4258 if (FDecl && i < FDecl->getNumParams())
4259 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004260
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004261 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004262 Param? InitializedEntity::InitializeParameter(Context, Param)
4263 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004264 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004265 SourceLocation(),
4266 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004267 if (ArgE.isInvalid())
4268 return true;
4269
4270 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004271 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004272 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004273
John McCalldadc5752010-08-24 06:29:42 +00004274 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004275 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004276 if (ArgExpr.isInvalid())
4277 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004278
Anders Carlsson355933d2009-08-25 03:49:14 +00004279 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004280 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004281 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004282 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004283
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004284 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004285 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004286 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004287 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004288 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004289 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004290 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004291 }
4292 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004293 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004294}
4295
Steve Naroff83895f72007-09-16 03:34:24 +00004296/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004297/// This provides the location of the left/right parens and a list of comma
4298/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004299ExprResult
John McCallb268a282010-08-23 23:25:46 +00004300Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004301 MultiExprArg args, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004302 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004303
4304 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004305 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004306 if (Result.isInvalid()) return ExprError();
4307 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004308
John McCallb268a282010-08-23 23:25:46 +00004309 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004310
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004311 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004312 // If this is a pseudo-destructor expression, build the call immediately.
4313 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4314 if (NumArgs > 0) {
4315 // Pseudo-destructor calls should not have any arguments.
4316 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004317 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004318 SourceRange(Args[0]->getLocStart(),
4319 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004320
Douglas Gregorad8a3362009-09-04 17:36:40 +00004321 NumArgs = 0;
4322 }
Mike Stump11289f42009-09-09 15:08:12 +00004323
Douglas Gregorad8a3362009-09-04 17:36:40 +00004324 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004325 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004326 }
Mike Stump11289f42009-09-09 15:08:12 +00004327
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004328 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004329 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004330 // FIXME: Will need to cache the results of name lookup (including ADL) in
4331 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004332 bool Dependent = false;
4333 if (Fn->isTypeDependent())
4334 Dependent = true;
4335 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4336 Dependent = true;
4337
4338 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004339 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00004340 Context.DependentTy, VK_RValue,
4341 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004342
4343 // Determine whether this is a call to an object (C++ [over.call.object]).
4344 if (Fn->getType()->isRecordType())
4345 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004346 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004347
John McCall10eae182009-11-30 22:42:35 +00004348 Expr *NakedFn = Fn->IgnoreParens();
4349
4350 // Determine whether this is a call to an unresolved member function.
4351 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4352 // If lookup was unresolved but not dependent (i.e. didn't find
4353 // an unresolved using declaration), it has to be an overloaded
4354 // function set, which means it must contain either multiple
4355 // declarations (all methods or method templates) or a single
4356 // method template.
4357 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00004358 isa<FunctionTemplateDecl>(
4359 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00004360 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00004361
John McCall2d74de92009-12-01 22:10:20 +00004362 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004363 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004364 }
4365
Douglas Gregore254f902009-02-04 00:32:51 +00004366 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00004367 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004368 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00004369 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00004370 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004371 RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004372 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004373
Anders Carlsson61914b52009-10-03 17:40:22 +00004374 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00004375 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCalle3027922010-08-25 11:45:40 +00004376 if (BO->getOpcode() == BO_PtrMemD ||
4377 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00004378 if (const FunctionProtoType *FPT
4379 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004380 QualType ResultTy = FPT->getCallResultType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004381 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004382
Douglas Gregor125fa402011-02-04 12:57:49 +00004383 // Check that the object type isn't more qualified than the
4384 // member function we're calling.
4385 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4386 Qualifiers ObjectQuals
4387 = BO->getOpcode() == BO_PtrMemD
4388 ? BO->getLHS()->getType().getQualifiers()
4389 : BO->getLHS()->getType()->getAs<PointerType>()
4390 ->getPointeeType().getQualifiers();
4391
4392 Qualifiers Difference = ObjectQuals - FuncQuals;
4393 Difference.removeObjCGCAttr();
4394 Difference.removeAddressSpace();
4395 if (Difference) {
4396 std::string QualsString = Difference.getAsString();
4397 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4398 << BO->getType().getUnqualifiedType()
4399 << QualsString
4400 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4401 }
4402
John McCallb268a282010-08-23 23:25:46 +00004403 CXXMemberCallExpr *TheCall
Abramo Bagnara21e9d862010-12-03 21:39:42 +00004404 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCall7decc9e2010-11-18 06:31:45 +00004405 NumArgs, ResultTy, VK,
John McCallb268a282010-08-23 23:25:46 +00004406 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004407
4408 if (CheckCallReturnType(FPT->getResultType(),
4409 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00004410 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004411 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00004412
John McCallb268a282010-08-23 23:25:46 +00004413 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004414 RParenLoc))
4415 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00004416
John McCallb268a282010-08-23 23:25:46 +00004417 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004418 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004419 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004420 diag::err_typecheck_call_not_function)
4421 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00004422 }
4423 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004424 }
4425
Douglas Gregore254f902009-02-04 00:32:51 +00004426 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004427 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00004428 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004429
Eli Friedmane14b1992009-12-26 03:35:45 +00004430 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004431 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4432 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4433 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4434 RParenLoc);
4435 }
4436
John McCall57500772009-12-16 12:17:52 +00004437 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004438 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4439 if (UnOp->getOpcode() == UO_AddrOf)
4440 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4441
John McCall57500772009-12-16 12:17:52 +00004442 if (isa<DeclRefExpr>(NakedFn))
4443 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4444
John McCall2d74de92009-12-01 22:10:20 +00004445 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
4446}
4447
John McCall57500772009-12-16 12:17:52 +00004448/// BuildResolvedCallExpr - Build a call to a resolved expression,
4449/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004450/// unary-convert to an expression of function-pointer or
4451/// block-pointer type.
4452///
4453/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004454ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004455Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4456 SourceLocation LParenLoc,
4457 Expr **Args, unsigned NumArgs,
4458 SourceLocation RParenLoc) {
4459 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4460
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004461 // Promote the function operand.
4462 UsualUnaryConversions(Fn);
4463
Chris Lattner08464942007-12-28 05:29:59 +00004464 // Make the call expr early, before semantic checks. This guarantees cleanup
4465 // of arguments and function on error.
John McCallb268a282010-08-23 23:25:46 +00004466 CallExpr *TheCall = new (Context) CallExpr(Context, Fn,
4467 Args, NumArgs,
4468 Context.BoolTy,
John McCall7decc9e2010-11-18 06:31:45 +00004469 VK_RValue,
John McCallb268a282010-08-23 23:25:46 +00004470 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004471
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004472 const FunctionType *FuncT;
4473 if (!Fn->getType()->isBlockPointerType()) {
4474 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4475 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004476 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004477 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004478 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4479 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00004480 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004481 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004482 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00004483 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004484 }
Chris Lattner08464942007-12-28 05:29:59 +00004485 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004486 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4487 << Fn->getType() << Fn->getSourceRange());
4488
Eli Friedman3164fb12009-03-22 22:00:50 +00004489 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004490 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00004491 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004492 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004493 return ExprError();
4494
Chris Lattner08464942007-12-28 05:29:59 +00004495 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004496 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004497 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004498
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004499 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00004500 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004501 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004502 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004503 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004504 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004505
Douglas Gregord8e97de2009-04-02 15:37:10 +00004506 if (FDecl) {
4507 // Check if we have too few/too many template arguments, based
4508 // on our knowledge of the function definition.
4509 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004510 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004511 const FunctionProtoType *Proto
4512 = Def->getType()->getAs<FunctionProtoType>();
4513 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004514 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4515 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004516 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004517
4518 // If the function we're calling isn't a function prototype, but we have
4519 // a function prototype from a prior declaratiom, use that prototype.
4520 if (!FDecl->hasPrototype())
4521 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004522 }
4523
Steve Naroff0b661582007-08-28 23:30:39 +00004524 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004525 for (unsigned i = 0; i != NumArgs; i++) {
4526 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004527
4528 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004529 InitializedEntity Entity
4530 = InitializedEntity::InitializeParameter(Context,
4531 Proto->getArgType(i));
4532 ExprResult ArgE = PerformCopyInitialization(Entity,
4533 SourceLocation(),
4534 Owned(Arg));
4535 if (ArgE.isInvalid())
4536 return true;
4537
4538 Arg = ArgE.takeAs<Expr>();
4539
4540 } else {
4541 DefaultArgumentPromotion(Arg);
Douglas Gregor8e09a722010-10-25 20:39:23 +00004542 }
4543
Douglas Gregor83025412010-10-26 05:45:40 +00004544 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4545 Arg->getType(),
4546 PDiag(diag::err_call_incomplete_argument)
4547 << Arg->getSourceRange()))
4548 return ExprError();
4549
Chris Lattner08464942007-12-28 05:29:59 +00004550 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004551 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004552 }
Chris Lattner08464942007-12-28 05:29:59 +00004553
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004554 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4555 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004556 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4557 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004558
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004559 // Check for sentinels
4560 if (NDecl)
4561 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004562
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004563 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004564 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00004565 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004566 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004567
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004568 if (unsigned BuiltinID = FDecl->getBuiltinID())
4569 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004570 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00004571 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004572 return ExprError();
4573 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004574
John McCallb268a282010-08-23 23:25:46 +00004575 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004576}
4577
John McCalldadc5752010-08-24 06:29:42 +00004578ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004579Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004580 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004581 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004582 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004583 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004584
4585 TypeSourceInfo *TInfo;
4586 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4587 if (!TInfo)
4588 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4589
John McCallb268a282010-08-23 23:25:46 +00004590 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004591}
4592
John McCalldadc5752010-08-24 06:29:42 +00004593ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004594Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00004595 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004596 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004597
Eli Friedman37a186d2008-05-20 05:22:08 +00004598 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004599 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4600 PDiag(diag::err_illegal_decl_array_incomplete_type)
4601 << SourceRange(LParenLoc,
4602 literalExpr->getSourceRange().getEnd())))
4603 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004604 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004605 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4606 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004607 } else if (!literalType->isDependentType() &&
4608 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00004609 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00004610 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00004611 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004612 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004613
Douglas Gregor85dabae2009-12-16 01:38:02 +00004614 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004615 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004616 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004617 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004618 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004619 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004620 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004621 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004622 &literalType);
4623 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004624 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004625 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004626
Chris Lattner79413952008-12-04 23:50:19 +00004627 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004628 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00004629 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004630 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004631 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004632
John McCall7decc9e2010-11-18 06:31:45 +00004633 // In C, compound literals are l-values for some reason.
4634 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4635
John McCall5d7aa7f2010-01-19 22:33:45 +00004636 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00004637 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004638}
4639
John McCalldadc5752010-08-24 06:29:42 +00004640ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00004641Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004642 SourceLocation RBraceLoc) {
4643 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00004644 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004645
Steve Naroff30d242c2007-09-15 18:49:24 +00004646 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004647 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004648
Ted Kremenekac034612010-04-13 23:39:13 +00004649 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4650 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004651 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004652 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004653}
4654
John McCalld7646252010-11-14 08:17:51 +00004655/// Prepares for a scalar cast, performing all the necessary stages
4656/// except the final cast and returning the kind required.
4657static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4658 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4659 // Also, callers should have filtered out the invalid cases with
4660 // pointers. Everything else should be possible.
4661
Abramo Bagnaraba854972011-01-04 09:50:03 +00004662 QualType SrcTy = Src->getType();
John McCalld7646252010-11-14 08:17:51 +00004663 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004664 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004665
John McCall8cb679e2010-11-15 09:13:47 +00004666 switch (SrcTy->getScalarTypeKind()) {
4667 case Type::STK_MemberPointer:
4668 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004669
John McCall8cb679e2010-11-15 09:13:47 +00004670 case Type::STK_Pointer:
4671 switch (DestTy->getScalarTypeKind()) {
4672 case Type::STK_Pointer:
4673 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00004674 CK_AnyPointerToObjCPointerCast :
4675 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00004676 case Type::STK_Bool:
4677 return CK_PointerToBoolean;
4678 case Type::STK_Integral:
4679 return CK_PointerToIntegral;
4680 case Type::STK_Floating:
4681 case Type::STK_FloatingComplex:
4682 case Type::STK_IntegralComplex:
4683 case Type::STK_MemberPointer:
4684 llvm_unreachable("illegal cast from pointer");
4685 }
4686 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004687
John McCall8cb679e2010-11-15 09:13:47 +00004688 case Type::STK_Bool: // casting from bool is like casting from an integer
4689 case Type::STK_Integral:
4690 switch (DestTy->getScalarTypeKind()) {
4691 case Type::STK_Pointer:
John McCalld7646252010-11-14 08:17:51 +00004692 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004693 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004694 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004695 case Type::STK_Bool:
4696 return CK_IntegralToBoolean;
4697 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004698 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004699 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004700 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004701 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004702 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004703 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004704 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004705 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004706 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004707 CK_IntegralToFloating);
4708 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004709 case Type::STK_MemberPointer:
4710 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004711 }
4712 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004713
John McCall8cb679e2010-11-15 09:13:47 +00004714 case Type::STK_Floating:
4715 switch (DestTy->getScalarTypeKind()) {
4716 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004717 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004718 case Type::STK_Bool:
4719 return CK_FloatingToBoolean;
4720 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004721 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004722 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004723 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004724 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004725 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004726 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004727 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004728 CK_FloatingToIntegral);
4729 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004730 case Type::STK_Pointer:
4731 llvm_unreachable("valid float->pointer cast?");
4732 case Type::STK_MemberPointer:
4733 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004734 }
4735 break;
4736
John McCall8cb679e2010-11-15 09:13:47 +00004737 case Type::STK_FloatingComplex:
4738 switch (DestTy->getScalarTypeKind()) {
4739 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004740 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004741 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004742 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004743 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004744 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004745 if (S.Context.hasSameType(ET, DestTy))
4746 return CK_FloatingComplexToReal;
4747 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4748 return CK_FloatingCast;
4749 }
John McCall8cb679e2010-11-15 09:13:47 +00004750 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004751 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004752 case Type::STK_Integral:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004753 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004754 CK_FloatingComplexToReal);
4755 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004756 case Type::STK_Pointer:
4757 llvm_unreachable("valid complex float->pointer cast?");
4758 case Type::STK_MemberPointer:
4759 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004760 }
4761 break;
4762
John McCall8cb679e2010-11-15 09:13:47 +00004763 case Type::STK_IntegralComplex:
4764 switch (DestTy->getScalarTypeKind()) {
4765 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004766 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004767 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004768 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004769 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004770 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004771 if (S.Context.hasSameType(ET, DestTy))
4772 return CK_IntegralComplexToReal;
4773 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4774 return CK_IntegralCast;
4775 }
John McCall8cb679e2010-11-15 09:13:47 +00004776 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004777 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004778 case Type::STK_Floating:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004779 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004780 CK_IntegralComplexToReal);
4781 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004782 case Type::STK_Pointer:
4783 llvm_unreachable("valid complex int->pointer cast?");
4784 case Type::STK_MemberPointer:
4785 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004786 }
4787 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004788 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004789
John McCalld7646252010-11-14 08:17:51 +00004790 llvm_unreachable("Unhandled scalar cast");
4791 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00004792}
4793
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004794/// CheckCastTypes - Check type constraints for casting between types.
John McCall7decc9e2010-11-18 06:31:45 +00004795bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4796 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4797 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00004798 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00004799 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4800 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00004801 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00004802 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00004803
John McCall7decc9e2010-11-18 06:31:45 +00004804 // We only support r-value casts in C.
4805 VK = VK_RValue;
4806
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004807 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4808 // type needs to be scalar.
4809 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004810 // We don't necessarily do lvalue-to-rvalue conversions on this.
4811 IgnoredValueConversions(castExpr);
4812
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004813 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004814 Kind = CK_ToVoid;
Anders Carlssonef918ac2009-10-16 02:35:04 +00004815 return false;
4816 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004817
John McCall34376a62010-12-04 03:47:34 +00004818 DefaultFunctionArrayLvalueConversion(castExpr);
4819
Eli Friedmane98194d2010-07-17 20:43:49 +00004820 if (RequireCompleteType(TyR.getBegin(), castType,
4821 diag::err_typecheck_cast_to_incomplete))
4822 return true;
4823
Anders Carlssonef918ac2009-10-16 02:35:04 +00004824 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004825 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004826 (castType->isStructureType() || castType->isUnionType())) {
4827 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004828 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004829 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4830 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004831 Kind = CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00004832 return false;
4833 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004834
Anders Carlsson525b76b2009-10-16 02:48:28 +00004835 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004836 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004837 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004838 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004839 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004840 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004841 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004842 castExpr->getType()) &&
4843 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004844 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4845 << castExpr->getSourceRange();
4846 break;
4847 }
4848 }
4849 if (Field == FieldEnd)
4850 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4851 << castExpr->getType() << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004852 Kind = CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00004853 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004854 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004855
Anders Carlsson525b76b2009-10-16 02:48:28 +00004856 // Reject any other conversions to non-scalar types.
4857 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
4858 << castType << castExpr->getSourceRange();
4859 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004860
John McCalld7646252010-11-14 08:17:51 +00004861 // The type we're casting to is known to be a scalar or vector.
4862
4863 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004864 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00004865 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004866 return Diag(castExpr->getLocStart(),
4867 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004868 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004869 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004870
4871 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00004872 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004873
Anders Carlsson525b76b2009-10-16 02:48:28 +00004874 if (castType->isVectorType())
4875 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
4876 if (castExpr->getType()->isVectorType())
4877 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
4878
John McCalld7646252010-11-14 08:17:51 +00004879 // The source and target types are both scalars, i.e.
4880 // - arithmetic types (fundamental, enum, and complex)
4881 // - all kinds of pointers
4882 // Note that member pointers were filtered out with C++, above.
4883
Anders Carlsson43d70f82009-10-16 05:23:41 +00004884 if (isa<ObjCSelectorExpr>(castExpr))
4885 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004886
John McCalld7646252010-11-14 08:17:51 +00004887 // If either type is a pointer, the other type has to be either an
4888 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00004889 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004890 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00004891 if (!castExprType->isIntegralType(Context) &&
Douglas Gregorb90df602010-06-16 00:17:44 +00004892 castExprType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004893 return Diag(castExpr->getLocStart(),
4894 diag::err_cast_pointer_from_non_pointer_int)
4895 << castExprType << castExpr->getSourceRange();
4896 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004897 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004898 return Diag(castExpr->getLocStart(),
4899 diag::err_cast_pointer_to_non_pointer_int)
4900 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004901 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004902
John McCalld7646252010-11-14 08:17:51 +00004903 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCall2b5c1b22010-08-12 21:44:57 +00004904
John McCalld7646252010-11-14 08:17:51 +00004905 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004906 CheckCastAlign(castExpr, castType, TyR);
4907
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004908 return false;
4909}
4910
Anders Carlsson525b76b2009-10-16 02:48:28 +00004911bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004912 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004913 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004914
Anders Carlssonde71adf2007-11-27 05:51:55 +00004915 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004916 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004917 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004918 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004919 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004920 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004921 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004922 } else
4923 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004924 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004925 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004926
John McCalle3027922010-08-25 11:45:40 +00004927 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004928 return false;
4929}
4930
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004931bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCalle3027922010-08-25 11:45:40 +00004932 CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004933 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004934
Anders Carlsson43d70f82009-10-16 05:23:41 +00004935 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004936
Nate Begemanc8961a42009-06-27 22:05:55 +00004937 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4938 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004939 if (SrcTy->isVectorType()) {
4940 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
4941 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4942 << DestTy << SrcTy << R;
John McCalle3027922010-08-25 11:45:40 +00004943 Kind = CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00004944 return false;
4945 }
4946
Nate Begemanbd956c42009-06-28 02:36:38 +00004947 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004948 // conversion will take place first from scalar to elt type, and then
4949 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004950 if (SrcTy->isPointerType())
4951 return Diag(R.getBegin(),
4952 diag::err_invalid_conversion_between_vector_and_scalar)
4953 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004954
4955 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4956 ImpCastExprToType(CastExpr, DestElemTy,
John McCalld7646252010-11-14 08:17:51 +00004957 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004958
John McCalle3027922010-08-25 11:45:40 +00004959 Kind = CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00004960 return false;
4961}
4962
John McCalldadc5752010-08-24 06:29:42 +00004963ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004964Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004965 SourceLocation RParenLoc, Expr *castExpr) {
4966 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004967 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004968
John McCall97513962010-01-15 18:39:57 +00004969 TypeSourceInfo *castTInfo;
4970 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4971 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00004972 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00004973
Nate Begeman5ec4b312009-08-10 23:49:36 +00004974 // If the Expr being casted is a ParenListExpr, handle it specially.
4975 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00004976 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00004977 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00004978
John McCallb268a282010-08-23 23:25:46 +00004979 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004980}
4981
John McCalldadc5752010-08-24 06:29:42 +00004982ExprResult
John McCallebe54742010-01-15 18:56:44 +00004983Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004984 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004985 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004986 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004987 CXXCastPath BasePath;
John McCallebe54742010-01-15 18:56:44 +00004988 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCall7decc9e2010-11-18 06:31:45 +00004989 Kind, VK, BasePath))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004990 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00004991
John McCallcf142162010-08-07 06:22:56 +00004992 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +00004993 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00004994 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00004995 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004996}
4997
Nate Begeman5ec4b312009-08-10 23:49:36 +00004998/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4999/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005000ExprResult
John McCallb268a282010-08-23 23:25:46 +00005001Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005002 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5003 if (!E)
5004 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00005005
John McCalldadc5752010-08-24 06:29:42 +00005006 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005007
Nate Begeman5ec4b312009-08-10 23:49:36 +00005008 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005009 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5010 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005011
John McCallb268a282010-08-23 23:25:46 +00005012 if (Result.isInvalid()) return ExprError();
5013
5014 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005015}
5016
John McCalldadc5752010-08-24 06:29:42 +00005017ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00005018Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00005019 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00005020 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00005021 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00005022 QualType Ty = TInfo->getType();
John Thompson781ad172010-06-30 22:55:51 +00005023 bool isAltiVecLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00005024
John Thompson781ad172010-06-30 22:55:51 +00005025 // Check for an altivec literal,
5026 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005027 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5028 if (PE->getNumExprs() == 0) {
5029 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5030 return ExprError();
5031 }
John Thompson781ad172010-06-30 22:55:51 +00005032 if (PE->getNumExprs() == 1) {
5033 if (!PE->getExpr(0)->getType()->isVectorType())
5034 isAltiVecLiteral = true;
5035 }
5036 else
5037 isAltiVecLiteral = true;
5038 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00005039
John Thompson781ad172010-06-30 22:55:51 +00005040 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
5041 // then handle it as such.
5042 if (isAltiVecLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005043 llvm::SmallVector<Expr *, 8> initExprs;
5044 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5045 initExprs.push_back(PE->getExpr(i));
5046
5047 // FIXME: This means that pretty-printing the final AST will produce curly
5048 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00005049 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5050 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00005051 initExprs.size(), RParenLoc);
5052 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00005053 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005054 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005055 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00005056 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00005057 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00005058 if (Result.isInvalid()) return ExprError();
5059 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005060 }
5061}
5062
John McCalldadc5752010-08-24 06:29:42 +00005063ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00005064 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005065 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00005066 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005067 unsigned nexprs = Val.size();
5068 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005069 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5070 Expr *expr;
5071 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5072 expr = new (Context) ParenExpr(L, R, exprs[0]);
5073 else
5074 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005075 return Owned(expr);
5076}
5077
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005078/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5079/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00005080/// C99 6.5.15
5081QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005082 Expr *&SAVE, ExprValueKind &VK,
John McCall4bc41ae2010-11-18 19:01:18 +00005083 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00005084 SourceLocation QuestionLoc) {
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005085 // If both LHS and RHS are overloaded functions, try to resolve them.
5086 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
5087 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
5088 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
5089 if (LHSResult.isInvalid())
5090 return QualType();
5091
5092 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
5093 if (RHSResult.isInvalid())
5094 return QualType();
5095
5096 LHS = LHSResult.take();
5097 RHS = RHSResult.take();
5098 }
5099
Sebastian Redl1a99f442009-04-16 17:51:27 +00005100 // C++ is sufficiently different to merit its own checker.
5101 if (getLangOptions().CPlusPlus)
John McCall4bc41ae2010-11-18 19:01:18 +00005102 return CXXCheckConditionalOperands(Cond, LHS, RHS, SAVE,
5103 VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00005104
5105 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005106 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005107
Chris Lattner432cff52009-02-18 04:28:32 +00005108 UsualUnaryConversions(Cond);
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00005109 if (SAVE) {
5110 SAVE = LHS = Cond;
5111 }
5112 else
5113 UsualUnaryConversions(LHS);
Chris Lattner432cff52009-02-18 04:28:32 +00005114 UsualUnaryConversions(RHS);
5115 QualType CondTy = Cond->getType();
5116 QualType LHSTy = LHS->getType();
5117 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00005118
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005119 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005120 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00005121 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5122 // Throw an error if its not either.
5123 if (getLangOptions().OpenCL) {
5124 if (!CondTy->isVectorType()) {
5125 Diag(Cond->getLocStart(),
5126 diag::err_typecheck_cond_expect_scalar_or_vector)
5127 << CondTy;
5128 return QualType();
5129 }
5130 }
5131 else {
5132 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5133 << CondTy;
5134 return QualType();
5135 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005136 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005137
Chris Lattnere2949f42008-01-06 22:42:25 +00005138 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005139 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5140 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00005141
Nate Begemanabb5a732010-09-20 22:41:17 +00005142 // OpenCL: If the condition is a vector, and both operands are scalar,
5143 // attempt to implicity convert them to the vector type to act like the
5144 // built in select.
5145 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5146 // Both operands should be of scalar type.
5147 if (!LHSTy->isScalarType()) {
5148 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5149 << CondTy;
5150 return QualType();
5151 }
5152 if (!RHSTy->isScalarType()) {
5153 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5154 << CondTy;
5155 return QualType();
5156 }
5157 // Implicity convert these scalars to the type of the condition.
5158 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5159 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5160 }
5161
Chris Lattnere2949f42008-01-06 22:42:25 +00005162 // If both operands have arithmetic type, do the usual arithmetic conversions
5163 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005164 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5165 UsualArithmeticConversions(LHS, RHS);
5166 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005167 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005168
Chris Lattnere2949f42008-01-06 22:42:25 +00005169 // If both operands are the same structure or union type, the result is that
5170 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005171 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5172 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005173 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005174 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005175 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005176 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005177 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005178 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005179
Chris Lattnere2949f42008-01-06 22:42:25 +00005180 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005181 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005182 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5183 if (!LHSTy->isVoidType())
5184 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5185 << RHS->getSourceRange();
5186 if (!RHSTy->isVoidType())
5187 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5188 << LHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005189 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5190 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005191 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005192 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005193 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5194 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005195 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005196 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005197 // promote the null to a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005198 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005199 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005200 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005201 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005202 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00005203 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005204 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005205 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005206
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005207 // All objective-c pointer type analysis is done here.
5208 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5209 QuestionLoc);
5210 if (!compositeType.isNull())
5211 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005212
5213
Steve Naroff05efa972009-07-01 14:36:47 +00005214 // Handle block pointer types.
5215 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5216 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5217 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5218 QualType destType = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005219 ImpCastExprToType(LHS, destType, CK_BitCast);
5220 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005221 return destType;
5222 }
5223 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005224 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005225 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005226 }
Steve Naroff05efa972009-07-01 14:36:47 +00005227 // We have 2 block pointer types.
5228 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5229 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005230 return LHSTy;
5231 }
Steve Naroff05efa972009-07-01 14:36:47 +00005232 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005233 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5234 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005235
Steve Naroff05efa972009-07-01 14:36:47 +00005236 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5237 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005238 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005239 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005240 // In this situation, we assume void* type. No especially good
5241 // reason, but this is what gcc does, and we do have to pick
5242 // to get a consistent AST.
5243 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005244 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5245 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005246 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005247 }
Steve Naroff05efa972009-07-01 14:36:47 +00005248 // The block pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005249 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5250 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005251 return LHSTy;
5252 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005253
Steve Naroff05efa972009-07-01 14:36:47 +00005254 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5255 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5256 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005257 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5258 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005259
5260 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5261 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5262 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005263 QualType destPointee
5264 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005265 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005266 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005267 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005268 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005269 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005270 return destType;
5271 }
5272 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005273 QualType destPointee
5274 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005275 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005276 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005277 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005278 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005279 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005280 return destType;
5281 }
5282
5283 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5284 // Two identical pointer types are always compatible.
5285 return LHSTy;
5286 }
5287 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5288 rhptee.getUnqualifiedType())) {
5289 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5290 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5291 // In this situation, we assume void* type. No especially good
5292 // reason, but this is what gcc does, and we do have to pick
5293 // to get a consistent AST.
5294 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005295 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5296 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005297 return incompatTy;
5298 }
5299 // The pointer types are compatible.
5300 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5301 // differently qualified versions of compatible types, the result type is
5302 // a pointer to an appropriately qualified version of the *composite*
5303 // type.
5304 // FIXME: Need to calculate the composite type.
5305 // FIXME: Need to add qualifiers
John McCalle3027922010-08-25 11:45:40 +00005306 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5307 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005308 return LHSTy;
5309 }
Mike Stump11289f42009-09-09 15:08:12 +00005310
John McCalle84af4e2010-11-13 01:35:44 +00005311 // GCC compatibility: soften pointer/integer mismatch. Note that
5312 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005313 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5314 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5315 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005316 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005317 return RHSTy;
5318 }
5319 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5320 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5321 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005322 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005323 return LHSTy;
5324 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005325
Chris Lattnere2949f42008-01-06 22:42:25 +00005326 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005327 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5328 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005329 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005330}
5331
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005332/// FindCompositeObjCPointerType - Helper method to find composite type of
5333/// two objective-c pointer types of the two input expressions.
5334QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5335 SourceLocation QuestionLoc) {
5336 QualType LHSTy = LHS->getType();
5337 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005338
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005339 // Handle things like Class and struct objc_class*. Here we case the result
5340 // to the pseudo-builtin, because that will be implicitly cast back to the
5341 // redefinition type if an attempt is made to access its fields.
5342 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005343 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005344 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005345 return LHSTy;
5346 }
5347 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005348 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005349 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005350 return RHSTy;
5351 }
5352 // And the same for struct objc_object* / id
5353 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005354 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005355 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005356 return LHSTy;
5357 }
5358 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005359 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005360 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005361 return RHSTy;
5362 }
5363 // And the same for struct objc_selector* / SEL
5364 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005365 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005366 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005367 return LHSTy;
5368 }
5369 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005370 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005371 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005372 return RHSTy;
5373 }
5374 // Check constraints for Objective-C object pointers types.
5375 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005376
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005377 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5378 // Two identical object pointer types are always compatible.
5379 return LHSTy;
5380 }
5381 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5382 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5383 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005384
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005385 // If both operands are interfaces and either operand can be
5386 // assigned to the other, use that type as the composite
5387 // type. This allows
5388 // xxx ? (A*) a : (B*) b
5389 // where B is a subclass of A.
5390 //
5391 // Additionally, as for assignment, if either type is 'id'
5392 // allow silent coercion. Finally, if the types are
5393 // incompatible then make sure to use 'id' as the composite
5394 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005395
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005396 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5397 // It could return the composite type.
5398 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5399 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5400 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5401 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5402 } else if ((LHSTy->isObjCQualifiedIdType() ||
5403 RHSTy->isObjCQualifiedIdType()) &&
5404 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5405 // Need to handle "id<xx>" explicitly.
5406 // GCC allows qualified id and any Objective-C type to devolve to
5407 // id. Currently localizing to here until clear this should be
5408 // part of ObjCQualifiedIdTypesAreCompatible.
5409 compositeType = Context.getObjCIdType();
5410 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5411 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005412 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005413 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5414 ;
5415 else {
5416 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5417 << LHSTy << RHSTy
5418 << LHS->getSourceRange() << RHS->getSourceRange();
5419 QualType incompatTy = Context.getObjCIdType();
John McCalle3027922010-08-25 11:45:40 +00005420 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5421 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005422 return incompatTy;
5423 }
5424 // The object pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005425 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5426 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005427 return compositeType;
5428 }
5429 // Check Objective-C object pointer types and 'void *'
5430 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5431 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5432 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5433 QualType destPointee
5434 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5435 QualType destType = Context.getPointerType(destPointee);
5436 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005437 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005438 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005439 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005440 return destType;
5441 }
5442 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5443 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5444 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5445 QualType destPointee
5446 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5447 QualType destType = Context.getPointerType(destPointee);
5448 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005449 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005450 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005451 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005452 return destType;
5453 }
5454 return QualType();
5455}
5456
Steve Naroff83895f72007-09-16 03:34:24 +00005457/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005458/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005459ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005460 SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +00005461 Expr *CondExpr, Expr *LHSExpr,
5462 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005463 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5464 // was the condition.
5465 bool isLHSNull = LHSExpr == 0;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005466 Expr *SAVEExpr = 0;
5467 if (isLHSNull) {
5468 LHSExpr = SAVEExpr = CondExpr;
5469 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005470
John McCall7decc9e2010-11-18 06:31:45 +00005471 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005472 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00005473 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCall4bc41ae2010-11-18 19:01:18 +00005474 SAVEExpr, VK, OK, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00005475 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005476 return ExprError();
5477
Douglas Gregor7e112b02009-08-26 14:37:04 +00005478 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005479 LHSExpr, ColonLoc,
5480 RHSExpr, SAVEExpr,
John McCall4bc41ae2010-11-18 19:01:18 +00005481 result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005482}
5483
John McCallaba90822011-01-31 23:13:11 +00005484// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005485// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005486// routine is it effectively iqnores the qualifiers on the top level pointee.
5487// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5488// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005489static Sema::AssignConvertType
5490checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5491 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5492 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005493
Steve Naroff1f4d7272007-05-11 04:00:31 +00005494 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005495 const Type *lhptee, *rhptee;
5496 Qualifiers lhq, rhq;
5497 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5498 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005499
John McCallaba90822011-01-31 23:13:11 +00005500 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005501
5502 // C99 6.5.16.1p1: This following citation is common to constraints
5503 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5504 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005505 Qualifiers lq;
5506
5507 if (!lhq.compatiblyIncludes(rhq)) {
5508 // Treat address-space mismatches as fatal. TODO: address subspaces
5509 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5510 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5511
5512 // For GCC compatibility, other qualifier mismatches are treated
5513 // as still compatible in C.
5514 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5515 }
Steve Naroff3f597292007-05-11 22:18:03 +00005516
Mike Stump4e1f26a2009-02-19 03:04:26 +00005517 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5518 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005519 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005520 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005521 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005522 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005523
Chris Lattner0a788432008-01-03 22:56:36 +00005524 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005525 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005526 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005527 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005528
Chris Lattner0a788432008-01-03 22:56:36 +00005529 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005530 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005531 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005532
5533 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005534 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005535 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005536 }
John McCall4fff8f62011-02-01 00:10:29 +00005537
Mike Stump4e1f26a2009-02-19 03:04:26 +00005538 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005539 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005540 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5541 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005542 // Check if the pointee types are compatible ignoring the sign.
5543 // We explicitly check for char so that we catch "char" vs
5544 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005545 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005546 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005547 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005548 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005549
Chris Lattnerec3a1562009-10-17 20:33:28 +00005550 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005551 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005552 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005553 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005554
John McCall4fff8f62011-02-01 00:10:29 +00005555 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005556 // Types are compatible ignoring the sign. Qualifier incompatibility
5557 // takes priority over sign incompatibility because the sign
5558 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005559 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005560 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005561
John McCallaba90822011-01-31 23:13:11 +00005562 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005563 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005564
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005565 // If we are a multi-level pointer, it's possible that our issue is simply
5566 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5567 // the eventual target type is the same and the pointers have the same
5568 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005569 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005570 do {
John McCall4fff8f62011-02-01 00:10:29 +00005571 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5572 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005573 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005574
John McCall4fff8f62011-02-01 00:10:29 +00005575 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005576 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005577 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005578
Eli Friedman80160bd2009-03-22 23:59:44 +00005579 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005580 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005581 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005582 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005583}
5584
John McCallaba90822011-01-31 23:13:11 +00005585/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005586/// block pointer types are compatible or whether a block and normal pointer
5587/// are compatible. It is more restrict than comparing two function pointer
5588// types.
John McCallaba90822011-01-31 23:13:11 +00005589static Sema::AssignConvertType
5590checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5591 QualType rhsType) {
5592 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5593 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5594
Steve Naroff081c7422008-09-04 15:10:53 +00005595 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005596
Steve Naroff081c7422008-09-04 15:10:53 +00005597 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005598 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5599 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005600
John McCallaba90822011-01-31 23:13:11 +00005601 // In C++, the types have to match exactly.
5602 if (S.getLangOptions().CPlusPlus)
5603 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005604
John McCallaba90822011-01-31 23:13:11 +00005605 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005606
Steve Naroff081c7422008-09-04 15:10:53 +00005607 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005608 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5609 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005610
John McCallaba90822011-01-31 23:13:11 +00005611 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5612 return Sema::IncompatibleBlockPointer;
5613
Steve Naroff081c7422008-09-04 15:10:53 +00005614 return ConvTy;
5615}
5616
John McCallaba90822011-01-31 23:13:11 +00005617/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005618/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005619static Sema::AssignConvertType
5620checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5621 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5622 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5623
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005624 if (lhsType->isObjCBuiltinType()) {
5625 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005626 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5627 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005628 return Sema::IncompatiblePointer;
5629 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005630 }
5631 if (rhsType->isObjCBuiltinType()) {
5632 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005633 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5634 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005635 return Sema::IncompatiblePointer;
5636 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005637 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005638 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005639 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005640 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005641 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005642
John McCallaba90822011-01-31 23:13:11 +00005643 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5644 return Sema::CompatiblePointerDiscardsQualifiers;
5645
5646 if (S.Context.typesAreCompatible(lhsType, rhsType))
5647 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005648 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005649 return Sema::IncompatibleObjCQualifiedId;
5650 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005651}
5652
John McCall29600e12010-11-16 02:32:08 +00005653Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005654Sema::CheckAssignmentConstraints(SourceLocation Loc,
5655 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005656 // Fake up an opaque expression. We don't actually care about what
5657 // cast operations are required, so if CheckAssignmentConstraints
5658 // adds casts to this they'll be wasted, but fortunately that doesn't
5659 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00005660 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John McCall29600e12010-11-16 02:32:08 +00005661 Expr *rhsPtr = &rhs;
5662 CastKind K = CK_Invalid;
5663
5664 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5665}
5666
Mike Stump4e1f26a2009-02-19 03:04:26 +00005667/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5668/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005669/// pointers. Here are some objectionable examples that GCC considers warnings:
5670///
5671/// int a, *pint;
5672/// short *pshort;
5673/// struct foo *pfoo;
5674///
5675/// pint = pshort; // warning: assignment from incompatible pointer type
5676/// a = pint; // warning: assignment makes integer from pointer without a cast
5677/// pint = a; // warning: assignment makes pointer from integer without a cast
5678/// pint = pfoo; // warning: assignment from incompatible pointer type
5679///
5680/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005681/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005682///
John McCall8cb679e2010-11-15 09:13:47 +00005683/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005684Sema::AssignConvertType
John McCall29600e12010-11-16 02:32:08 +00005685Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005686 CastKind &Kind) {
John McCall29600e12010-11-16 02:32:08 +00005687 QualType rhsType = rhs->getType();
5688
Chris Lattnera52c2f22008-01-04 23:18:45 +00005689 // Get canonical types. We're not formatting these types, just comparing
5690 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005691 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5692 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005693
John McCalle5255932011-01-31 22:28:28 +00005694 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00005695 if (lhsType == rhsType) {
5696 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005697 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005698 }
5699
Douglas Gregor6b754842008-10-28 00:22:11 +00005700 // If the left-hand side is a reference type, then we are in a
5701 // (rare!) case where we've allowed the use of references in C,
5702 // e.g., as a parameter type in a built-in function. In this case,
5703 // just make sure that the type referenced is compatible with the
5704 // right-hand side type. The caller is responsible for adjusting
5705 // lhsType so that the resulting expression does not have reference
5706 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005707 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005708 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5709 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005710 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005711 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005712 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005713 }
John McCalle5255932011-01-31 22:28:28 +00005714
Nate Begemanbd956c42009-06-28 02:36:38 +00005715 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5716 // to the same ExtVector type.
5717 if (lhsType->isExtVectorType()) {
5718 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005719 return Incompatible;
5720 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005721 // CK_VectorSplat does T -> vector T, so first cast to the
5722 // element type.
5723 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5724 if (elType != rhsType) {
5725 Kind = PrepareScalarCast(*this, rhs, elType);
5726 ImpCastExprToType(rhs, elType, Kind);
5727 }
5728 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005729 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005730 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005731 }
Mike Stump11289f42009-09-09 15:08:12 +00005732
John McCalle5255932011-01-31 22:28:28 +00005733 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00005734 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005735 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005736 // Allow assignments of an AltiVec vector type to an equivalent GCC
5737 // vector type and vice versa
5738 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5739 Kind = CK_BitCast;
5740 return Compatible;
5741 }
5742
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005743 // If we are allowing lax vector conversions, and LHS and RHS are both
5744 // vectors, the total size only needs to be the same. This is a bitcast;
5745 // no bits are changed but the result type is different.
5746 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005747 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005748 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005749 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005750 }
Chris Lattner881a2122008-01-04 23:32:24 +00005751 }
5752 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005753 }
Eli Friedman3360d892008-05-30 18:07:22 +00005754
John McCalle5255932011-01-31 22:28:28 +00005755 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00005756 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005757 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005758 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005759 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005760 }
Eli Friedman3360d892008-05-30 18:07:22 +00005761
John McCalle5255932011-01-31 22:28:28 +00005762 // Conversions to normal pointers.
5763 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5764 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00005765 if (isa<PointerType>(rhsType)) {
5766 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00005767 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005768 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005769
John McCalle5255932011-01-31 22:28:28 +00005770 // int -> T*
5771 if (rhsType->isIntegerType()) {
5772 Kind = CK_IntegralToPointer; // FIXME: null?
5773 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005774 }
John McCalle5255932011-01-31 22:28:28 +00005775
5776 // C pointers are not compatible with ObjC object pointers,
5777 // with two exceptions:
5778 if (isa<ObjCObjectPointerType>(rhsType)) {
5779 // - conversions to void*
5780 if (lhsPointer->getPointeeType()->isVoidType()) {
5781 Kind = CK_AnyPointerToObjCPointerCast;
5782 return Compatible;
5783 }
5784
5785 // - conversions from 'Class' to the redefinition type
5786 if (rhsType->isObjCClassType() &&
5787 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005788 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005789 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005790 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005791
John McCalle5255932011-01-31 22:28:28 +00005792 Kind = CK_BitCast;
5793 return IncompatiblePointer;
5794 }
5795
5796 // U^ -> void*
5797 if (rhsType->getAs<BlockPointerType>()) {
5798 if (lhsPointer->getPointeeType()->isVoidType()) {
5799 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005800 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005801 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005802 }
John McCalle5255932011-01-31 22:28:28 +00005803
Steve Naroff081c7422008-09-04 15:10:53 +00005804 return Incompatible;
5805 }
5806
John McCalle5255932011-01-31 22:28:28 +00005807 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00005808 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005809 // U^ -> T^
5810 if (rhsType->isBlockPointerType()) {
5811 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00005812 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00005813 }
5814
5815 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005816 if (rhsType->isIntegerType()) {
5817 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005818 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005819 }
5820
John McCalle5255932011-01-31 22:28:28 +00005821 // id -> T^
5822 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5823 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005824 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005825 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005826
John McCalle5255932011-01-31 22:28:28 +00005827 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005828 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005829 if (RHSPT->getPointeeType()->isVoidType()) {
5830 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005831 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005832 }
John McCall8cb679e2010-11-15 09:13:47 +00005833
Chris Lattnera52c2f22008-01-04 23:18:45 +00005834 return Incompatible;
5835 }
5836
John McCalle5255932011-01-31 22:28:28 +00005837 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005838 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005839 // A* -> B*
5840 if (rhsType->isObjCObjectPointerType()) {
5841 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00005842 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00005843 }
5844
5845 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00005846 if (rhsType->isIntegerType()) {
5847 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005848 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005849 }
5850
John McCalle5255932011-01-31 22:28:28 +00005851 // In general, C pointers are not compatible with ObjC object pointers,
5852 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00005853 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005854 // - conversions from 'void*'
5855 if (rhsType->isVoidPointerType()) {
5856 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005857 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005858 }
5859
5860 // - conversions to 'Class' from its redefinition type
5861 if (lhsType->isObjCClassType() &&
5862 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
5863 Kind = CK_BitCast;
5864 return Compatible;
5865 }
5866
5867 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005868 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005869 }
John McCalle5255932011-01-31 22:28:28 +00005870
5871 // T^ -> A*
5872 if (rhsType->isBlockPointerType()) {
5873 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005874 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005875 }
5876
Steve Naroff7cae42b2009-07-10 23:34:53 +00005877 return Incompatible;
5878 }
John McCalle5255932011-01-31 22:28:28 +00005879
5880 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00005881 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005882 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005883 if (lhsType == Context.BoolTy) {
5884 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005885 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005886 }
Eli Friedman3360d892008-05-30 18:07:22 +00005887
John McCalle5255932011-01-31 22:28:28 +00005888 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005889 if (lhsType->isIntegerType()) {
5890 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005891 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005892 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005893
Chris Lattnera52c2f22008-01-04 23:18:45 +00005894 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005895 }
John McCalle5255932011-01-31 22:28:28 +00005896
5897 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005898 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005899 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005900 if (lhsType == Context.BoolTy) {
5901 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005902 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005903 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005904
John McCalle5255932011-01-31 22:28:28 +00005905 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005906 if (lhsType->isIntegerType()) {
5907 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005908 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005909 }
5910
Steve Naroff7cae42b2009-07-10 23:34:53 +00005911 return Incompatible;
5912 }
Eli Friedman3360d892008-05-30 18:07:22 +00005913
John McCalle5255932011-01-31 22:28:28 +00005914 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00005915 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005916 if (Context.typesAreCompatible(lhsType, rhsType)) {
5917 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005918 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005919 }
Bill Wendling216423b2007-05-30 06:30:29 +00005920 }
John McCalle5255932011-01-31 22:28:28 +00005921
Steve Naroff98cf3e92007-06-06 18:38:38 +00005922 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005923}
5924
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005925/// \brief Constructs a transparent union from an expression that is
5926/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00005927static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005928 QualType UnionType, FieldDecl *Field) {
5929 // Build an initializer list that designates the appropriate member
5930 // of the transparent union.
Ted Kremenekac034612010-04-13 23:39:13 +00005931 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005932 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005933 SourceLocation());
5934 Initializer->setType(UnionType);
5935 Initializer->setInitializedFieldInUnion(Field);
5936
5937 // Build a compound literal constructing a value of the transparent
5938 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005939 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00005940 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall7decc9e2010-11-18 06:31:45 +00005941 VK_RValue, Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005942}
5943
5944Sema::AssignConvertType
5945Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
5946 QualType FromType = rExpr->getType();
5947
Mike Stump11289f42009-09-09 15:08:12 +00005948 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005949 // transparent_union GCC extension.
5950 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005951 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005952 return Incompatible;
5953
5954 // The field to initialize within the transparent union.
5955 RecordDecl *UD = UT->getDecl();
5956 FieldDecl *InitField = 0;
5957 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005958 for (RecordDecl::field_iterator it = UD->field_begin(),
5959 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005960 it != itend; ++it) {
5961 if (it->getType()->isPointerType()) {
5962 // If the transparent union contains a pointer type, we allow:
5963 // 1) void pointer
5964 // 2) null pointer constant
5965 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005966 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +00005967 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005968 InitField = *it;
5969 break;
5970 }
Mike Stump11289f42009-09-09 15:08:12 +00005971
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005972 if (rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005973 Expr::NPC_ValueDependentIsNull)) {
John McCalle84af4e2010-11-13 01:35:44 +00005974 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005975 InitField = *it;
5976 break;
5977 }
5978 }
5979
John McCall29600e12010-11-16 02:32:08 +00005980 Expr *rhs = rExpr;
John McCall8cb679e2010-11-15 09:13:47 +00005981 CastKind Kind = CK_Invalid;
John McCall29600e12010-11-16 02:32:08 +00005982 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005983 == Compatible) {
John McCall29600e12010-11-16 02:32:08 +00005984 ImpCastExprToType(rhs, it->getType(), Kind);
5985 rExpr = rhs;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005986 InitField = *it;
5987 break;
5988 }
5989 }
5990
5991 if (!InitField)
5992 return Incompatible;
5993
5994 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
5995 return Compatible;
5996}
5997
Chris Lattner9bad62c2008-01-04 18:04:52 +00005998Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005999Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00006000 if (getLangOptions().CPlusPlus) {
6001 if (!lhsType->isRecordType()) {
6002 // C++ 5.17p3: If the left operand is not of class type, the
6003 // expression is implicitly converted (C++ 4) to the
6004 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00006005 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006006 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00006007 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00006008 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00006009 }
6010
6011 // FIXME: Currently, we fall through and treat C++ classes like C
6012 // structures.
John McCall34376a62010-12-04 03:47:34 +00006013 }
Douglas Gregor9a657932008-10-21 23:43:52 +00006014
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006015 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6016 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00006017 if ((lhsType->isPointerType() ||
6018 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00006019 lhsType->isBlockPointerType())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006020 && rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006021 Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00006022 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006023 return Compatible;
6024 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006025
Chris Lattnere6dcd502007-10-16 02:55:40 +00006026 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006027 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00006028 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00006029 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00006030 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00006031 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00006032 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00006033 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006034
John McCall8cb679e2010-11-15 09:13:47 +00006035 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006036 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00006037 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006038
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006039 // C99 6.5.16.1p2: The value of the right operand is converted to the
6040 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006041 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6042 // so that we can use references in built-in functions even in C.
6043 // The getNonReferenceType() call makes sure that the resulting expression
6044 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006045 if (result != Incompatible && rExpr->getType() != lhsType)
John McCall8cb679e2010-11-15 09:13:47 +00006046 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006047 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006048}
6049
Chris Lattner326f7572008-11-18 01:30:42 +00006050QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006051 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006052 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00006053 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006054 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006055}
6056
Chris Lattnerfaa54172010-01-12 21:23:57 +00006057QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00006058 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006059 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00006060 QualType lhsType =
6061 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
6062 QualType rhsType =
6063 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006064
Nate Begeman191a6b12008-07-14 18:02:46 +00006065 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006066 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00006067 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006068
Nate Begeman191a6b12008-07-14 18:02:46 +00006069 // Handle the case of a vector & extvector type of the same size and element
6070 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006071 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00006072 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006073 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006074 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006075 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006076 if (lhsType->isExtVectorType()) {
John McCalle3027922010-08-25 11:45:40 +00006077 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006078 return lhsType;
6079 }
6080
John McCalle3027922010-08-25 11:45:40 +00006081 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006082 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00006083 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6084 // If we are allowing lax vector conversions, and LHS and RHS are both
6085 // vectors, the total size only needs to be the same. This is a
6086 // bitcast; no bits are changed but the result type is different.
6087 ImpCastExprToType(rex, lhsType, CK_BitCast);
6088 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006089 }
Eric Christophera613f562010-08-26 00:42:16 +00006090 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006091 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006092 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006093
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006094 // Handle the case of equivalent AltiVec and GCC vector types
6095 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6096 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCalle3027922010-08-25 11:45:40 +00006097 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006098 return rhsType;
6099 }
6100
Nate Begemanbd956c42009-06-28 02:36:38 +00006101 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6102 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6103 bool swapped = false;
6104 if (rhsType->isExtVectorType()) {
6105 swapped = true;
6106 std::swap(rex, lex);
6107 std::swap(rhsType, lhsType);
6108 }
Mike Stump11289f42009-09-09 15:08:12 +00006109
Nate Begeman886448d2009-06-28 19:12:57 +00006110 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00006111 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006112 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00006113 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00006114 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6115 if (order > 0)
6116 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
6117 if (order >= 0) {
6118 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006119 if (swapped) std::swap(rex, lex);
6120 return lhsType;
6121 }
6122 }
6123 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6124 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00006125 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6126 if (order > 0)
6127 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
6128 if (order >= 0) {
6129 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006130 if (swapped) std::swap(rex, lex);
6131 return lhsType;
6132 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006133 }
6134 }
Mike Stump11289f42009-09-09 15:08:12 +00006135
Nate Begeman886448d2009-06-28 19:12:57 +00006136 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00006137 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006138 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00006139 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006140 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006141}
6142
Chris Lattnerfaa54172010-01-12 21:23:57 +00006143QualType Sema::CheckMultiplyDivideOperands(
6144 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00006145 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006146 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006147
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006148 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006149
Chris Lattnerfaa54172010-01-12 21:23:57 +00006150 if (!lex->getType()->isArithmeticType() ||
6151 !rex->getType()->isArithmeticType())
6152 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006153
Chris Lattnerfaa54172010-01-12 21:23:57 +00006154 // Check for division by zero.
6155 if (isDiv &&
6156 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006157 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattner70117952010-01-12 21:30:55 +00006158 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006159
Chris Lattnerfaa54172010-01-12 21:23:57 +00006160 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006161}
6162
Chris Lattnerfaa54172010-01-12 21:23:57 +00006163QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00006164 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006165 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006166 if (lex->getType()->hasIntegerRepresentation() &&
6167 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006168 return CheckVectorOperands(Loc, lex, rex);
6169 return InvalidOperands(Loc, lex, rex);
6170 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006171
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006172 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006173
Chris Lattnerfaa54172010-01-12 21:23:57 +00006174 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6175 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006176
Chris Lattnerfaa54172010-01-12 21:23:57 +00006177 // Check for remainder by zero.
6178 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00006179 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
6180 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006181
Chris Lattnerfaa54172010-01-12 21:23:57 +00006182 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006183}
6184
Chris Lattnerfaa54172010-01-12 21:23:57 +00006185QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00006186 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006187 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6188 QualType compType = CheckVectorOperands(Loc, lex, rex);
6189 if (CompLHSTy) *CompLHSTy = compType;
6190 return compType;
6191 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006192
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006193 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006194
Steve Naroffe4718892007-04-27 18:30:00 +00006195 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006196 if (lex->getType()->isArithmeticType() &&
6197 rex->getType()->isArithmeticType()) {
6198 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006199 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006200 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006201
Eli Friedman8e122982008-05-18 18:08:51 +00006202 // Put any potential pointer into PExp
6203 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00006204 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006205 std::swap(PExp, IExp);
6206
Steve Naroff6b712a72009-07-14 18:25:06 +00006207 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006208
Eli Friedman8e122982008-05-18 18:08:51 +00006209 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006210 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006211
Chris Lattner12bdebb2009-04-24 23:50:08 +00006212 // Check for arithmetic on pointers to incomplete types.
6213 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006214 if (getLangOptions().CPlusPlus) {
6215 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00006216 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00006217 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006218 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006219
6220 // GNU extension: arithmetic on pointer to void
6221 Diag(Loc, diag::ext_gnu_void_ptr)
6222 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006223 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006224 if (getLangOptions().CPlusPlus) {
6225 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6226 << lex->getType() << lex->getSourceRange();
6227 return QualType();
6228 }
6229
6230 // GNU extension: arithmetic on pointer to function
6231 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6232 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00006233 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006234 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00006235 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00006236 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006237 PExp->getType()->isObjCObjectPointerType()) &&
6238 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00006239 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6240 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006241 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006242 return QualType();
6243 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00006244 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006245 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006246 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6247 << PointeeTy << PExp->getSourceRange();
6248 return QualType();
6249 }
Mike Stump11289f42009-09-09 15:08:12 +00006250
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006251 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00006252 QualType LHSTy = Context.isPromotableBitField(lex);
6253 if (LHSTy.isNull()) {
6254 LHSTy = lex->getType();
6255 if (LHSTy->isPromotableIntegerType())
6256 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006257 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006258 *CompLHSTy = LHSTy;
6259 }
Eli Friedman8e122982008-05-18 18:08:51 +00006260 return PExp->getType();
6261 }
6262 }
6263
Chris Lattner326f7572008-11-18 01:30:42 +00006264 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006265}
6266
Chris Lattner2a3569b2008-04-07 05:30:13 +00006267// C99 6.5.6
6268QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006269 SourceLocation Loc, QualType* CompLHSTy) {
6270 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6271 QualType compType = CheckVectorOperands(Loc, lex, rex);
6272 if (CompLHSTy) *CompLHSTy = compType;
6273 return compType;
6274 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006275
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006276 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006277
Chris Lattner4d62f422007-12-09 21:53:25 +00006278 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006279
Chris Lattner4d62f422007-12-09 21:53:25 +00006280 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00006281 if (lex->getType()->isArithmeticType()
6282 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006283 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006284 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006285 }
Mike Stump11289f42009-09-09 15:08:12 +00006286
Chris Lattner4d62f422007-12-09 21:53:25 +00006287 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00006288 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00006289 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006290
Douglas Gregorac1fb652009-03-24 19:52:54 +00006291 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006292
Douglas Gregorac1fb652009-03-24 19:52:54 +00006293 bool ComplainAboutVoid = false;
6294 Expr *ComplainAboutFunc = 0;
6295 if (lpointee->isVoidType()) {
6296 if (getLangOptions().CPlusPlus) {
6297 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6298 << lex->getSourceRange() << rex->getSourceRange();
6299 return QualType();
6300 }
6301
6302 // GNU C extension: arithmetic on pointer to void
6303 ComplainAboutVoid = true;
6304 } else if (lpointee->isFunctionType()) {
6305 if (getLangOptions().CPlusPlus) {
6306 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006307 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006308 return QualType();
6309 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006310
6311 // GNU C extension: arithmetic on pointer to function
6312 ComplainAboutFunc = lex;
6313 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00006314 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006315 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00006316 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006317 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006318 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006319
Chris Lattner12bdebb2009-04-24 23:50:08 +00006320 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006321 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006322 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6323 << lpointee << lex->getSourceRange();
6324 return QualType();
6325 }
Mike Stump11289f42009-09-09 15:08:12 +00006326
Chris Lattner4d62f422007-12-09 21:53:25 +00006327 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00006328 if (rex->getType()->isIntegerType()) {
6329 if (ComplainAboutVoid)
6330 Diag(Loc, diag::ext_gnu_void_ptr)
6331 << lex->getSourceRange() << rex->getSourceRange();
6332 if (ComplainAboutFunc)
6333 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006334 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006335 << ComplainAboutFunc->getSourceRange();
6336
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006337 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006338 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006339 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006340
Chris Lattner4d62f422007-12-09 21:53:25 +00006341 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006342 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006343 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006344
Douglas Gregorac1fb652009-03-24 19:52:54 +00006345 // RHS must be a completely-type object type.
6346 // Handle the GNU void* extension.
6347 if (rpointee->isVoidType()) {
6348 if (getLangOptions().CPlusPlus) {
6349 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6350 << lex->getSourceRange() << rex->getSourceRange();
6351 return QualType();
6352 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006353
Douglas Gregorac1fb652009-03-24 19:52:54 +00006354 ComplainAboutVoid = true;
6355 } else if (rpointee->isFunctionType()) {
6356 if (getLangOptions().CPlusPlus) {
6357 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006358 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006359 return QualType();
6360 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006361
6362 // GNU extension: arithmetic on pointer to function
6363 if (!ComplainAboutFunc)
6364 ComplainAboutFunc = rex;
6365 } else if (!rpointee->isDependentType() &&
6366 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006367 PDiag(diag::err_typecheck_sub_ptr_object)
6368 << rex->getSourceRange()
6369 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006370 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006371
Eli Friedman168fe152009-05-16 13:54:38 +00006372 if (getLangOptions().CPlusPlus) {
6373 // Pointee types must be the same: C++ [expr.add]
6374 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6375 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6376 << lex->getType() << rex->getType()
6377 << lex->getSourceRange() << rex->getSourceRange();
6378 return QualType();
6379 }
6380 } else {
6381 // Pointee types must be compatible C99 6.5.6p3
6382 if (!Context.typesAreCompatible(
6383 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6384 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6385 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6386 << lex->getType() << rex->getType()
6387 << lex->getSourceRange() << rex->getSourceRange();
6388 return QualType();
6389 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006390 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006391
Douglas Gregorac1fb652009-03-24 19:52:54 +00006392 if (ComplainAboutVoid)
6393 Diag(Loc, diag::ext_gnu_void_ptr)
6394 << lex->getSourceRange() << rex->getSourceRange();
6395 if (ComplainAboutFunc)
6396 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006397 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006398 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006399
6400 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006401 return Context.getPointerDiffType();
6402 }
6403 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006404
Chris Lattner326f7572008-11-18 01:30:42 +00006405 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006406}
6407
Douglas Gregor0bf31402010-10-08 23:50:27 +00006408static bool isScopedEnumerationType(QualType T) {
6409 if (const EnumType *ET = dyn_cast<EnumType>(T))
6410 return ET->getDecl()->isScoped();
6411 return false;
6412}
6413
Chris Lattner2a3569b2008-04-07 05:30:13 +00006414// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00006415QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00006416 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006417 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006418 if (!lex->getType()->hasIntegerRepresentation() ||
6419 !rex->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006420 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006421
Douglas Gregor0bf31402010-10-08 23:50:27 +00006422 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6423 // hasIntegerRepresentation() above instead of this.
6424 if (isScopedEnumerationType(lex->getType()) ||
6425 isScopedEnumerationType(rex->getType())) {
6426 return InvalidOperands(Loc, lex, rex);
6427 }
6428
Nate Begemane46ee9a2009-10-25 02:26:48 +00006429 // Vector shifts promote their scalar inputs to vector type.
6430 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6431 return CheckVectorOperands(Loc, lex, rex);
6432
Chris Lattner5c11c412007-12-12 05:47:28 +00006433 // Shifts don't perform usual arithmetic conversions, they just do integer
6434 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006435
John McCall57cdd882010-12-16 19:28:59 +00006436 // For the LHS, do usual unary conversions, but then reset them away
6437 // if this is a compound assignment.
6438 Expr *old_lex = lex;
6439 UsualUnaryConversions(lex);
6440 QualType LHSTy = lex->getType();
6441 if (isCompAssign) lex = old_lex;
6442
6443 // The RHS is simpler.
Chris Lattner5c11c412007-12-12 05:47:28 +00006444 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006445
Ryan Flynnf53fab82009-08-07 16:20:20 +00006446 // Sanity-check shift operands
6447 llvm::APSInt Right;
6448 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00006449 if (!rex->isValueDependent() &&
6450 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00006451 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00006452 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6453 else {
6454 llvm::APInt LeftBits(Right.getBitWidth(),
6455 Context.getTypeSize(lex->getType()));
6456 if (Right.uge(LeftBits))
6457 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6458 }
6459 }
6460
Chris Lattner5c11c412007-12-12 05:47:28 +00006461 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006462 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006463}
6464
Chandler Carruth17773fc2010-07-10 12:30:03 +00006465static bool IsWithinTemplateSpecialization(Decl *D) {
6466 if (DeclContext *DC = D->getDeclContext()) {
6467 if (isa<ClassTemplateSpecializationDecl>(DC))
6468 return true;
6469 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6470 return FD->isFunctionTemplateSpecialization();
6471 }
6472 return false;
6473}
6474
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006475// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00006476QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006477 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006478 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006479
Chris Lattner9a152e22009-12-05 05:40:13 +00006480 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00006481 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006482 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006483
Steve Naroff31090012007-07-16 21:54:35 +00006484 QualType lType = lex->getType();
6485 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006486
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006487 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006488 !(lType->isBlockPointerType() && isRelational) &&
6489 !lex->getLocStart().isMacroID() &&
6490 !rex->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006491 // For non-floating point types, check for self-comparisons of the form
6492 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6493 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006494 //
6495 // NOTE: Don't warn about comparison expressions resulting from macro
6496 // expansion. Also don't warn about comparisons which are only self
6497 // comparisons within a template specialization. The warnings should catch
6498 // obvious cases in the definition of the template anyways. The idea is to
6499 // warn when the typed comparison operator will always evaluate to the same
6500 // result.
John McCall34376a62010-12-04 03:47:34 +00006501 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6502 Expr *RHSStripped = rex->IgnoreParenImpCasts();
Chandler Carruth17773fc2010-07-10 12:30:03 +00006503 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006504 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006505 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006506 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006507 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6508 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006509 << (Opc == BO_EQ
6510 || Opc == BO_LE
6511 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006512 } else if (lType->isArrayType() && rType->isArrayType() &&
6513 !DRL->getDecl()->getType()->isReferenceType() &&
6514 !DRR->getDecl()->getType()->isReferenceType()) {
6515 // what is it always going to eval to?
6516 char always_evals_to;
6517 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006518 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006519 always_evals_to = 0; // false
6520 break;
John McCalle3027922010-08-25 11:45:40 +00006521 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006522 always_evals_to = 1; // true
6523 break;
6524 default:
6525 // best we can say is 'a constant'
6526 always_evals_to = 2; // e.g. array1 <= array2
6527 break;
6528 }
6529 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6530 << 1 // array
6531 << always_evals_to);
6532 }
6533 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006534 }
Mike Stump11289f42009-09-09 15:08:12 +00006535
Chris Lattner222b8bd2009-03-08 19:39:53 +00006536 if (isa<CastExpr>(LHSStripped))
6537 LHSStripped = LHSStripped->IgnoreParenCasts();
6538 if (isa<CastExpr>(RHSStripped))
6539 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006540
Chris Lattner222b8bd2009-03-08 19:39:53 +00006541 // Warn about comparisons against a string constant (unless the other
6542 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006543 Expr *literalString = 0;
6544 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006545 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006546 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006547 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006548 literalString = lex;
6549 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006550 } else if ((isa<StringLiteral>(RHSStripped) ||
6551 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006552 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006553 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006554 literalString = rex;
6555 literalStringStripped = RHSStripped;
6556 }
6557
6558 if (literalString) {
6559 std::string resultComparison;
6560 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006561 case BO_LT: resultComparison = ") < 0"; break;
6562 case BO_GT: resultComparison = ") > 0"; break;
6563 case BO_LE: resultComparison = ") <= 0"; break;
6564 case BO_GE: resultComparison = ") >= 0"; break;
6565 case BO_EQ: resultComparison = ") == 0"; break;
6566 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006567 default: assert(false && "Invalid comparison operator");
6568 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006569
Douglas Gregor49862b82010-01-12 23:18:54 +00006570 DiagRuntimeBehavior(Loc,
6571 PDiag(diag::warn_stringcompare)
6572 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006573 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006574 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006575 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006576
Douglas Gregorec170db2010-06-08 19:50:34 +00006577 // C99 6.5.8p3 / C99 6.5.9p4
6578 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6579 UsualArithmeticConversions(lex, rex);
6580 else {
6581 UsualUnaryConversions(lex);
6582 UsualUnaryConversions(rex);
6583 }
6584
6585 lType = lex->getType();
6586 rType = rex->getType();
6587
Douglas Gregorca63811b2008-11-19 03:25:36 +00006588 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00006589 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00006590
Chris Lattnerb620c342007-08-26 01:18:55 +00006591 if (isRelational) {
6592 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006593 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006594 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006595 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006596 if (lType->hasFloatingRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006597 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006598
Chris Lattnerb620c342007-08-26 01:18:55 +00006599 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006600 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006601 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006602
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006603 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006604 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006605 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006606 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006607
Douglas Gregorf267edd2010-06-15 21:38:40 +00006608 // All of the following pointer-related warnings are GCC extensions, except
6609 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006610 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006611 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006612 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006613 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006614 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006615
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006616 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006617 if (LCanPointeeTy == RCanPointeeTy)
6618 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006619 if (!isRelational &&
6620 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6621 // Valid unless comparison between non-null pointer and function pointer
6622 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006623 // In a SFINAE context, we treat this as a hard error to maintain
6624 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006625 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6626 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006627 Diag(Loc,
6628 isSFINAEContext()?
6629 diag::err_typecheck_comparison_of_fptr_to_void
6630 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006631 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006632
6633 if (isSFINAEContext())
6634 return QualType();
6635
John McCalle3027922010-08-25 11:45:40 +00006636 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006637 return ResultTy;
6638 }
6639 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006640
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006641 // C++ [expr.rel]p2:
6642 // [...] Pointer conversions (4.10) and qualification
6643 // conversions (4.4) are performed on pointer operands (or on
6644 // a pointer operand and a null pointer constant) to bring
6645 // them to their composite pointer type. [...]
6646 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006647 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006648 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006649 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006650 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006651 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006652 if (T.isNull()) {
6653 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6654 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6655 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006656 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006657 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006658 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006659 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006660 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006661 }
6662
John McCalle3027922010-08-25 11:45:40 +00006663 ImpCastExprToType(lex, T, CK_BitCast);
6664 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006665 return ResultTy;
6666 }
Eli Friedman16c209612009-08-23 00:27:47 +00006667 // C99 6.5.9p2 and C99 6.5.8p2
6668 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6669 RCanPointeeTy.getUnqualifiedType())) {
6670 // Valid unless a relational comparison of function pointers
6671 if (isRelational && LCanPointeeTy->isFunctionType()) {
6672 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6673 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6674 }
6675 } else if (!isRelational &&
6676 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6677 // Valid unless comparison between non-null pointer and function pointer
6678 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6679 && !LHSIsNull && !RHSIsNull) {
6680 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6681 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6682 }
6683 } else {
6684 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006685 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006686 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006687 }
Eli Friedman16c209612009-08-23 00:27:47 +00006688 if (LCanPointeeTy != RCanPointeeTy)
John McCalle3027922010-08-25 11:45:40 +00006689 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006690 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006691 }
Mike Stump11289f42009-09-09 15:08:12 +00006692
Sebastian Redl576fd422009-05-10 18:38:11 +00006693 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006694 // Comparison of nullptr_t with itself.
6695 if (lType->isNullPtrType() && rType->isNullPtrType())
6696 return ResultTy;
6697
Mike Stump11289f42009-09-09 15:08:12 +00006698 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006699 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006700 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006701 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006702 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006703 ImpCastExprToType(rex, lType,
6704 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006705 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006706 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006707 return ResultTy;
6708 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006709 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006710 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006711 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006712 ImpCastExprToType(lex, rType,
6713 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006714 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006715 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006716 return ResultTy;
6717 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006718
6719 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006720 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006721 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6722 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006723 // In addition, pointers to members can be compared, or a pointer to
6724 // member and a null pointer constant. Pointer to member conversions
6725 // (4.11) and qualification conversions (4.4) are performed to bring
6726 // them to a common type. If one operand is a null pointer constant,
6727 // the common type is the type of the other operand. Otherwise, the
6728 // common type is a pointer to member type similar (4.4) to the type
6729 // of one of the operands, with a cv-qualification signature (4.4)
6730 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006731 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006732 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006733 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006734 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006735 if (T.isNull()) {
6736 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006737 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006738 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006739 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006740 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006741 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006742 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006743 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006744 }
Mike Stump11289f42009-09-09 15:08:12 +00006745
John McCalle3027922010-08-25 11:45:40 +00006746 ImpCastExprToType(lex, T, CK_BitCast);
6747 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006748 return ResultTy;
6749 }
Sebastian Redl576fd422009-05-10 18:38:11 +00006750 }
Mike Stump11289f42009-09-09 15:08:12 +00006751
Steve Naroff081c7422008-09-04 15:10:53 +00006752 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00006753 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006754 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6755 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006756
Steve Naroff081c7422008-09-04 15:10:53 +00006757 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006758 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006759 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006760 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006761 }
John McCalle3027922010-08-25 11:45:40 +00006762 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006763 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006764 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00006765 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006766 if (!isRelational
6767 && ((lType->isBlockPointerType() && rType->isPointerType())
6768 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006769 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006770 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006771 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006772 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006773 ->getPointeeType()->isVoidType())))
6774 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6775 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006776 }
John McCalle3027922010-08-25 11:45:40 +00006777 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006778 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006779 }
Steve Naroff081c7422008-09-04 15:10:53 +00006780
Steve Naroff7cae42b2009-07-10 23:34:53 +00006781 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006782 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006783 const PointerType *LPT = lType->getAs<PointerType>();
6784 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006785 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00006786 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006787 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00006788 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006789
Steve Naroff753567f2008-11-17 19:49:16 +00006790 if (!LPtrToVoid && !RPtrToVoid &&
6791 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006792 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006793 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006794 }
John McCalle3027922010-08-25 11:45:40 +00006795 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006796 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006797 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006798 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006799 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006800 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6801 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006802 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006803 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006804 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006805 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006806 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6807 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006808 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006809 bool isError = false;
6810 if ((LHSIsNull && lType->isIntegerType()) ||
6811 (RHSIsNull && rType->isIntegerType())) {
6812 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006813 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006814 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006815 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006816 else if (getLangOptions().CPlusPlus) {
6817 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6818 isError = true;
6819 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006820 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006821
Chris Lattnerd99bd522009-08-23 00:03:44 +00006822 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006823 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00006824 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006825 if (isError)
6826 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006827 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006828
6829 if (lType->isIntegerType())
John McCalle84af4e2010-11-13 01:35:44 +00006830 ImpCastExprToType(lex, rType,
6831 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006832 else
John McCalle84af4e2010-11-13 01:35:44 +00006833 ImpCastExprToType(rex, lType,
6834 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006835 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006836 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006837
Steve Naroff4b191572008-09-04 16:56:14 +00006838 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006839 if (!isRelational && RHSIsNull
6840 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00006841 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006842 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006843 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006844 if (!isRelational && LHSIsNull
6845 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00006846 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006847 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006848 }
Chris Lattner326f7572008-11-18 01:30:42 +00006849 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006850}
6851
Nate Begeman191a6b12008-07-14 18:02:46 +00006852/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006853/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006854/// like a scalar comparison, a vector comparison produces a vector of integer
6855/// types.
6856QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00006857 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006858 bool isRelational) {
6859 // Check to make sure we're operating on vectors of the same type and width,
6860 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00006861 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00006862 if (vType.isNull())
6863 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006864
Anton Yartsev3f8f2882010-11-18 03:19:30 +00006865 // If AltiVec, the comparison results in a numeric type, i.e.
6866 // bool for C++, int for C
6867 if (getLangOptions().AltiVec)
6868 return (getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy);
6869
Nate Begeman191a6b12008-07-14 18:02:46 +00006870 QualType lType = lex->getType();
6871 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006872
Nate Begeman191a6b12008-07-14 18:02:46 +00006873 // For non-floating point types, check for self-comparisons of the form
6874 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6875 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006876 if (!lType->hasFloatingRepresentation()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006877 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
6878 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
6879 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregorec170db2010-06-08 19:50:34 +00006880 DiagRuntimeBehavior(Loc,
6881 PDiag(diag::warn_comparison_always)
6882 << 0 // self-
6883 << 2 // "a constant"
6884 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006885 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006886
Nate Begeman191a6b12008-07-14 18:02:46 +00006887 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006888 if (!isRelational && lType->hasFloatingRepresentation()) {
6889 assert (rType->hasFloatingRepresentation());
Chris Lattner326f7572008-11-18 01:30:42 +00006890 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00006891 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006892
Nate Begeman191a6b12008-07-14 18:02:46 +00006893 // Return the type for the comparison, which is the same as vector type for
6894 // integer vectors, or an integer type of identical size and number of
6895 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006896 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00006897 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006898
John McCall9dd450b2009-09-21 23:43:11 +00006899 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006900 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006901 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006902 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006903 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006904 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6905
Mike Stump4e1f26a2009-02-19 03:04:26 +00006906 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006907 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006908 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6909}
6910
Steve Naroff218bc2b2007-05-04 21:54:46 +00006911inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00006912 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006913 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6914 if (lex->getType()->hasIntegerRepresentation() &&
6915 rex->getType()->hasIntegerRepresentation())
6916 return CheckVectorOperands(Loc, lex, rex);
6917
6918 return InvalidOperands(Loc, lex, rex);
6919 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006920
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006921 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006922
Douglas Gregor0bf31402010-10-08 23:50:27 +00006923 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
6924 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006925 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00006926 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006927}
6928
Steve Naroff218bc2b2007-05-04 21:54:46 +00006929inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner8406c512010-07-13 19:41:32 +00006930 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
6931
6932 // Diagnose cases where the user write a logical and/or but probably meant a
6933 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6934 // is a constant.
6935 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman6b197e02010-07-27 19:14:53 +00006936 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00006937 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00006938 !Loc.isMacroID()) {
6939 // If the RHS can be constant folded, and if it constant folds to something
6940 // that isn't 0 or 1 (which indicate a potential logical operation that
6941 // happened to fold to true/false) then warn.
6942 Expr::EvalResult Result;
6943 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
6944 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
6945 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6946 << rex->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00006947 << (Opc == BO_LAnd ? "&&" : "||")
6948 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00006949 }
6950 }
Chris Lattner8406c512010-07-13 19:41:32 +00006951
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006952 if (!Context.getLangOptions().CPlusPlus) {
6953 UsualUnaryConversions(lex);
6954 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006955
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006956 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
6957 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006958
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006959 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006960 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006961
John McCall4a2429a2010-06-04 00:29:51 +00006962 // The following is safe because we only use this method for
6963 // non-overloadable operands.
6964
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006965 // C++ [expr.log.and]p1
6966 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006967 // The operands are both contextually converted to type bool.
6968 if (PerformContextuallyConvertToBool(lex) ||
6969 PerformContextuallyConvertToBool(rex))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006970 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006971
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006972 // C++ [expr.log.and]p2
6973 // C++ [expr.log.or]p2
6974 // The result is a bool.
6975 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006976}
6977
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006978/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6979/// is a read-only property; return true if so. A readonly property expression
6980/// depends on various declarations and thus must be treated specially.
6981///
Mike Stump11289f42009-09-09 15:08:12 +00006982static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006983 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6984 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006985 if (PropExpr->isImplicitProperty()) return false;
6986
6987 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6988 QualType BaseType = PropExpr->isSuperReceiver() ?
6989 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006990 PropExpr->getBase()->getType();
6991
John McCallb7bd14f2010-12-02 01:19:52 +00006992 if (const ObjCObjectPointerType *OPT =
6993 BaseType->getAsObjCInterfacePointerType())
6994 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6995 if (S.isPropertyReadonly(PDecl, IFace))
6996 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006997 }
6998 return false;
6999}
7000
Chris Lattner30bd3272008-11-18 01:22:49 +00007001/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7002/// emit an error and return true. If so, return false.
7003static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007004 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007005 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007006 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007007 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7008 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00007009 if (IsLV == Expr::MLV_Valid)
7010 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007011
Chris Lattner30bd3272008-11-18 01:22:49 +00007012 unsigned Diag = 0;
7013 bool NeedType = false;
7014 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00007015 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007016 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007017 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7018 NeedType = true;
7019 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007020 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007021 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7022 NeedType = true;
7023 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007024 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007025 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7026 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007027 case Expr::MLV_Valid:
7028 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007029 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007030 case Expr::MLV_MemberFunction:
7031 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007032 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7033 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007034 case Expr::MLV_IncompleteType:
7035 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007036 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007037 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007038 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007039 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007040 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7041 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007042 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007043 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7044 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007045 case Expr::MLV_ReadonlyProperty:
7046 Diag = diag::error_readonly_property_assignment;
7047 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007048 case Expr::MLV_NoSetterProperty:
7049 Diag = diag::error_nosetter_property_assignment;
7050 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007051 case Expr::MLV_SubObjCPropertySetting:
7052 Diag = diag::error_no_subobject_property_setting;
7053 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007054 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007055
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007056 SourceRange Assign;
7057 if (Loc != OrigLoc)
7058 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007059 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007060 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007061 else
Mike Stump11289f42009-09-09 15:08:12 +00007062 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007063 return true;
7064}
7065
7066
7067
7068// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00007069QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
7070 SourceLocation Loc,
7071 QualType CompoundType) {
7072 // Verify that LHS is a modifiable lvalue, and emit error if not.
7073 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007074 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007075
7076 QualType LHSType = LHS->getType();
7077 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007078 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007079 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007080 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007081 // Simple assignment "x = y".
John McCall34376a62010-12-04 03:47:34 +00007082 if (LHS->getObjectKind() == OK_ObjCProperty)
7083 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007084 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007085 // Special case of NSObject attributes on c-style pointer types.
7086 if (ConvTy == IncompatiblePointer &&
7087 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007088 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007089 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007090 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007091 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007092
John McCall7decc9e2010-11-18 06:31:45 +00007093 if (ConvTy == Compatible &&
7094 getLangOptions().ObjCNonFragileABI &&
7095 LHSType->isObjCObjectType())
7096 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7097 << LHSType;
7098
Chris Lattnerea714382008-08-21 18:04:13 +00007099 // If the RHS is a unary plus or minus, check to see if they = and + are
7100 // right next to each other. If so, the user may have typo'd "x =+ 4"
7101 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00007102 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00007103 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7104 RHSCheck = ICE->getSubExpr();
7105 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007106 if ((UO->getOpcode() == UO_Plus ||
7107 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007108 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007109 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00007110 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7111 // And there is a space or other character before the subexpr of the
7112 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00007113 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7114 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007115 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007116 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007117 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007118 }
Chris Lattnerea714382008-08-21 18:04:13 +00007119 }
7120 } else {
7121 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007122 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007123 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007124
Chris Lattner326f7572008-11-18 01:30:42 +00007125 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007126 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007127 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007128
Chris Lattner39561062010-07-07 06:14:23 +00007129
7130 // Check to see if the destination operand is a dereferenced null pointer. If
7131 // so, and if not volatile-qualified, this is undefined behavior that the
7132 // optimizer will delete, so warn about it. People sometimes try to use this
7133 // to get a deterministic trap and are surprised by clang's behavior. This
7134 // only handles the pattern "*null = whatever", which is a very syntactic
7135 // check.
7136 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCalle3027922010-08-25 11:45:40 +00007137 if (UO->getOpcode() == UO_Deref &&
Chris Lattner39561062010-07-07 06:14:23 +00007138 UO->getSubExpr()->IgnoreParenCasts()->
7139 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7140 !UO->getType().isVolatileQualified()) {
7141 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
7142 << UO->getSubExpr()->getSourceRange();
7143 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
7144 }
7145
Steve Naroff98cf3e92007-06-06 18:38:38 +00007146 // C99 6.5.16p3: The type of an assignment expression is the type of the
7147 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007148 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007149 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7150 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007151 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007152 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007153 return (getLangOptions().CPlusPlus
7154 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007155}
7156
Chris Lattner326f7572008-11-18 01:30:42 +00007157// C99 6.5.17
John McCall34376a62010-12-04 03:47:34 +00007158static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007159 SourceLocation Loc) {
7160 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007161
John McCall4bc41ae2010-11-18 19:01:18 +00007162 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007163 if (LHSResult.isInvalid())
7164 return QualType();
7165
John McCall4bc41ae2010-11-18 19:01:18 +00007166 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007167 if (RHSResult.isInvalid())
7168 return QualType();
7169 RHS = RHSResult.take();
7170
John McCall73d36182010-10-12 07:14:40 +00007171 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7172 // operands, but not unary promotions.
7173 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007174
John McCall34376a62010-12-04 03:47:34 +00007175 // So we treat the LHS as a ignored value, and in C++ we allow the
7176 // containing site to determine what should be done with the RHS.
7177 S.IgnoredValueConversions(LHS);
7178
7179 if (!S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007180 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCall73d36182010-10-12 07:14:40 +00007181 if (!RHS->getType()->isVoidType())
John McCall4bc41ae2010-11-18 19:01:18 +00007182 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007183 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007184
Chris Lattner326f7572008-11-18 01:30:42 +00007185 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007186}
7187
Steve Naroff7a5af782007-07-13 16:58:59 +00007188/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7189/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007190static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7191 ExprValueKind &VK,
7192 SourceLocation OpLoc,
7193 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007194 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007195 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007196
Chris Lattner6b0cf142008-11-21 07:05:48 +00007197 QualType ResType = Op->getType();
7198 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007199
John McCall4bc41ae2010-11-18 19:01:18 +00007200 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007201 // Decrement of bool is not allowed.
7202 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007203 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007204 return QualType();
7205 }
7206 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007207 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007208 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007209 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007210 } else if (ResType->isAnyPointerType()) {
7211 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007212
Chris Lattner6b0cf142008-11-21 07:05:48 +00007213 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00007214 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007215 if (S.getLangOptions().CPlusPlus) {
7216 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007217 << Op->getSourceRange();
7218 return QualType();
7219 }
7220
7221 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00007222 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007223 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007224 if (S.getLangOptions().CPlusPlus) {
7225 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007226 << Op->getType() << Op->getSourceRange();
7227 return QualType();
7228 }
7229
John McCall4bc41ae2010-11-18 19:01:18 +00007230 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007231 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007232 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7233 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00007234 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00007235 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00007236 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007237 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00007238 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7239 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007240 << PointeeTy << Op->getSourceRange();
7241 return QualType();
7242 }
Eli Friedman090addd2010-01-03 00:20:48 +00007243 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007244 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007245 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007246 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007247 } else if (ResType->isPlaceholderType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007248 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007249 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007250 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7251 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007252 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7253 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007254 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007255 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007256 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007257 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007258 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007259 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007260 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007261 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007262 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007263 // In C++, a prefix increment is the same type as the operand. Otherwise
7264 // (in C or with postfix), the increment is the unqualified type of the
7265 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007266 if (isPrefix && S.getLangOptions().CPlusPlus) {
7267 VK = VK_LValue;
7268 return ResType;
7269 } else {
7270 VK = VK_RValue;
7271 return ResType.getUnqualifiedType();
7272 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007273}
7274
John McCall34376a62010-12-04 03:47:34 +00007275void Sema::ConvertPropertyForRValue(Expr *&E) {
7276 assert(E->getValueKind() == VK_LValue &&
7277 E->getObjectKind() == OK_ObjCProperty);
7278 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7279
7280 ExprValueKind VK = VK_RValue;
7281 if (PRE->isImplicitProperty()) {
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007282 if (const ObjCMethodDecl *GetterMethod =
7283 PRE->getImplicitPropertyGetter()) {
7284 QualType Result = GetterMethod->getResultType();
7285 VK = Expr::getValueKindForType(Result);
7286 }
7287 else {
7288 Diag(PRE->getLocation(), diag::err_getter_not_found)
7289 << PRE->getBase()->getType();
7290 }
John McCall34376a62010-12-04 03:47:34 +00007291 }
7292
7293 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7294 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007295
7296 ExprResult Result = MaybeBindToTemporary(E);
7297 if (!Result.isInvalid())
7298 E = Result.take();
John McCall34376a62010-12-04 03:47:34 +00007299}
7300
7301void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7302 assert(LHS->getValueKind() == VK_LValue &&
7303 LHS->getObjectKind() == OK_ObjCProperty);
7304 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7305
7306 if (PRE->isImplicitProperty()) {
7307 // If using property-dot syntax notation for assignment, and there is a
7308 // setter, RHS expression is being passed to the setter argument. So,
7309 // type conversion (and comparison) is RHS to setter's argument type.
7310 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7311 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7312 LHSTy = (*P)->getType();
7313
7314 // Otherwise, if the getter returns an l-value, just call that.
7315 } else {
7316 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7317 ExprValueKind VK = Expr::getValueKindForType(Result);
7318 if (VK == VK_LValue) {
7319 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7320 CK_GetObjCProperty, LHS, 0, VK);
7321 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007322 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007323 }
John McCall34376a62010-12-04 03:47:34 +00007324 }
7325
7326 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007327 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007328 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007329 Expr *Arg = RHS;
7330 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7331 Owned(Arg));
7332 if (!ArgE.isInvalid())
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007333 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007334 }
7335}
7336
7337
Anders Carlsson806700f2008-02-01 07:15:58 +00007338/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007339/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007340/// where the declaration is needed for type checking. We only need to
7341/// handle cases when the expression references a function designator
7342/// or is an lvalue. Here are some examples:
7343/// - &(x) => x
7344/// - &*****f => f for f a function designator.
7345/// - &s.xx => s
7346/// - &s.zz[1].yy -> s, if zz is an array
7347/// - *(x + 1) -> x, if x is an array
7348/// - &"123"[2] -> 0
7349/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007350static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007351 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007352 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007353 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007354 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007355 // If this is an arrow operator, the address is an offset from
7356 // the base's value, so the object the base refers to is
7357 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007358 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007359 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007360 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007361 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007362 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007363 // FIXME: This code shouldn't be necessary! We should catch the implicit
7364 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007365 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7366 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7367 if (ICE->getSubExpr()->getType()->isArrayType())
7368 return getPrimaryDecl(ICE->getSubExpr());
7369 }
7370 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007371 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007372 case Stmt::UnaryOperatorClass: {
7373 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007374
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007375 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007376 case UO_Real:
7377 case UO_Imag:
7378 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007379 return getPrimaryDecl(UO->getSubExpr());
7380 default:
7381 return 0;
7382 }
7383 }
Steve Naroff47500512007-04-19 23:00:49 +00007384 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007385 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007386 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007387 // If the result of an implicit cast is an l-value, we care about
7388 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007389 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007390 default:
7391 return 0;
7392 }
7393}
7394
7395/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007396/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007397/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007398/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007399/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007400/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007401/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007402static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7403 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007404 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007405 return S.Context.DependentTy;
7406 if (OrigOp->getType() == S.Context.OverloadTy)
7407 return S.Context.OverloadTy;
John McCall8d08b9b2010-08-27 09:08:28 +00007408
John McCall4bc41ae2010-11-18 19:01:18 +00007409 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007410 if (PR.isInvalid()) return QualType();
7411 OrigOp = PR.take();
7412
John McCall8d08b9b2010-08-27 09:08:28 +00007413 // Make sure to ignore parentheses in subsequent checks
7414 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007415
John McCall4bc41ae2010-11-18 19:01:18 +00007416 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007417 // Implement C99-only parts of addressof rules.
7418 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007419 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007420 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7421 // (assuming the deref expression is valid).
7422 return uOp->getSubExpr()->getType();
7423 }
7424 // Technically, there should be a check for array subscript
7425 // expressions here, but the result of one is always an lvalue anyway.
7426 }
John McCallf3a88602011-02-03 08:15:49 +00007427 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007428 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007429
Chris Lattner9156f1b2010-07-05 19:17:26 +00007430 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007431 bool sfinae = S.isSFINAEContext();
7432 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7433 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007434 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007435 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007436 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007437 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007438 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007439 } else if (lval == Expr::LV_MemberFunction) {
7440 // If it's an instance method, make a member pointer.
7441 // The expression must have exactly the form &A::foo.
7442
7443 // If the underlying expression isn't a decl ref, give up.
7444 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007445 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007446 << OrigOp->getSourceRange();
7447 return QualType();
7448 }
7449 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7450 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7451
7452 // The id-expression was parenthesized.
7453 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007454 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007455 << OrigOp->getSourceRange();
7456
7457 // The method was named without a qualifier.
7458 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007459 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007460 << op->getSourceRange();
7461 }
7462
John McCall4bc41ae2010-11-18 19:01:18 +00007463 return S.Context.getMemberPointerType(op->getType(),
7464 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007465 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007466 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007467 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007468 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007469 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007470 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007471 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007472 return QualType();
7473 }
John McCall086a4642010-11-24 05:12:34 +00007474 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007475 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007476 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007477 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007478 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007479 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007480 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007481 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007482 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007483 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007484 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007485 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007486 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007487 << "property expression" << op->getSourceRange();
7488 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007489 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007490 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007491 // with the register storage-class specifier.
7492 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007493 // in C++ it is not error to take address of a register
7494 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007495 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007496 !S.getLangOptions().CPlusPlus) {
7497 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007498 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007499 return QualType();
7500 }
John McCalld14a8642009-11-21 08:51:07 +00007501 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007502 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007503 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007504 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007505 // Could be a pointer to member, though, if there is an explicit
7506 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007507 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007508 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007509 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007510 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007511 S.Diag(OpLoc,
7512 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007513 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007514 return QualType();
7515 }
Mike Stump11289f42009-09-09 15:08:12 +00007516
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007517 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7518 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007519 return S.Context.getMemberPointerType(op->getType(),
7520 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007521 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007522 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007523 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007524 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007525 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007526
Eli Friedmance7f9002009-05-16 23:27:50 +00007527 if (lval == Expr::LV_IncompleteVoidType) {
7528 // Taking the address of a void variable is technically illegal, but we
7529 // allow it in cases which are otherwise valid.
7530 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007531 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007532 }
7533
Steve Naroff47500512007-04-19 23:00:49 +00007534 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007535 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007536 return S.Context.getObjCObjectPointerType(op->getType());
7537 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007538}
7539
Chris Lattner9156f1b2010-07-05 19:17:26 +00007540/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007541static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7542 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007543 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007544 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007545
John McCall4bc41ae2010-11-18 19:01:18 +00007546 S.UsualUnaryConversions(Op);
Chris Lattner9156f1b2010-07-05 19:17:26 +00007547 QualType OpTy = Op->getType();
7548 QualType Result;
7549
7550 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7551 // is an incomplete type or void. It would be possible to warn about
7552 // dereferencing a void pointer, but it's completely well-defined, and such a
7553 // warning is unlikely to catch any mistakes.
7554 if (const PointerType *PT = OpTy->getAs<PointerType>())
7555 Result = PT->getPointeeType();
7556 else if (const ObjCObjectPointerType *OPT =
7557 OpTy->getAs<ObjCObjectPointerType>())
7558 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007559 else {
John McCall4bc41ae2010-11-18 19:01:18 +00007560 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007561 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007562 if (PR.take() != Op)
7563 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007564 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007565
Chris Lattner9156f1b2010-07-05 19:17:26 +00007566 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007567 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007568 << OpTy << Op->getSourceRange();
7569 return QualType();
7570 }
John McCall4bc41ae2010-11-18 19:01:18 +00007571
7572 // Dereferences are usually l-values...
7573 VK = VK_LValue;
7574
7575 // ...except that certain expressions are never l-values in C.
7576 if (!S.getLangOptions().CPlusPlus &&
7577 IsCForbiddenLValueType(S.Context, Result))
7578 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007579
7580 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007581}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007582
John McCalle3027922010-08-25 11:45:40 +00007583static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007584 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007585 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007586 switch (Kind) {
7587 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007588 case tok::periodstar: Opc = BO_PtrMemD; break;
7589 case tok::arrowstar: Opc = BO_PtrMemI; break;
7590 case tok::star: Opc = BO_Mul; break;
7591 case tok::slash: Opc = BO_Div; break;
7592 case tok::percent: Opc = BO_Rem; break;
7593 case tok::plus: Opc = BO_Add; break;
7594 case tok::minus: Opc = BO_Sub; break;
7595 case tok::lessless: Opc = BO_Shl; break;
7596 case tok::greatergreater: Opc = BO_Shr; break;
7597 case tok::lessequal: Opc = BO_LE; break;
7598 case tok::less: Opc = BO_LT; break;
7599 case tok::greaterequal: Opc = BO_GE; break;
7600 case tok::greater: Opc = BO_GT; break;
7601 case tok::exclaimequal: Opc = BO_NE; break;
7602 case tok::equalequal: Opc = BO_EQ; break;
7603 case tok::amp: Opc = BO_And; break;
7604 case tok::caret: Opc = BO_Xor; break;
7605 case tok::pipe: Opc = BO_Or; break;
7606 case tok::ampamp: Opc = BO_LAnd; break;
7607 case tok::pipepipe: Opc = BO_LOr; break;
7608 case tok::equal: Opc = BO_Assign; break;
7609 case tok::starequal: Opc = BO_MulAssign; break;
7610 case tok::slashequal: Opc = BO_DivAssign; break;
7611 case tok::percentequal: Opc = BO_RemAssign; break;
7612 case tok::plusequal: Opc = BO_AddAssign; break;
7613 case tok::minusequal: Opc = BO_SubAssign; break;
7614 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7615 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7616 case tok::ampequal: Opc = BO_AndAssign; break;
7617 case tok::caretequal: Opc = BO_XorAssign; break;
7618 case tok::pipeequal: Opc = BO_OrAssign; break;
7619 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007620 }
7621 return Opc;
7622}
7623
John McCalle3027922010-08-25 11:45:40 +00007624static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007625 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007626 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007627 switch (Kind) {
7628 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007629 case tok::plusplus: Opc = UO_PreInc; break;
7630 case tok::minusminus: Opc = UO_PreDec; break;
7631 case tok::amp: Opc = UO_AddrOf; break;
7632 case tok::star: Opc = UO_Deref; break;
7633 case tok::plus: Opc = UO_Plus; break;
7634 case tok::minus: Opc = UO_Minus; break;
7635 case tok::tilde: Opc = UO_Not; break;
7636 case tok::exclaim: Opc = UO_LNot; break;
7637 case tok::kw___real: Opc = UO_Real; break;
7638 case tok::kw___imag: Opc = UO_Imag; break;
7639 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007640 }
7641 return Opc;
7642}
7643
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007644/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7645/// This warning is only emitted for builtin assignment operations. It is also
7646/// suppressed in the event of macro expansions.
7647static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7648 SourceLocation OpLoc) {
7649 if (!S.ActiveTemplateInstantiations.empty())
7650 return;
7651 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7652 return;
7653 lhs = lhs->IgnoreParenImpCasts();
7654 rhs = rhs->IgnoreParenImpCasts();
7655 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7656 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7657 if (!LeftDeclRef || !RightDeclRef ||
7658 LeftDeclRef->getLocation().isMacroID() ||
7659 RightDeclRef->getLocation().isMacroID())
7660 return;
7661 const ValueDecl *LeftDecl =
7662 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7663 const ValueDecl *RightDecl =
7664 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7665 if (LeftDecl != RightDecl)
7666 return;
7667 if (LeftDecl->getType().isVolatileQualified())
7668 return;
7669 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7670 if (RefTy->getPointeeType().isVolatileQualified())
7671 return;
7672
7673 S.Diag(OpLoc, diag::warn_self_assignment)
7674 << LeftDeclRef->getType()
7675 << lhs->getSourceRange() << rhs->getSourceRange();
7676}
7677
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007678/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7679/// operator @p Opc at location @c TokLoc. This routine only supports
7680/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007681ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007682 BinaryOperatorKind Opc,
John McCalle3027922010-08-25 11:45:40 +00007683 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007684 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007685 // The following two variables are used for compound assignment operators
7686 QualType CompLHSTy; // Type of LHS after promotions for computation
7687 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007688 ExprValueKind VK = VK_RValue;
7689 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007690
7691 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007692 case BO_Assign:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007693 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007694 if (getLangOptions().CPlusPlus &&
7695 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall4bc41ae2010-11-18 19:01:18 +00007696 VK = lhs->getValueKind();
7697 OK = lhs->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007698 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007699 if (!ResultTy.isNull())
7700 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007701 break;
John McCalle3027922010-08-25 11:45:40 +00007702 case BO_PtrMemD:
7703 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007704 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007705 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007706 break;
John McCalle3027922010-08-25 11:45:40 +00007707 case BO_Mul:
7708 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007709 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007710 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007711 break;
John McCalle3027922010-08-25 11:45:40 +00007712 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007713 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7714 break;
John McCalle3027922010-08-25 11:45:40 +00007715 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007716 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7717 break;
John McCalle3027922010-08-25 11:45:40 +00007718 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007719 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7720 break;
John McCalle3027922010-08-25 11:45:40 +00007721 case BO_Shl:
7722 case BO_Shr:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007723 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
7724 break;
John McCalle3027922010-08-25 11:45:40 +00007725 case BO_LE:
7726 case BO_LT:
7727 case BO_GE:
7728 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007729 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007730 break;
John McCalle3027922010-08-25 11:45:40 +00007731 case BO_EQ:
7732 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007733 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007734 break;
John McCalle3027922010-08-25 11:45:40 +00007735 case BO_And:
7736 case BO_Xor:
7737 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007738 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7739 break;
John McCalle3027922010-08-25 11:45:40 +00007740 case BO_LAnd:
7741 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007742 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007743 break;
John McCalle3027922010-08-25 11:45:40 +00007744 case BO_MulAssign:
7745 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007746 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007747 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007748 CompLHSTy = CompResultTy;
7749 if (!CompResultTy.isNull())
7750 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007751 break;
John McCalle3027922010-08-25 11:45:40 +00007752 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007753 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7754 CompLHSTy = CompResultTy;
7755 if (!CompResultTy.isNull())
7756 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007757 break;
John McCalle3027922010-08-25 11:45:40 +00007758 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007759 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7760 if (!CompResultTy.isNull())
7761 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007762 break;
John McCalle3027922010-08-25 11:45:40 +00007763 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007764 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7765 if (!CompResultTy.isNull())
7766 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007767 break;
John McCalle3027922010-08-25 11:45:40 +00007768 case BO_ShlAssign:
7769 case BO_ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007770 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
7771 CompLHSTy = CompResultTy;
7772 if (!CompResultTy.isNull())
7773 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007774 break;
John McCalle3027922010-08-25 11:45:40 +00007775 case BO_AndAssign:
7776 case BO_XorAssign:
7777 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007778 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7779 CompLHSTy = CompResultTy;
7780 if (!CompResultTy.isNull())
7781 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007782 break;
John McCalle3027922010-08-25 11:45:40 +00007783 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007784 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCall7decc9e2010-11-18 06:31:45 +00007785 if (getLangOptions().CPlusPlus) {
7786 VK = rhs->getValueKind();
7787 OK = rhs->getObjectKind();
7788 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007789 break;
7790 }
7791 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007792 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007793 if (CompResultTy.isNull())
John McCall7decc9e2010-11-18 06:31:45 +00007794 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
7795 VK, OK, OpLoc));
7796
John McCall34376a62010-12-04 03:47:34 +00007797 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007798 VK = VK_LValue;
7799 OK = lhs->getObjectKind();
7800 }
7801 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
7802 VK, OK, CompLHSTy,
7803 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007804}
7805
Sebastian Redl44615072009-10-27 12:10:02 +00007806/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
7807/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007808static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7809 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007810 const PartialDiagnostic &FirstNote,
7811 SourceRange FirstParenRange,
7812 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00007813 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007814 Self.Diag(Loc, PD);
7815
7816 if (!FirstNote.getDiagID())
7817 return;
7818
7819 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
7820 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7821 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007822 return;
7823 }
7824
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007825 Self.Diag(Loc, FirstNote)
7826 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00007827 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007828
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007829 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007830 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007831
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007832 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
7833 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7834 // We can't display the parentheses, so just dig the
7835 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007836 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007837 return;
7838 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007839
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007840 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00007841 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
7842 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007843}
7844
Sebastian Redl44615072009-10-27 12:10:02 +00007845/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7846/// operators are mixed in a way that suggests that the programmer forgot that
7847/// comparison operators have higher precedence. The most typical example of
7848/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007849static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007850 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007851 typedef BinaryOperator BinOp;
7852 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7853 rhsopc = static_cast<BinOp::Opcode>(-1);
7854 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007855 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007856 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007857 rhsopc = BO->getOpcode();
7858
7859 // Subs are not binary operators.
7860 if (lhsopc == -1 && rhsopc == -1)
7861 return;
7862
7863 // Bitwise operations are sometimes used as eager logical ops.
7864 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007865 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7866 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007867 return;
7868
Sebastian Redl44615072009-10-27 12:10:02 +00007869 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007870 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007871 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00007872 << SourceRange(lhs->getLocStart(), OpLoc)
7873 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00007874 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007875 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007876 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
7877 Self.PDiag(diag::note_precedence_bitwise_silence)
7878 << BinOp::getOpcodeStr(lhsopc),
7879 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00007880 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007881 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007882 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00007883 << SourceRange(OpLoc, rhs->getLocEnd())
7884 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00007885 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007886 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007887 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
7888 Self.PDiag(diag::note_precedence_bitwise_silence)
7889 << BinOp::getOpcodeStr(rhsopc),
7890 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00007891}
7892
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007893/// \brief It accepts a '&&' expr that is inside a '||' one.
7894/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7895/// in parentheses.
7896static void
7897EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
7898 Expr *E) {
7899 assert(isa<BinaryOperator>(E) &&
7900 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
7901 SuggestParentheses(Self, OpLoc,
7902 Self.PDiag(diag::warn_logical_and_in_logical_or)
7903 << E->getSourceRange(),
7904 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
7905 E->getSourceRange(),
7906 Self.PDiag(0), SourceRange());
7907}
7908
7909/// \brief Returns true if the given expression can be evaluated as a constant
7910/// 'true'.
7911static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7912 bool Res;
7913 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7914}
7915
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007916/// \brief Returns true if the given expression can be evaluated as a constant
7917/// 'false'.
7918static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7919 bool Res;
7920 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7921}
7922
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007923/// \brief Look for '&&' in the left hand of a '||' expr.
7924static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007925 Expr *OrLHS, Expr *OrRHS) {
7926 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007927 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007928 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7929 if (EvaluatesAsFalse(S, OrRHS))
7930 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007931 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7932 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7933 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7934 } else if (Bop->getOpcode() == BO_LOr) {
7935 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7936 // If it's "a || b && 1 || c" we didn't warn earlier for
7937 // "a || b && 1", but warn now.
7938 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7939 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7940 }
7941 }
7942 }
7943}
7944
7945/// \brief Look for '&&' in the right hand of a '||' expr.
7946static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007947 Expr *OrLHS, Expr *OrRHS) {
7948 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007949 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007950 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7951 if (EvaluatesAsFalse(S, OrLHS))
7952 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007953 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7954 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7955 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007956 }
7957 }
7958}
7959
Sebastian Redl43028242009-10-26 15:24:15 +00007960/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007961/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007962static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007963 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007964 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007965 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007966 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7967
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007968 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7969 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007970 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007971 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7972 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007973 }
Sebastian Redl43028242009-10-26 15:24:15 +00007974}
7975
Steve Naroff218bc2b2007-05-04 21:54:46 +00007976// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007977ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00007978 tok::TokenKind Kind,
7979 Expr *lhs, Expr *rhs) {
7980 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00007981 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7982 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00007983
Sebastian Redl43028242009-10-26 15:24:15 +00007984 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7985 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7986
Douglas Gregor5287f092009-11-05 00:51:44 +00007987 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7988}
7989
John McCalldadc5752010-08-24 06:29:42 +00007990ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007991 BinaryOperatorKind Opc,
7992 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00007993 if (getLangOptions().CPlusPlus) {
7994 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007995
John McCall622114c2010-12-06 05:26:58 +00007996 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7997 UseBuiltinOperator = false;
7998 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7999 UseBuiltinOperator = true;
8000 } else {
8001 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8002 !rhs->getType()->isOverloadableType();
8003 }
8004
8005 if (!UseBuiltinOperator) {
8006 // 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.
8010 UnresolvedSet<16> Functions;
8011 OverloadedOperatorKind OverOp
8012 = BinaryOperator::getOverloadedOperator(Opc);
8013 if (S && OverOp != OO_None)
8014 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8015 Functions);
8016
8017 // Build the (potentially-overloaded, potentially-dependent)
8018 // binary operation.
8019 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8020 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008021 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008022
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008023 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00008024 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008025}
8026
John McCalldadc5752010-08-24 06:29:42 +00008027ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008028 UnaryOperatorKind Opc,
John McCall36226622010-10-12 02:09:17 +00008029 Expr *Input) {
John McCall7decc9e2010-11-18 06:31:45 +00008030 ExprValueKind VK = VK_RValue;
8031 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008032 QualType resultType;
8033 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008034 case UO_PreInc:
8035 case UO_PreDec:
8036 case UO_PostInc:
8037 case UO_PostDec:
John McCall4bc41ae2010-11-18 19:01:18 +00008038 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008039 Opc == UO_PreInc ||
8040 Opc == UO_PostInc,
8041 Opc == UO_PreInc ||
8042 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008043 break;
John McCalle3027922010-08-25 11:45:40 +00008044 case UO_AddrOf:
John McCall4bc41ae2010-11-18 19:01:18 +00008045 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008046 break;
John McCalle3027922010-08-25 11:45:40 +00008047 case UO_Deref:
Douglas Gregorb92a1562010-02-03 00:27:59 +00008048 DefaultFunctionArrayLvalueConversion(Input);
John McCall4bc41ae2010-11-18 19:01:18 +00008049 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008050 break;
John McCalle3027922010-08-25 11:45:40 +00008051 case UO_Plus:
8052 case UO_Minus:
Steve Naroff31090012007-07-16 21:54:35 +00008053 UsualUnaryConversions(Input);
8054 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008055 if (resultType->isDependentType())
8056 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008057 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8058 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008059 break;
8060 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8061 resultType->isEnumeralType())
8062 break;
8063 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008064 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008065 resultType->isPointerType())
8066 break;
John McCall36226622010-10-12 02:09:17 +00008067 else if (resultType->isPlaceholderType()) {
8068 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8069 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008070 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008071 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008072
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008073 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8074 << resultType << Input->getSourceRange());
John McCalle3027922010-08-25 11:45:40 +00008075 case UO_Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00008076 UsualUnaryConversions(Input);
8077 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008078 if (resultType->isDependentType())
8079 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008080 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8081 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8082 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008083 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008084 << resultType << Input->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008085 else if (resultType->hasIntegerRepresentation())
8086 break;
8087 else if (resultType->isPlaceholderType()) {
8088 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8089 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008090 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008091 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008092 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8093 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008094 }
Steve Naroff35d85152007-05-07 00:24:15 +00008095 break;
John McCalle3027922010-08-25 11:45:40 +00008096 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008097 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00008098 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00008099 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008100 if (resultType->isDependentType())
8101 break;
John McCall36226622010-10-12 02:09:17 +00008102 if (resultType->isScalarType()) { // C99 6.5.3.3p1
8103 // ok, fallthrough
8104 } else if (resultType->isPlaceholderType()) {
8105 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8106 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008107 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008108 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008109 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8110 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008111 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008112
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008113 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008114 // In C++, it's bool. C++ 5.3.1p8
8115 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00008116 break;
John McCalle3027922010-08-25 11:45:40 +00008117 case UO_Real:
8118 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008119 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008120 // _Real and _Imag map ordinary l-values into ordinary l-values.
8121 if (Input->getValueKind() != VK_RValue &&
8122 Input->getObjectKind() == OK_Ordinary)
8123 VK = Input->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008124 break;
John McCalle3027922010-08-25 11:45:40 +00008125 case UO_Extension:
Chris Lattner86554282007-06-08 22:32:33 +00008126 resultType = Input->getType();
John McCall7decc9e2010-11-18 06:31:45 +00008127 VK = Input->getValueKind();
8128 OK = Input->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008129 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008130 }
8131 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008132 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008133
John McCall7decc9e2010-11-18 06:31:45 +00008134 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
8135 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008136}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008137
John McCalldadc5752010-08-24 06:29:42 +00008138ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008139 UnaryOperatorKind Opc,
8140 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008141 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008142 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008143 // Find all of the overloaded operators visible from this
8144 // point. We perform both an operator-name lookup from the local
8145 // scope and an argument-dependent lookup based on the types of
8146 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008147 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008148 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008149 if (S && OverOp != OO_None)
8150 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8151 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008152
John McCallb268a282010-08-23 23:25:46 +00008153 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008154 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008155
John McCallb268a282010-08-23 23:25:46 +00008156 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008157}
8158
Douglas Gregor5287f092009-11-05 00:51:44 +00008159// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008160ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008161 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008162 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008163}
8164
Steve Naroff66356bd2007-09-16 14:56:35 +00008165/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
John McCalldadc5752010-08-24 06:29:42 +00008166ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008167 SourceLocation LabLoc,
8168 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00008169 // Look up the record for this label identifier.
John McCallaab3e412010-08-25 08:40:02 +00008170 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00008171
Daniel Dunbar88402ce2008-08-04 16:51:22 +00008172 // If we haven't seen this label yet, create a forward reference. It
8173 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00008174 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00008175 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008176
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00008177 LabelDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008178 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008179 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
8180 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008181}
8182
John McCalldadc5752010-08-24 06:29:42 +00008183ExprResult
John McCallb268a282010-08-23 23:25:46 +00008184Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008185 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008186 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8187 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8188
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008189 bool isFileScope
8190 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008191 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008192 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008193
Chris Lattner366727f2007-07-24 16:58:17 +00008194 // FIXME: there are a variety of strange constraints to enforce here, for
8195 // example, it is not possible to goto into a stmt expression apparently.
8196 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008197
Chris Lattner366727f2007-07-24 16:58:17 +00008198 // If there are sub stmts in the compound stmt, take the type of the last one
8199 // as the type of the stmtexpr.
8200 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008201 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008202 if (!Compound->body_empty()) {
8203 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008204 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008205 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008206 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8207 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008208 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008209 }
8210 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008211 // Do function/array conversion on the last expression, but not
8212 // lvalue-to-rvalue. However, initialize an unqualified type.
8213 DefaultFunctionArrayConversion(LastExpr);
8214 Ty = LastExpr->getType().getUnqualifiedType();
8215
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008216 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8217 ExprResult Res = PerformCopyInitialization(
8218 InitializedEntity::InitializeResult(LPLoc,
8219 Ty,
8220 false),
8221 SourceLocation(),
8222 Owned(LastExpr));
8223 if (Res.isInvalid())
8224 return ExprError();
8225 if ((LastExpr = Res.takeAs<Expr>())) {
8226 if (!LastLabelStmt)
8227 Compound->setLastStmt(LastExpr);
8228 else
8229 LastLabelStmt->setSubStmt(LastExpr);
8230 StmtExprMayBindToTemp = true;
8231 }
8232 }
8233 }
Chris Lattner944d3062008-07-26 19:51:01 +00008234 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008235
Eli Friedmanba961a92009-03-23 00:24:07 +00008236 // FIXME: Check that expression type is complete/non-abstract; statement
8237 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008238 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8239 if (StmtExprMayBindToTemp)
8240 return MaybeBindToTemporary(ResStmtExpr);
8241 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008242}
Steve Naroff78864672007-08-01 22:05:33 +00008243
John McCalldadc5752010-08-24 06:29:42 +00008244ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008245 TypeSourceInfo *TInfo,
8246 OffsetOfComponent *CompPtr,
8247 unsigned NumComponents,
8248 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008249 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008250 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008251 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008252
Chris Lattnerf17bd422007-08-30 17:45:32 +00008253 // We must have at least one component that refers to the type, and the first
8254 // one is known to be a field designator. Verify that the ArgTy represents
8255 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008256 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008257 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8258 << ArgTy << TypeRange);
8259
8260 // Type must be complete per C99 7.17p3 because a declaring a variable
8261 // with an incomplete type would be ill-formed.
8262 if (!Dependent
8263 && RequireCompleteType(BuiltinLoc, ArgTy,
8264 PDiag(diag::err_offsetof_incomplete_type)
8265 << TypeRange))
8266 return ExprError();
8267
Chris Lattner78502cf2007-08-31 21:49:13 +00008268 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8269 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008270 // FIXME: This diagnostic isn't actually visible because the location is in
8271 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008272 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008273 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8274 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008275
8276 bool DidWarnAboutNonPOD = false;
8277 QualType CurrentType = ArgTy;
8278 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8279 llvm::SmallVector<OffsetOfNode, 4> Comps;
8280 llvm::SmallVector<Expr*, 4> Exprs;
8281 for (unsigned i = 0; i != NumComponents; ++i) {
8282 const OffsetOfComponent &OC = CompPtr[i];
8283 if (OC.isBrackets) {
8284 // Offset of an array sub-field. TODO: Should we allow vector elements?
8285 if (!CurrentType->isDependentType()) {
8286 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8287 if(!AT)
8288 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8289 << CurrentType);
8290 CurrentType = AT->getElementType();
8291 } else
8292 CurrentType = Context.DependentTy;
8293
8294 // The expression must be an integral expression.
8295 // FIXME: An integral constant expression?
8296 Expr *Idx = static_cast<Expr*>(OC.U.E);
8297 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8298 !Idx->getType()->isIntegerType())
8299 return ExprError(Diag(Idx->getLocStart(),
8300 diag::err_typecheck_subscript_not_integer)
8301 << Idx->getSourceRange());
8302
8303 // Record this array index.
8304 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8305 Exprs.push_back(Idx);
8306 continue;
8307 }
8308
8309 // Offset of a field.
8310 if (CurrentType->isDependentType()) {
8311 // We have the offset of a field, but we can't look into the dependent
8312 // type. Just record the identifier of the field.
8313 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8314 CurrentType = Context.DependentTy;
8315 continue;
8316 }
8317
8318 // We need to have a complete type to look into.
8319 if (RequireCompleteType(OC.LocStart, CurrentType,
8320 diag::err_offsetof_incomplete_type))
8321 return ExprError();
8322
8323 // Look for the designated field.
8324 const RecordType *RC = CurrentType->getAs<RecordType>();
8325 if (!RC)
8326 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8327 << CurrentType);
8328 RecordDecl *RD = RC->getDecl();
8329
8330 // C++ [lib.support.types]p5:
8331 // The macro offsetof accepts a restricted set of type arguments in this
8332 // International Standard. type shall be a POD structure or a POD union
8333 // (clause 9).
8334 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8335 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8336 DiagRuntimeBehavior(BuiltinLoc,
8337 PDiag(diag::warn_offsetof_non_pod_type)
8338 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8339 << CurrentType))
8340 DidWarnAboutNonPOD = true;
8341 }
8342
8343 // Look for the field.
8344 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8345 LookupQualifiedName(R, RD);
8346 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008347 IndirectFieldDecl *IndirectMemberDecl = 0;
8348 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008349 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008350 MemberDecl = IndirectMemberDecl->getAnonField();
8351 }
8352
Douglas Gregor882211c2010-04-28 22:16:22 +00008353 if (!MemberDecl)
8354 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8355 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8356 OC.LocEnd));
8357
Douglas Gregor10982ea2010-04-28 22:36:06 +00008358 // C99 7.17p3:
8359 // (If the specified member is a bit-field, the behavior is undefined.)
8360 //
8361 // We diagnose this as an error.
8362 if (MemberDecl->getBitWidth()) {
8363 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8364 << MemberDecl->getDeclName()
8365 << SourceRange(BuiltinLoc, RParenLoc);
8366 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8367 return ExprError();
8368 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008369
8370 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008371 if (IndirectMemberDecl)
8372 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008373
Douglas Gregord1702062010-04-29 00:18:15 +00008374 // If the member was found in a base class, introduce OffsetOfNodes for
8375 // the base class indirections.
8376 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8377 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008378 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008379 CXXBasePath &Path = Paths.front();
8380 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8381 B != BEnd; ++B)
8382 Comps.push_back(OffsetOfNode(B->Base));
8383 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008384
Francois Pichet783dd6e2010-11-21 06:08:52 +00008385 if (IndirectMemberDecl) {
8386 for (IndirectFieldDecl::chain_iterator FI =
8387 IndirectMemberDecl->chain_begin(),
8388 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8389 assert(isa<FieldDecl>(*FI));
8390 Comps.push_back(OffsetOfNode(OC.LocStart,
8391 cast<FieldDecl>(*FI), OC.LocEnd));
8392 }
8393 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008394 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008395
Douglas Gregor882211c2010-04-28 22:16:22 +00008396 CurrentType = MemberDecl->getType().getNonReferenceType();
8397 }
8398
8399 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8400 TInfo, Comps.data(), Comps.size(),
8401 Exprs.data(), Exprs.size(), RParenLoc));
8402}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008403
John McCalldadc5752010-08-24 06:29:42 +00008404ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008405 SourceLocation BuiltinLoc,
8406 SourceLocation TypeLoc,
8407 ParsedType argty,
8408 OffsetOfComponent *CompPtr,
8409 unsigned NumComponents,
8410 SourceLocation RPLoc) {
8411
Douglas Gregor882211c2010-04-28 22:16:22 +00008412 TypeSourceInfo *ArgTInfo;
8413 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8414 if (ArgTy.isNull())
8415 return ExprError();
8416
Eli Friedman06dcfd92010-08-05 10:15:45 +00008417 if (!ArgTInfo)
8418 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8419
8420 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8421 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008422}
8423
8424
John McCalldadc5752010-08-24 06:29:42 +00008425ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008426 Expr *CondExpr,
8427 Expr *LHSExpr, Expr *RHSExpr,
8428 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008429 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8430
John McCall7decc9e2010-11-18 06:31:45 +00008431 ExprValueKind VK = VK_RValue;
8432 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008433 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008434 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008435 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008436 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008437 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008438 } else {
8439 // The conditional expression is required to be a constant expression.
8440 llvm::APSInt condEval(32);
8441 SourceLocation ExpLoc;
8442 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008443 return ExprError(Diag(ExpLoc,
8444 diag::err_typecheck_choose_expr_requires_constant)
8445 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008446
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008447 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008448 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8449
8450 resType = ActiveExpr->getType();
8451 ValueDependent = ActiveExpr->isValueDependent();
8452 VK = ActiveExpr->getValueKind();
8453 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008454 }
8455
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008456 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008457 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008458 resType->isDependentType(),
8459 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008460}
8461
Steve Naroffc540d662008-09-03 18:15:37 +00008462//===----------------------------------------------------------------------===//
8463// Clang Extensions.
8464//===----------------------------------------------------------------------===//
8465
8466/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008467void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008468 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8469 PushBlockScope(BlockScope, Block);
8470 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008471 if (BlockScope)
8472 PushDeclContext(BlockScope, Block);
8473 else
8474 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008475}
8476
Mike Stump82f071f2009-02-04 22:31:32 +00008477void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008478 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008479 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008480 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008481
John McCall8cb7bdf2010-06-04 23:28:52 +00008482 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008483 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008484
John McCall3882ace2011-01-05 12:14:39 +00008485 // GetTypeForDeclarator always produces a function type for a block
8486 // literal signature. Furthermore, it is always a FunctionProtoType
8487 // unless the function was written with a typedef.
8488 assert(T->isFunctionType() &&
8489 "GetTypeForDeclarator made a non-function block signature");
8490
8491 // Look for an explicit signature in that function type.
8492 FunctionProtoTypeLoc ExplicitSignature;
8493
8494 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8495 if (isa<FunctionProtoTypeLoc>(tmp)) {
8496 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8497
8498 // Check whether that explicit signature was synthesized by
8499 // GetTypeForDeclarator. If so, don't save that as part of the
8500 // written signature.
8501 if (ExplicitSignature.getLParenLoc() ==
8502 ExplicitSignature.getRParenLoc()) {
8503 // This would be much cheaper if we stored TypeLocs instead of
8504 // TypeSourceInfos.
8505 TypeLoc Result = ExplicitSignature.getResultLoc();
8506 unsigned Size = Result.getFullDataSize();
8507 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8508 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8509
8510 ExplicitSignature = FunctionProtoTypeLoc();
8511 }
John McCalla3ccba02010-06-04 11:21:44 +00008512 }
Mike Stump11289f42009-09-09 15:08:12 +00008513
John McCall3882ace2011-01-05 12:14:39 +00008514 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8515 CurBlock->FunctionType = T;
8516
8517 const FunctionType *Fn = T->getAs<FunctionType>();
8518 QualType RetTy = Fn->getResultType();
8519 bool isVariadic =
8520 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8521
John McCall8e346702010-06-04 19:02:56 +00008522 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008523
John McCalla3ccba02010-06-04 11:21:44 +00008524 // Don't allow returning a objc interface by value.
8525 if (RetTy->isObjCObjectType()) {
8526 Diag(ParamInfo.getSourceRange().getBegin(),
8527 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8528 return;
8529 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008530
John McCalla3ccba02010-06-04 11:21:44 +00008531 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008532 // return type. TODO: what should we do with declarators like:
8533 // ^ * { ... }
8534 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008535 if (RetTy != Context.DependentTy)
8536 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008537
John McCalla3ccba02010-06-04 11:21:44 +00008538 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00008539 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008540 if (ExplicitSignature) {
8541 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8542 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008543 if (Param->getIdentifier() == 0 &&
8544 !Param->isImplicit() &&
8545 !Param->isInvalidDecl() &&
8546 !getLangOptions().CPlusPlus)
8547 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008548 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008549 }
John McCalla3ccba02010-06-04 11:21:44 +00008550
8551 // Fake up parameter variables if we have a typedef, like
8552 // ^ fntype { ... }
8553 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8554 for (FunctionProtoType::arg_type_iterator
8555 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8556 ParmVarDecl *Param =
8557 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8558 ParamInfo.getSourceRange().getBegin(),
8559 *I);
John McCall8e346702010-06-04 19:02:56 +00008560 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008561 }
Steve Naroffc540d662008-09-03 18:15:37 +00008562 }
John McCalla3ccba02010-06-04 11:21:44 +00008563
John McCall8e346702010-06-04 19:02:56 +00008564 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008565 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008566 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008567 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8568 CurBlock->TheDecl->param_end(),
8569 /*CheckParameterNames=*/false);
8570 }
8571
John McCalla3ccba02010-06-04 11:21:44 +00008572 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008573 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008574
John McCall8e346702010-06-04 19:02:56 +00008575 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008576 Diag(ParamInfo.getAttributes()->getLoc(),
8577 diag::warn_attribute_sentinel_not_variadic) << 1;
8578 // FIXME: remove the attribute.
8579 }
8580
8581 // Put the parameter variables in scope. We can bail out immediately
8582 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008583 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008584 return;
8585
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008586 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008587 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8588 (*AI)->setOwningFunction(CurBlock->TheDecl);
8589
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008590 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008591 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008592 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008593
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008594 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008595 }
John McCallf7b2fb52010-01-22 00:28:27 +00008596 }
Steve Naroffc540d662008-09-03 18:15:37 +00008597}
8598
8599/// ActOnBlockError - If there is an error parsing a block, this callback
8600/// is invoked to pop the information about the block from the action impl.
8601void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008602 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008603 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008604 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008605}
8606
8607/// ActOnBlockStmtExpr - This is called when the body of a block statement
8608/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008609ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
John McCallb268a282010-08-23 23:25:46 +00008610 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008611 // If blocks are disabled, emit an error.
8612 if (!LangOpts.Blocks)
8613 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008614
Douglas Gregor9a28e842010-03-01 23:15:13 +00008615 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008616
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008617 PopDeclContext();
8618
Steve Naroffc540d662008-09-03 18:15:37 +00008619 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008620 if (!BSI->ReturnType.isNull())
8621 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008622
Mike Stump3bf1ab42009-07-28 22:04:01 +00008623 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008624 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008625
John McCallc63de662011-02-02 13:00:07 +00008626 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008627 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8628 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008629
John McCall8e346702010-06-04 19:02:56 +00008630 // If the user wrote a function type in some form, try to use that.
8631 if (!BSI->FunctionType.isNull()) {
8632 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8633
8634 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8635 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8636
8637 // Turn protoless block types into nullary block types.
8638 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008639 FunctionProtoType::ExtProtoInfo EPI;
8640 EPI.ExtInfo = Ext;
8641 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008642
8643 // Otherwise, if we don't need to change anything about the function type,
8644 // preserve its sugar structure.
8645 } else if (FTy->getResultType() == RetTy &&
8646 (!NoReturn || FTy->getNoReturnAttr())) {
8647 BlockTy = BSI->FunctionType;
8648
8649 // Otherwise, make the minimal modifications to the function type.
8650 } else {
8651 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008652 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8653 EPI.TypeQuals = 0; // FIXME: silently?
8654 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008655 BlockTy = Context.getFunctionType(RetTy,
8656 FPT->arg_type_begin(),
8657 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008658 EPI);
John McCall8e346702010-06-04 19:02:56 +00008659 }
8660
8661 // If we don't have a function type, just build one from nothing.
8662 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008663 FunctionProtoType::ExtProtoInfo EPI;
8664 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
8665 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008666 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008667
John McCall8e346702010-06-04 19:02:56 +00008668 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8669 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008670 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008671
Chris Lattner45542ea2009-04-19 05:28:12 +00008672 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00008673 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008674 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008675
John McCallb268a282010-08-23 23:25:46 +00008676 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Mike Stump314825b2010-01-19 23:08:01 +00008677
8678 bool Good = true;
8679 // Check goto/label use.
8680 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
8681 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
8682 LabelStmt *L = I->second;
8683
8684 // Verify that we have no forward references left. If so, there was a goto
8685 // or address of a label taken, but no definition of it.
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00008686 if (L->getSubStmt() != 0) {
8687 if (!L->isUsed())
8688 Diag(L->getIdentLoc(), diag::warn_unused_label) << L->getName();
Mike Stump314825b2010-01-19 23:08:01 +00008689 continue;
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00008690 }
Mike Stump314825b2010-01-19 23:08:01 +00008691
8692 // Emit error.
8693 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
8694 Good = false;
8695 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00008696 if (!Good) {
8697 PopFunctionOrBlockScope();
Mike Stump314825b2010-01-19 23:08:01 +00008698 return ExprError();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008699 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008700
John McCallc63de662011-02-02 13:00:07 +00008701 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCall1d570a72010-08-25 05:56:39 +00008702
Ted Kremenek918fe842010-03-20 21:06:02 +00008703 // Issue any analysis-based warnings.
Ted Kremenek0b405322010-03-23 00:13:23 +00008704 const sema::AnalysisBasedWarnings::Policy &WP =
8705 AnalysisWarnings.getDefaultPolicy();
John McCall1d570a72010-08-25 05:56:39 +00008706 AnalysisWarnings.IssueWarnings(WP, Result);
Ted Kremenek918fe842010-03-20 21:06:02 +00008707
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008708 PopFunctionOrBlockScope();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008709 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008710}
8711
John McCalldadc5752010-08-24 06:29:42 +00008712ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008713 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008714 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008715 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008716 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008717 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008718}
8719
John McCalldadc5752010-08-24 06:29:42 +00008720ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008721 Expr *E, TypeSourceInfo *TInfo,
8722 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008723 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008724
Eli Friedman121ba0c2008-08-09 23:32:40 +00008725 // Get the va_list type
8726 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008727 if (VaListType->isArrayType()) {
8728 // Deal with implicit array decay; for example, on x86-64,
8729 // va_list is an array, but it's supposed to decay to
8730 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008731 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008732 // Make sure the input expression also decays appropriately.
8733 UsualUnaryConversions(E);
8734 } else {
8735 // Otherwise, the va_list argument must be an l-value because
8736 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008737 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008738 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008739 return ExprError();
8740 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008741
Douglas Gregorad3150c2009-05-19 23:10:31 +00008742 if (!E->isTypeDependent() &&
8743 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008744 return ExprError(Diag(E->getLocStart(),
8745 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008746 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008747 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008748
Eli Friedmanba961a92009-03-23 00:24:07 +00008749 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008750 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008751
Abramo Bagnara27db2392010-08-10 10:06:15 +00008752 QualType T = TInfo->getType().getNonLValueExprType(Context);
8753 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008754}
8755
John McCalldadc5752010-08-24 06:29:42 +00008756ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008757 // The type of __null will be int or long, depending on the size of
8758 // pointers on the target.
8759 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008760 unsigned pw = Context.Target.getPointerWidth(0);
8761 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008762 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008763 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008764 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008765 else if (pw == Context.Target.getLongLongWidth())
8766 Ty = Context.LongLongTy;
8767 else {
8768 assert(!"I don't know size of pointer!");
8769 Ty = Context.IntTy;
8770 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008771
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008772 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008773}
8774
Alexis Huntc46382e2010-04-28 23:02:27 +00008775static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008776 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008777 if (!SemaRef.getLangOptions().ObjC1)
8778 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008779
Anders Carlssonace5d072009-11-10 04:46:30 +00008780 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8781 if (!PT)
8782 return;
8783
8784 // Check if the destination is of type 'id'.
8785 if (!PT->isObjCIdType()) {
8786 // Check if the destination is the 'NSString' interface.
8787 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8788 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8789 return;
8790 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008791
Anders Carlssonace5d072009-11-10 04:46:30 +00008792 // Strip off any parens and casts.
8793 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8794 if (!SL || SL->isWide())
8795 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008796
Douglas Gregora771f462010-03-31 17:46:05 +00008797 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008798}
8799
Chris Lattner9bad62c2008-01-04 18:04:52 +00008800bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8801 SourceLocation Loc,
8802 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008803 Expr *SrcExpr, AssignmentAction Action,
8804 bool *Complained) {
8805 if (Complained)
8806 *Complained = false;
8807
Chris Lattner9bad62c2008-01-04 18:04:52 +00008808 // Decode the result (notice that AST's are still created for extensions).
8809 bool isInvalid = false;
8810 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008811 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008812
Chris Lattner9bad62c2008-01-04 18:04:52 +00008813 switch (ConvTy) {
8814 default: assert(0 && "Unknown conversion type");
8815 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008816 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008817 DiagKind = diag::ext_typecheck_convert_pointer_int;
8818 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008819 case IntToPointer:
8820 DiagKind = diag::ext_typecheck_convert_int_pointer;
8821 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008822 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008823 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008824 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
8825 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008826 case IncompatiblePointerSign:
8827 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8828 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008829 case FunctionVoidPointer:
8830 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8831 break;
John McCall4fff8f62011-02-01 00:10:29 +00008832 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00008833 // Perform array-to-pointer decay if necessary.
8834 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8835
John McCall4fff8f62011-02-01 00:10:29 +00008836 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8837 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8838 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8839 DiagKind = diag::err_typecheck_incompatible_address_space;
8840 break;
8841 }
8842
8843 llvm_unreachable("unknown error case for discarding qualifiers!");
8844 // fallthrough
8845 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008846 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008847 // If the qualifiers lost were because we were applying the
8848 // (deprecated) C++ conversion from a string literal to a char*
8849 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8850 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00008851 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008852 // bit of refactoring (so that the second argument is an
8853 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00008854 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008855 // C++ semantics.
8856 if (getLangOptions().CPlusPlus &&
8857 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8858 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008859 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8860 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008861 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008862 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008863 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008864 case IntToBlockPointer:
8865 DiagKind = diag::err_int_to_block_pointer;
8866 break;
8867 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008868 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008869 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008870 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008871 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008872 // it can give a more specific diagnostic.
8873 DiagKind = diag::warn_incompatible_qualified_id;
8874 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008875 case IncompatibleVectors:
8876 DiagKind = diag::warn_incompatible_vectors;
8877 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008878 case Incompatible:
8879 DiagKind = diag::err_typecheck_convert_incompatible;
8880 isInvalid = true;
8881 break;
8882 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008883
Douglas Gregorc68e1402010-04-09 00:35:39 +00008884 QualType FirstType, SecondType;
8885 switch (Action) {
8886 case AA_Assigning:
8887 case AA_Initializing:
8888 // The destination type comes first.
8889 FirstType = DstType;
8890 SecondType = SrcType;
8891 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00008892
Douglas Gregorc68e1402010-04-09 00:35:39 +00008893 case AA_Returning:
8894 case AA_Passing:
8895 case AA_Converting:
8896 case AA_Sending:
8897 case AA_Casting:
8898 // The source type comes first.
8899 FirstType = SrcType;
8900 SecondType = DstType;
8901 break;
8902 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008903
Douglas Gregorc68e1402010-04-09 00:35:39 +00008904 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00008905 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008906 if (Complained)
8907 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008908 return isInvalid;
8909}
Anders Carlssone54e8a12008-11-30 19:50:32 +00008910
Chris Lattnerc71d08b2009-04-25 21:59:05 +00008911bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008912 llvm::APSInt ICEResult;
8913 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8914 if (Result)
8915 *Result = ICEResult;
8916 return false;
8917 }
8918
Anders Carlssone54e8a12008-11-30 19:50:32 +00008919 Expr::EvalResult EvalResult;
8920
Mike Stump4e1f26a2009-02-19 03:04:26 +00008921 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00008922 EvalResult.HasSideEffects) {
8923 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8924
8925 if (EvalResult.Diag) {
8926 // We only show the note if it's not the usual "invalid subexpression"
8927 // or if it's actually in a subexpression.
8928 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8929 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8930 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8931 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008932
Anders Carlssone54e8a12008-11-30 19:50:32 +00008933 return true;
8934 }
8935
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008936 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8937 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00008938
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008939 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008940 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
8941 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008942 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008943
Anders Carlssone54e8a12008-11-30 19:50:32 +00008944 if (Result)
8945 *Result = EvalResult.Val.getInt();
8946 return false;
8947}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008948
Douglas Gregorff790f12009-11-26 00:44:06 +00008949void
Mike Stump11289f42009-09-09 15:08:12 +00008950Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008951 ExprEvalContexts.push_back(
8952 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008953}
8954
Mike Stump11289f42009-09-09 15:08:12 +00008955void
Douglas Gregorff790f12009-11-26 00:44:06 +00008956Sema::PopExpressionEvaluationContext() {
8957 // Pop the current expression evaluation context off the stack.
8958 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8959 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008960
Douglas Gregorfab31f42009-12-12 07:57:52 +00008961 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8962 if (Rec.PotentiallyReferenced) {
8963 // Mark any remaining declarations in the current position of the stack
8964 // as "referenced". If they were not meant to be referenced, semantic
8965 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008966 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00008967 I = Rec.PotentiallyReferenced->begin(),
8968 IEnd = Rec.PotentiallyReferenced->end();
8969 I != IEnd; ++I)
8970 MarkDeclarationReferenced(I->first, I->second);
8971 }
8972
8973 if (Rec.PotentiallyDiagnosed) {
8974 // Emit any pending diagnostics.
8975 for (PotentiallyEmittedDiagnostics::iterator
8976 I = Rec.PotentiallyDiagnosed->begin(),
8977 IEnd = Rec.PotentiallyDiagnosed->end();
8978 I != IEnd; ++I)
8979 Diag(I->first, I->second);
8980 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008981 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008982
8983 // When are coming out of an unevaluated context, clear out any
8984 // temporaries that we may have created as part of the evaluation of
8985 // the expression in that context: they aren't relevant because they
8986 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008987 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00008988 ExprTemporaries.size() > Rec.NumTemporaries)
8989 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
8990 ExprTemporaries.end());
8991
8992 // Destroy the popped expression evaluation record.
8993 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008994}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008995
8996/// \brief Note that the given declaration was referenced in the source code.
8997///
8998/// This routine should be invoke whenever a given declaration is referenced
8999/// in the source code, and where that reference occurred. If this declaration
9000/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9001/// C99 6.9p3), then the declaration will be marked as used.
9002///
9003/// \param Loc the location where the declaration was referenced.
9004///
9005/// \param D the declaration that has been referenced by the source code.
9006void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9007 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009008
Douglas Gregorebada0772010-06-17 23:14:26 +00009009 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009010 return;
Mike Stump11289f42009-09-09 15:08:12 +00009011
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00009012 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9013 // template or not. The reason for this is that unevaluated expressions
9014 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9015 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009016 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009017 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009018 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009019 return;
9020 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009021
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009022 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9023 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009024
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009025 // Do not mark anything as "used" within a dependent context; wait for
9026 // an instantiation.
9027 if (CurContext->isDependentContext())
9028 return;
Mike Stump11289f42009-09-09 15:08:12 +00009029
Douglas Gregorff790f12009-11-26 00:44:06 +00009030 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009031 case Unevaluated:
9032 // We are in an expression that is not potentially evaluated; do nothing.
9033 return;
Mike Stump11289f42009-09-09 15:08:12 +00009034
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009035 case PotentiallyEvaluated:
9036 // We are in a potentially-evaluated expression, so this declaration is
9037 // "used"; handle this below.
9038 break;
Mike Stump11289f42009-09-09 15:08:12 +00009039
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009040 case PotentiallyPotentiallyEvaluated:
9041 // We are in an expression that may be potentially evaluated; queue this
9042 // declaration reference until we know whether the expression is
9043 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009044 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009045 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009046
9047 case PotentiallyEvaluatedIfUsed:
9048 // Referenced declarations will only be used if the construct in the
9049 // containing expression is used.
9050 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009051 }
Mike Stump11289f42009-09-09 15:08:12 +00009052
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009053 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009054 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009055 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00009056 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00009057 if (Constructor->getParent()->hasTrivialConstructor())
9058 return;
9059 if (!Constructor->isUsed(false))
9060 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00009061 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00009062 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009063 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009064 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9065 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009066
Douglas Gregor88d292c2010-05-13 16:44:06 +00009067 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009068 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009069 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009070 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009071 if (Destructor->isVirtual())
9072 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009073 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9074 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9075 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009076 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009077 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009078 } else if (MethodDecl->isVirtual())
9079 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009080 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009081 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00009082 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009083 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009084 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009085 bool AlreadyInstantiated = false;
9086 if (FunctionTemplateSpecializationInfo *SpecInfo
9087 = Function->getTemplateSpecializationInfo()) {
9088 if (SpecInfo->getPointOfInstantiation().isInvalid())
9089 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009090 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009091 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009092 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009093 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009094 = Function->getMemberSpecializationInfo()) {
9095 if (MSInfo->getPointOfInstantiation().isInvalid())
9096 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009097 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009098 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009099 AlreadyInstantiated = true;
9100 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009101
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009102 if (!AlreadyInstantiated) {
9103 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9104 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9105 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9106 Loc));
9107 else
Chandler Carruth54080172010-08-25 08:44:16 +00009108 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009109 }
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009110 } else // Walk redefinitions, as some of them may be instantiable.
9111 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9112 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009113 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009114 MarkDeclarationReferenced(Loc, *i);
9115 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009116
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009117 // FIXME: keep track of references to static functions
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009118
9119 // Recursive functions should be marked when used from another function.
9120 if (CurContext != Function)
9121 Function->setUsed(true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009122
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009123 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009124 }
Mike Stump11289f42009-09-09 15:08:12 +00009125
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009126 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009127 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009128 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009129 Var->getInstantiatedFromStaticDataMember()) {
9130 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9131 assert(MSInfo && "Missing member specialization information?");
9132 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9133 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9134 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +00009135 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009136 }
9137 }
Mike Stump11289f42009-09-09 15:08:12 +00009138
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009139 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009140
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009141 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009142 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009143 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009144}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009145
Douglas Gregor5597ab42010-05-07 23:12:07 +00009146namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009147 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009148 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009149 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009150 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9151 Sema &S;
9152 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009153
Douglas Gregor5597ab42010-05-07 23:12:07 +00009154 public:
9155 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009156
Douglas Gregor5597ab42010-05-07 23:12:07 +00009157 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009158
9159 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9160 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009161 };
9162}
9163
Chandler Carruthaf80f662010-06-09 08:17:30 +00009164bool MarkReferencedDecls::TraverseTemplateArgument(
9165 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009166 if (Arg.getKind() == TemplateArgument::Declaration) {
9167 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9168 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009169
9170 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009171}
9172
Chandler Carruthaf80f662010-06-09 08:17:30 +00009173bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009174 if (ClassTemplateSpecializationDecl *Spec
9175 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9176 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009177 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009178 }
9179
Chandler Carruthc65667c2010-06-10 10:31:57 +00009180 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009181}
9182
9183void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9184 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009185 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009186}
9187
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009188namespace {
9189 /// \brief Helper class that marks all of the declarations referenced by
9190 /// potentially-evaluated subexpressions as "referenced".
9191 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9192 Sema &S;
9193
9194 public:
9195 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9196
9197 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9198
9199 void VisitDeclRefExpr(DeclRefExpr *E) {
9200 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9201 }
9202
9203 void VisitMemberExpr(MemberExpr *E) {
9204 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009205 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009206 }
9207
9208 void VisitCXXNewExpr(CXXNewExpr *E) {
9209 if (E->getConstructor())
9210 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9211 if (E->getOperatorNew())
9212 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9213 if (E->getOperatorDelete())
9214 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009215 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009216 }
9217
9218 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9219 if (E->getOperatorDelete())
9220 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009221 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9222 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9223 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9224 S.MarkDeclarationReferenced(E->getLocStart(),
9225 S.LookupDestructor(Record));
9226 }
9227
Douglas Gregor32b3de52010-09-11 23:32:50 +00009228 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009229 }
9230
9231 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9232 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009233 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009234 }
9235
9236 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9237 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9238 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009239
9240 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9241 Visit(E->getExpr());
9242 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009243 };
9244}
9245
9246/// \brief Mark any declarations that appear within this expression or any
9247/// potentially-evaluated subexpressions as "referenced".
9248void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9249 EvaluatedExprMarker(*this).Visit(E);
9250}
9251
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009252/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9253/// of the program being compiled.
9254///
9255/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009256/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009257/// possibility that the code will actually be executable. Code in sizeof()
9258/// expressions, code used only during overload resolution, etc., are not
9259/// potentially evaluated. This routine will suppress such diagnostics or,
9260/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009261/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009262/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009263///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009264/// This routine should be used for all diagnostics that describe the run-time
9265/// behavior of a program, such as passing a non-POD value through an ellipsis.
9266/// Failure to do so will likely result in spurious diagnostics or failures
9267/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009268bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009269 const PartialDiagnostic &PD) {
9270 switch (ExprEvalContexts.back().Context ) {
9271 case Unevaluated:
9272 // The argument will never be evaluated, so don't complain.
9273 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009274
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009275 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009276 case PotentiallyEvaluatedIfUsed:
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009277 Diag(Loc, PD);
9278 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009279
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009280 case PotentiallyPotentiallyEvaluated:
9281 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9282 break;
9283 }
9284
9285 return false;
9286}
9287
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009288bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9289 CallExpr *CE, FunctionDecl *FD) {
9290 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9291 return false;
9292
9293 PartialDiagnostic Note =
9294 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9295 << FD->getDeclName() : PDiag();
9296 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009297
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009298 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009299 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009300 PDiag(diag::err_call_function_incomplete_return)
9301 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009302 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009303 << CE->getSourceRange(),
9304 std::make_pair(NoteLoc, Note)))
9305 return true;
9306
9307 return false;
9308}
9309
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009310// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009311// will prevent this condition from triggering, which is what we want.
9312void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9313 SourceLocation Loc;
9314
John McCall0506e4a2009-11-11 02:41:58 +00009315 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009316 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009317
John McCalld5707ab2009-10-12 21:59:07 +00009318 if (isa<BinaryOperator>(E)) {
9319 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009320 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009321 return;
9322
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009323 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9324
John McCallb0e419e2009-11-12 00:06:05 +00009325 // Greylist some idioms by putting them into a warning subcategory.
9326 if (ObjCMessageExpr *ME
9327 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9328 Selector Sel = ME->getSelector();
9329
John McCallb0e419e2009-11-12 00:06:05 +00009330 // self = [<foo> init...]
9331 if (isSelfExpr(Op->getLHS())
9332 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
9333 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9334
9335 // <foo> = [<bar> nextObject]
9336 else if (Sel.isUnarySelector() &&
9337 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
9338 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9339 }
John McCall0506e4a2009-11-11 02:41:58 +00009340
John McCalld5707ab2009-10-12 21:59:07 +00009341 Loc = Op->getOperatorLoc();
9342 } else if (isa<CXXOperatorCallExpr>(E)) {
9343 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009344 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009345 return;
9346
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009347 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009348 Loc = Op->getOperatorLoc();
9349 } else {
9350 // Not an assignment.
9351 return;
9352 }
9353
John McCalld5707ab2009-10-12 21:59:07 +00009354 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00009355 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009356
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009357 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009358
9359 if (IsOrAssign)
9360 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9361 << FixItHint::CreateReplacement(Loc, "!=");
9362 else
9363 Diag(Loc, diag::note_condition_assign_to_comparison)
9364 << FixItHint::CreateReplacement(Loc, "==");
9365
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009366 Diag(Loc, diag::note_condition_assign_silence)
9367 << FixItHint::CreateInsertion(Open, "(")
9368 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +00009369}
9370
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009371/// \brief Redundant parentheses over an equality comparison can indicate
9372/// that the user intended an assignment used as condition.
9373void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009374 // Don't warn if the parens came from a macro.
9375 SourceLocation parenLoc = parenE->getLocStart();
9376 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9377 return;
9378
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009379 Expr *E = parenE->IgnoreParens();
9380
9381 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009382 if (opE->getOpcode() == BO_EQ &&
9383 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9384 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009385 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009386
Ted Kremenekae022092011-02-02 02:20:30 +00009387 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9388 Diag(Loc, diag::note_equality_comparison_to_assign)
9389 << FixItHint::CreateReplacement(Loc, "=");
9390 Diag(Loc, diag::note_equality_comparison_silence)
9391 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9392 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009393 }
9394}
9395
John McCalld5707ab2009-10-12 21:59:07 +00009396bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9397 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009398 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9399 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009400
9401 if (!E->isTypeDependent()) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009402 if (E->isBoundMemberFunction(Context))
9403 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9404 << E->getSourceRange();
9405
John McCall34376a62010-12-04 03:47:34 +00009406 if (getLangOptions().CPlusPlus)
9407 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9408
9409 DefaultFunctionArrayLvalueConversion(E);
John McCall29cb2fd2010-12-04 06:09:13 +00009410
9411 QualType T = E->getType();
John McCall34376a62010-12-04 03:47:34 +00009412 if (!T->isScalarType()) // C99 6.8.4.1p1
9413 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9414 << T << E->getSourceRange();
John McCalld5707ab2009-10-12 21:59:07 +00009415 }
9416
9417 return false;
9418}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009419
John McCalldadc5752010-08-24 06:29:42 +00009420ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9421 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009422 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009423 return ExprError();
9424
Douglas Gregorb412e172010-07-25 18:17:45 +00009425 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00009426 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00009427
9428 return Owned(Sub);
9429}
John McCall36e7fe32010-10-12 00:20:44 +00009430
9431/// Check for operands with placeholder types and complain if found.
9432/// Returns true if there was an error and no recovery was possible.
9433ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9434 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9435 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9436
9437 // If this is overload, check for a single overload.
9438 if (BT->getKind() == BuiltinType::Overload) {
9439 if (FunctionDecl *Specialization
9440 = ResolveSingleFunctionTemplateSpecialization(E)) {
9441 // The access doesn't really matter in this case.
9442 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9443 Specialization->getAccess());
9444 E = FixOverloadedFunctionReference(E, Found, Specialization);
9445 if (!E) return ExprError();
9446 return Owned(E);
9447 }
9448
John McCall36226622010-10-12 02:09:17 +00009449 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
John McCall36e7fe32010-10-12 00:20:44 +00009450 return ExprError();
9451 }
9452
9453 // Otherwise it's a use of undeduced auto.
9454 assert(BT->getKind() == BuiltinType::UndeducedAuto);
9455
9456 DeclRefExpr *DRE = cast<DeclRefExpr>(E->IgnoreParens());
9457 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
9458 << DRE->getDecl() << E->getSourceRange();
9459 return ExprError();
9460}