blob: 45e0c3377b830ba0b097310467bb13a9603b83e8 [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) {
531 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
532 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
533 }
John McCalld005ac92010-11-13 08:17:45 +0000534 return rhs;
535 }
536
537 // LHS is at least as wide. Find its corresponding complex type.
538 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
539
540 // double -> _Complex double
541 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000542 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000543
544 // _Complex float -> _Complex double
545 if (order > 0)
John McCallc5e62b42010-11-13 09:02:35 +0000546 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000547
548 return result;
549 }
550
551 // Now handle "real" floating types (i.e. float, double, long double).
552 bool LHSFloat = lhs->isRealFloatingType();
553 bool RHSFloat = rhs->isRealFloatingType();
554 if (LHSFloat || RHSFloat) {
555 // If we have two real floating types, convert the smaller operand
556 // to the bigger result.
557 if (LHSFloat && RHSFloat) {
558 int order = Context.getFloatingTypeOrder(lhs, rhs);
559 if (order > 0) {
560 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
561 return lhs;
562 }
563
564 assert(order < 0 && "illegal float comparison");
565 if (!isCompAssign)
566 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
567 return rhs;
568 }
569
570 // If we have an integer operand, the result is the real floating type.
571 if (LHSFloat) {
572 if (rhs->isIntegerType()) {
573 // Convert rhs to the lhs floating point type.
574 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
575 return lhs;
576 }
577
578 // Convert both sides to the appropriate complex float.
579 assert(rhs->isComplexIntegerType());
580 QualType result = Context.getComplexType(lhs);
581
582 // _Complex int -> _Complex float
John McCalld7646252010-11-14 08:17:51 +0000583 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000584
585 // float -> _Complex float
586 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000587 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000588
589 return result;
590 }
591
592 assert(RHSFloat);
593 if (lhs->isIntegerType()) {
594 // Convert lhs to the rhs floating point type.
595 if (!isCompAssign)
596 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
597 return rhs;
598 }
599
600 // Convert both sides to the appropriate complex float.
601 assert(lhs->isComplexIntegerType());
602 QualType result = Context.getComplexType(rhs);
603
604 // _Complex int -> _Complex float
605 if (!isCompAssign)
John McCalld7646252010-11-14 08:17:51 +0000606 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000607
608 // float -> _Complex float
John McCallc5e62b42010-11-13 09:02:35 +0000609 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000610
611 return result;
612 }
613
614 // Handle GCC complex int extension.
615 // FIXME: if the operands are (int, _Complex long), we currently
616 // don't promote the complex. Also, signedness?
617 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
618 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
619 if (lhsComplexInt && rhsComplexInt) {
620 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
621 rhsComplexInt->getElementType());
622 assert(order && "inequal types with equal element ordering");
623 if (order > 0) {
624 // _Complex int -> _Complex long
John McCallc5e62b42010-11-13 09:02:35 +0000625 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000626 return lhs;
627 }
628
629 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000630 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000631 return rhs;
632 } else if (lhsComplexInt) {
633 // int -> _Complex int
John McCallc5e62b42010-11-13 09:02:35 +0000634 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000635 return lhs;
636 } else if (rhsComplexInt) {
637 // int -> _Complex int
638 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000639 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000640 return rhs;
641 }
642
643 // Finally, we have two differing integer types.
644 // The rules for this case are in C99 6.3.1.8
645 int compare = Context.getIntegerTypeOrder(lhs, rhs);
646 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
647 rhsSigned = rhs->hasSignedIntegerRepresentation();
648 if (lhsSigned == rhsSigned) {
649 // Same signedness; use the higher-ranked type
650 if (compare >= 0) {
651 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
652 return lhs;
653 } else if (!isCompAssign)
654 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
655 return rhs;
656 } else if (compare != (lhsSigned ? 1 : -1)) {
657 // The unsigned type has greater than or equal rank to the
658 // signed type, so use the unsigned type
659 if (rhsSigned) {
660 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
661 return lhs;
662 } else if (!isCompAssign)
663 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
664 return rhs;
665 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
666 // The two types are different widths; if we are here, that
667 // means the signed type is larger than the unsigned type, so
668 // use the signed type.
669 if (lhsSigned) {
670 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
671 return lhs;
672 } else if (!isCompAssign)
673 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
674 return rhs;
675 } else {
676 // The signed type is higher-ranked than the unsigned type,
677 // but isn't actually any bigger (like unsigned int and long
678 // on most 32-bit systems). Use the unsigned type corresponding
679 // to the signed type.
680 QualType result =
681 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
682 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
683 if (!isCompAssign)
684 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
685 return result;
686 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000687}
688
Chris Lattner513165e2008-07-25 21:10:04 +0000689//===----------------------------------------------------------------------===//
690// Semantic Analysis for various Expression Types
691//===----------------------------------------------------------------------===//
692
693
Steve Naroff83895f72007-09-16 03:34:24 +0000694/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000695/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
696/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
697/// multiple tokens. However, the common case is that StringToks points to one
698/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000699///
John McCalldadc5752010-08-24 06:29:42 +0000700ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000701Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000702 assert(NumStringToks && "Must have at least one string!");
703
Chris Lattner8a24e582009-01-16 18:51:42 +0000704 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000705 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000706 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000707
Chris Lattner23b7eb62007-06-15 23:05:46 +0000708 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000709 for (unsigned i = 0; i != NumStringToks; ++i)
710 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000711
Chris Lattner36fc8792008-02-11 00:02:17 +0000712 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000713 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000714 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000715
716 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000717 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000718 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000719
Chris Lattner36fc8792008-02-11 00:02:17 +0000720 // Get an array type for the string, according to C99 6.4.5. This includes
721 // the nul terminator character as well as the string length for pascal
722 // strings.
723 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000724 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000725 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000726
Chris Lattner5b183d82006-11-10 05:03:26 +0000727 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000728 return Owned(StringLiteral::Create(Context, Literal.GetString(),
729 Literal.GetStringLength(),
730 Literal.AnyWide, StrTy,
731 &StringTokLocs[0],
732 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000733}
734
Chris Lattner2a9d9892008-10-20 05:16:36 +0000735/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
736/// CurBlock to VD should cause it to be snapshotted (as we do for auto
737/// variables defined outside the block) or false if this is not needed (e.g.
738/// for values inside the block or for globals).
739///
Douglas Gregor4f13beb2010-03-01 20:44:28 +0000740/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
Chris Lattner497d7b02009-04-21 22:26:47 +0000741/// up-to-date.
742///
Douglas Gregor9a28e842010-03-01 23:15:13 +0000743static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
Chris Lattner2a9d9892008-10-20 05:16:36 +0000744 ValueDecl *VD) {
745 // If the value is defined inside the block, we couldn't snapshot it even if
746 // we wanted to.
747 if (CurBlock->TheDecl == VD->getDeclContext())
748 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000749
Chris Lattner2a9d9892008-10-20 05:16:36 +0000750 // If this is an enum constant or function, it is constant, don't snapshot.
751 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
752 return false;
753
754 // If this is a reference to an extern, static, or global variable, no need to
755 // snapshot it.
756 // FIXME: What about 'const' variables in C++?
757 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000758 if (!Var->hasLocalStorage())
759 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000760
Chris Lattner497d7b02009-04-21 22:26:47 +0000761 // Blocks that have these can't be constant.
762 CurBlock->hasBlockDeclRefExprs = true;
763
764 // If we have nested blocks, the decl may be declared in an outer block (in
765 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
766 // be defined outside all of the current blocks (in which case the blocks do
767 // all get the bit). Walk the nesting chain.
Douglas Gregor9a28e842010-03-01 23:15:13 +0000768 for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
769 BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000770
Douglas Gregor9a28e842010-03-01 23:15:13 +0000771 if (!NextBlock)
772 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000773
Chris Lattner497d7b02009-04-21 22:26:47 +0000774 // If we found the defining block for the variable, don't mark the block as
775 // having a reference outside it.
776 if (NextBlock->TheDecl == VD->getDeclContext())
777 break;
Mike Stump11289f42009-09-09 15:08:12 +0000778
Chris Lattner497d7b02009-04-21 22:26:47 +0000779 // Otherwise, the DeclRef from the inner block causes the outer one to need
780 // a snapshot as well.
781 NextBlock->hasBlockDeclRefExprs = true;
782 }
Mike Stump11289f42009-09-09 15:08:12 +0000783
Chris Lattner2a9d9892008-10-20 05:16:36 +0000784 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000785}
786
Chris Lattner2a9d9892008-10-20 05:16:36 +0000787
John McCalldadc5752010-08-24 06:29:42 +0000788ExprResult
John McCall7decc9e2010-11-18 06:31:45 +0000789Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
790 SourceLocation Loc, const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000791 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +0000792 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000793}
794
795/// BuildDeclRefExpr - Build a DeclRefExpr.
John McCalldadc5752010-08-24 06:29:42 +0000796ExprResult
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000797Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +0000798 ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000799 const DeclarationNameInfo &NameInfo,
800 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000801 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000802 Diag(NameInfo.getLoc(),
Mike Stump11289f42009-09-09 15:08:12 +0000803 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000804 << D->getDeclName();
805 return ExprError();
806 }
Mike Stump11289f42009-09-09 15:08:12 +0000807
Anders Carlsson946b86d2009-06-24 00:10:43 +0000808 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Douglas Gregor15243332010-04-27 21:10:04 +0000809 if (isa<NonTypeTemplateParmDecl>(VD)) {
810 // Non-type template parameters can be referenced anywhere they are
811 // visible.
Douglas Gregora8a089b2010-07-13 18:40:04 +0000812 Ty = Ty.getNonLValueExprType(Context);
Douglas Gregor15243332010-04-27 21:10:04 +0000813 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
Anders Carlsson946b86d2009-06-24 00:10:43 +0000814 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
815 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000816 Diag(NameInfo.getLoc(),
817 diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000818 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000819 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000820 << D->getIdentifier();
821 return ExprError();
822 }
823 }
John McCall4bc41ae2010-11-18 19:01:18 +0000824
825 // This ridiculousness brought to you by 'extern void x;' and the
826 // GNU compiler collection.
827 } else if (!getLangOptions().CPlusPlus && !Ty.hasQualifiers() &&
828 Ty->isVoidType()) {
829 VK = VK_RValue;
Anders Carlsson946b86d2009-06-24 00:10:43 +0000830 }
831 }
Mike Stump11289f42009-09-09 15:08:12 +0000832
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000833 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +0000834
John McCall086a4642010-11-24 05:12:34 +0000835 Expr *E = DeclRefExpr::Create(Context,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000836 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
John McCall086a4642010-11-24 05:12:34 +0000837 SS? SS->getRange() : SourceRange(),
838 D, NameInfo, Ty, VK);
839
840 // Just in case we're building an illegal pointer-to-member.
841 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
842 E->setObjectKind(OK_BitField);
843
844 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000845}
846
John McCallfeb624a2010-11-23 20:48:44 +0000847static ExprResult
848BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
849 const CXXScopeSpec &SS, FieldDecl *Field,
850 DeclAccessPair FoundDecl,
851 const DeclarationNameInfo &MemberNameInfo);
852
John McCalldadc5752010-08-24 06:29:42 +0000853ExprResult
Douglas Gregord5846a12009-04-15 06:41:24 +0000854Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
Francois Pichet783dd6e2010-11-21 06:08:52 +0000855 IndirectFieldDecl *IndirectField,
Douglas Gregord5846a12009-04-15 06:41:24 +0000856 Expr *BaseObjectExpr,
857 SourceLocation OpLoc) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000858 // Build the expression that refers to the base object, from
859 // which we will build a sequence of member references to each
860 // of the anonymous union objects and, eventually, the field we
861 // found via name lookup.
862 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000863 Qualifiers BaseQuals;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000864 VarDecl *BaseObject = IndirectField->getVarDecl();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000865 if (BaseObject) {
866 // BaseObject is an anonymous struct/union variable (and is,
867 // therefore, not part of another non-anonymous record).
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000868 MarkDeclarationReferenced(Loc, BaseObject);
John McCall7decc9e2010-11-18 06:31:45 +0000869 BaseObjectExpr =
870 new (Context) DeclRefExpr(BaseObject, BaseObject->getType(),
871 VK_LValue, Loc);
John McCall8ccfcb52009-09-24 19:53:00 +0000872 BaseQuals
873 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000874 } else if (BaseObjectExpr) {
875 // The caller provided the base object expression. Determine
876 // whether its a pointer and whether it adds any qualifiers to the
877 // anonymous struct/union fields we're looking into.
878 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000879 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000880 BaseObjectIsPointer = true;
881 ObjectType = ObjectPtr->getPointeeType();
882 }
John McCall8ccfcb52009-09-24 19:53:00 +0000883 BaseQuals
884 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000885 } else {
886 // We've found a member of an anonymous struct/union that is
887 // inside a non-anonymous struct/union, so in a well-formed
888 // program our base object expression is "this".
John McCall87fe5d52010-05-20 01:18:31 +0000889 DeclContext *DC = getFunctionLevelDeclContext();
890 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000891 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000892 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000893 = Context.getTagDeclType(
Francois Pichet783dd6e2010-11-21 06:08:52 +0000894 cast<RecordDecl>(
895 (*IndirectField->chain_begin())->getDeclContext()));
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000896 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000897 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000898 == Context.getCanonicalType(ThisType)) ||
899 IsDerivedFrom(ThisType, AnonFieldType)) {
900 // Our base object expression is "this".
Douglas Gregor4b654412009-12-24 20:23:34 +0000901 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000902 MD->getThisType(Context),
903 /*isImplicit=*/true);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000904 BaseObjectIsPointer = true;
905 }
906 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000907 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
Francois Pichet783dd6e2010-11-21 06:08:52 +0000908 << IndirectField->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000909 }
John McCall8ccfcb52009-09-24 19:53:00 +0000910 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000911 }
912
Mike Stump11289f42009-09-09 15:08:12 +0000913 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000914 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
Francois Pichet783dd6e2010-11-21 06:08:52 +0000915 << IndirectField->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000916 }
917
918 // Build the implicit member references to the field of the
919 // anonymous struct/union.
920 Expr *Result = BaseObjectExpr;
John McCallfeb624a2010-11-23 20:48:44 +0000921
Francois Pichet783dd6e2010-11-21 06:08:52 +0000922 IndirectFieldDecl::chain_iterator FI = IndirectField->chain_begin(),
923 FEnd = IndirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +0000924
Francois Pichet783dd6e2010-11-21 06:08:52 +0000925 // Skip the first VarDecl if present.
926 if (BaseObject)
927 FI++;
928 for (; FI != FEnd; FI++) {
929 FieldDecl *Field = cast<FieldDecl>(*FI);
John McCall8ccfcb52009-09-24 19:53:00 +0000930
John McCallfeb624a2010-11-23 20:48:44 +0000931 // FIXME: the first access can be qualified
932 CXXScopeSpec SS;
John McCall8ccfcb52009-09-24 19:53:00 +0000933
John McCallfeb624a2010-11-23 20:48:44 +0000934 // FIXME: these are somewhat meaningless
935 DeclarationNameInfo MemberNameInfo(Field->getDeclName(), Loc);
936 DeclAccessPair FoundDecl = DeclAccessPair::make(Field, Field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +0000937
John McCallfeb624a2010-11-23 20:48:44 +0000938 Result = BuildFieldReferenceExpr(*this, Result, BaseObjectIsPointer,
939 SS, Field, FoundDecl, MemberNameInfo)
940 .take();
John McCall8ccfcb52009-09-24 19:53:00 +0000941
John McCallfeb624a2010-11-23 20:48:44 +0000942 // All the implicit accesses are dot-accesses.
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000943 BaseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000944 }
945
Sebastian Redlffbcf962009-01-18 18:53:16 +0000946 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000947}
948
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000949/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +0000950/// possibly a list of template arguments.
951///
952/// If this produces template arguments, it is permitted to call
953/// DecomposeTemplateName.
954///
955/// This actually loses a lot of source location information for
956/// non-standard name kinds; we should consider preserving that in
957/// some way.
958static void DecomposeUnqualifiedId(Sema &SemaRef,
959 const UnqualifiedId &Id,
960 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000961 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +0000962 const TemplateArgumentListInfo *&TemplateArgs) {
963 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
964 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
965 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
966
967 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
968 Id.TemplateId->getTemplateArgs(),
969 Id.TemplateId->NumArgs);
970 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
971 TemplateArgsPtr.release();
972
John McCall3e56fd42010-08-23 07:28:44 +0000973 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000974 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
975 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +0000976 TemplateArgs = &Buffer;
977 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000978 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +0000979 TemplateArgs = 0;
980 }
981}
982
John McCall69f9dbc2010-02-08 19:26:07 +0000983/// Determines whether the given record is "fully-formed" at the given
984/// location, i.e. whether a qualified lookup into it is assured of
985/// getting consistent results already.
John McCall10eae182009-11-30 22:42:35 +0000986static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
John McCall69f9dbc2010-02-08 19:26:07 +0000987 if (!Record->hasDefinition())
988 return false;
989
John McCall10eae182009-11-30 22:42:35 +0000990 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
991 E = Record->bases_end(); I != E; ++I) {
992 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
993 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
994 if (!BaseRT) return false;
995
996 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall69f9dbc2010-02-08 19:26:07 +0000997 if (!BaseRecord->hasDefinition() ||
John McCall10eae182009-11-30 22:42:35 +0000998 !IsFullyFormedScope(SemaRef, BaseRecord))
999 return false;
1000 }
1001
1002 return true;
1003}
1004
John McCall2d74de92009-12-01 22:10:20 +00001005/// Determines if the given class is provably not derived from all of
1006/// the prospective base classes.
1007static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1008 CXXRecordDecl *Record,
1009 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001010 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001011 return false;
1012
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001013 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001014 if (!RD) return false;
1015 Record = cast<CXXRecordDecl>(RD);
1016
John McCall2d74de92009-12-01 22:10:20 +00001017 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1018 E = Record->bases_end(); I != E; ++I) {
1019 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1020 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1021 if (!BaseRT) return false;
1022
1023 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001024 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1025 return false;
1026 }
1027
1028 return true;
1029}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001030
John McCall2d74de92009-12-01 22:10:20 +00001031enum IMAKind {
1032 /// The reference is definitely not an instance member access.
1033 IMA_Static,
1034
1035 /// The reference may be an implicit instance member access.
1036 IMA_Mixed,
1037
1038 /// The reference may be to an instance member, but it is invalid if
1039 /// so, because the context is not an instance method.
1040 IMA_Mixed_StaticContext,
1041
1042 /// The reference may be to an instance member, but it is invalid if
1043 /// so, because the context is from an unrelated class.
1044 IMA_Mixed_Unrelated,
1045
1046 /// The reference is definitely an implicit instance member access.
1047 IMA_Instance,
1048
1049 /// The reference may be to an unresolved using declaration.
1050 IMA_Unresolved,
1051
1052 /// The reference may be to an unresolved using declaration and the
1053 /// context is not an instance method.
1054 IMA_Unresolved_StaticContext,
1055
John McCall2d74de92009-12-01 22:10:20 +00001056 /// All possible referrents are instance members and the current
1057 /// context is not an instance method.
1058 IMA_Error_StaticContext,
1059
1060 /// All possible referrents are instance members of an unrelated
1061 /// class.
1062 IMA_Error_Unrelated
1063};
1064
1065/// The given lookup names class member(s) and is not being used for
1066/// an address-of-member expression. Classify the type of access
1067/// according to whether it's possible that this reference names an
1068/// instance member. This is best-effort; it is okay to
1069/// conservatively answer "yes", in which case some errors will simply
1070/// not be caught until template-instantiation.
1071static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1072 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001073 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001074
John McCall87fe5d52010-05-20 01:18:31 +00001075 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001076 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001077 (!isa<CXXMethodDecl>(DC) ||
1078 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001079
1080 if (R.isUnresolvableResult())
1081 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1082
1083 // Collect all the declaring classes of instance members we find.
1084 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001085 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001086 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1087 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001088 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001089
John McCalla8ae2222010-04-06 21:38:20 +00001090 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001091 if (dyn_cast<FieldDecl>(D))
1092 hasField = true;
1093
John McCall2d74de92009-12-01 22:10:20 +00001094 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001095 Classes.insert(R->getCanonicalDecl());
1096 }
1097 else
1098 hasNonInstance = true;
1099 }
1100
1101 // If we didn't find any instance members, it can't be an implicit
1102 // member reference.
1103 if (Classes.empty())
1104 return IMA_Static;
1105
1106 // If the current context is not an instance method, it can't be
1107 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001108 if (isStaticContext) {
1109 if (hasNonInstance)
1110 return IMA_Mixed_StaticContext;
1111
1112 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1113 // C++0x [expr.prim.general]p10:
1114 // An id-expression that denotes a non-static data member or non-static
1115 // member function of a class can only be used:
1116 // (...)
1117 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1118 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1119 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1120 if (isUnevaluatedExpression)
1121 return IMA_Mixed_StaticContext;
1122 }
1123
1124 return IMA_Error_StaticContext;
1125 }
John McCall2d74de92009-12-01 22:10:20 +00001126
1127 // If we can prove that the current context is unrelated to all the
1128 // declaring classes, it can't be an implicit member reference (in
1129 // which case it's an error if any of those members are selected).
1130 if (IsProvablyNotDerivedFrom(SemaRef,
John McCall87fe5d52010-05-20 01:18:31 +00001131 cast<CXXMethodDecl>(DC)->getParent(),
John McCall2d74de92009-12-01 22:10:20 +00001132 Classes))
1133 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1134
1135 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1136}
1137
1138/// Diagnose a reference to a field with no object available.
1139static void DiagnoseInstanceReference(Sema &SemaRef,
1140 const CXXScopeSpec &SS,
1141 const LookupResult &R) {
1142 SourceLocation Loc = R.getNameLoc();
1143 SourceRange Range(Loc);
1144 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1145
1146 if (R.getAsSingle<FieldDecl>()) {
1147 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1148 if (MD->isStatic()) {
1149 // "invalid use of member 'x' in static member function"
1150 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
1151 << Range << R.getLookupName();
1152 return;
1153 }
1154 }
1155
1156 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
1157 << R.getLookupName() << Range;
1158 return;
1159 }
1160
1161 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001162}
1163
John McCalld681c392009-12-16 08:11:27 +00001164/// Diagnose an empty lookup.
1165///
1166/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001167bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1168 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001169 DeclarationName Name = R.getLookupName();
1170
John McCalld681c392009-12-16 08:11:27 +00001171 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001172 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001173 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1174 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001175 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001176 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001177 diagnostic_suggest = diag::err_undeclared_use_suggest;
1178 }
John McCalld681c392009-12-16 08:11:27 +00001179
Douglas Gregor598b08f2009-12-31 05:20:13 +00001180 // If the original lookup was an unqualified lookup, fake an
1181 // unqualified lookup. This is useful when (for example) the
1182 // original lookup would not have found something because it was a
1183 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001184 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001185 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001186 if (isa<CXXRecordDecl>(DC)) {
1187 LookupQualifiedName(R, DC);
1188
1189 if (!R.empty()) {
1190 // Don't give errors about ambiguities in this lookup.
1191 R.suppressDiagnostics();
1192
1193 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1194 bool isInstance = CurMethod &&
1195 CurMethod->isInstance() &&
1196 DC == CurMethod->getParent();
1197
1198 // Give a code modification hint to insert 'this->'.
1199 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1200 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001201 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001202 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1203 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001204 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001205 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001206 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001207 Diag(R.getNameLoc(), diagnostic) << Name
1208 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1209 QualType DepThisType = DepMethod->getThisType(Context);
1210 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1211 R.getNameLoc(), DepThisType, false);
1212 TemplateArgumentListInfo TList;
1213 if (ULE->hasExplicitTemplateArgs())
1214 ULE->copyTemplateArgumentsInto(TList);
1215 CXXDependentScopeMemberExpr *DepExpr =
1216 CXXDependentScopeMemberExpr::Create(
1217 Context, DepThis, DepThisType, true, SourceLocation(),
1218 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
1219 R.getLookupNameInfo(), &TList);
1220 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001221 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001222 // FIXME: we should be able to handle this case too. It is correct
1223 // to add this-> here. This is a workaround for PR7947.
1224 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001225 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001226 } else {
John McCalld681c392009-12-16 08:11:27 +00001227 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001228 }
John McCalld681c392009-12-16 08:11:27 +00001229
1230 // Do we really want to note all of these?
1231 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1232 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1233
1234 // Tell the callee to try to recover.
1235 return false;
1236 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001237
1238 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001239 }
1240 }
1241
Douglas Gregor598b08f2009-12-31 05:20:13 +00001242 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001243 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001244 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001245 if (!R.empty()) {
1246 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1247 if (SS.isEmpty())
1248 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1249 << FixItHint::CreateReplacement(R.getNameLoc(),
1250 R.getLookupName().getAsString());
1251 else
1252 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1253 << Name << computeDeclContext(SS, false) << R.getLookupName()
1254 << SS.getRange()
1255 << FixItHint::CreateReplacement(R.getNameLoc(),
1256 R.getLookupName().getAsString());
1257 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1258 Diag(ND->getLocation(), diag::note_previous_decl)
1259 << ND->getDeclName();
1260
1261 // Tell the callee to try to recover.
1262 return false;
1263 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001264
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001265 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1266 // FIXME: If we ended up with a typo for a type name or
1267 // Objective-C class name, we're in trouble because the parser
1268 // is in the wrong place to recover. Suggest the typo
1269 // correction, but don't make it a fix-it since we're not going
1270 // to recover well anyway.
1271 if (SS.isEmpty())
1272 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1273 else
1274 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1275 << Name << computeDeclContext(SS, false) << R.getLookupName()
1276 << SS.getRange();
1277
1278 // Don't try to recover; it won't work.
1279 return true;
1280 }
1281 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001282 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001283 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001284 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001285 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001286 else
Douglas Gregor25363982010-01-01 00:15:04 +00001287 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001288 << Name << computeDeclContext(SS, false) << Corrected
1289 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001290 return true;
1291 }
Douglas Gregor25363982010-01-01 00:15:04 +00001292 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001293 }
1294
1295 // Emit a special diagnostic for failed member lookups.
1296 // FIXME: computing the declaration context might fail here (?)
1297 if (!SS.isEmpty()) {
1298 Diag(R.getNameLoc(), diag::err_no_member)
1299 << Name << computeDeclContext(SS, false)
1300 << SS.getRange();
1301 return true;
1302 }
1303
John McCalld681c392009-12-16 08:11:27 +00001304 // Give up, we can't recover.
1305 Diag(R.getNameLoc(), diagnostic) << Name;
1306 return true;
1307}
1308
Douglas Gregor05fcf842010-11-02 20:36:02 +00001309ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1310 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001311 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1312 if (!IDecl)
1313 return 0;
1314 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1315 if (!ClassImpDecl)
1316 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001317 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001318 if (!property)
1319 return 0;
1320 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001321 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1322 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001323 return 0;
1324 return property;
1325}
1326
Douglas Gregor05fcf842010-11-02 20:36:02 +00001327bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1328 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1329 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1330 if (!IDecl)
1331 return false;
1332 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1333 if (!ClassImpDecl)
1334 return false;
1335 if (ObjCPropertyImplDecl *PIDecl
1336 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1337 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1338 PIDecl->getPropertyIvarDecl())
1339 return false;
1340
1341 return true;
1342}
1343
Fariborz Jahanian18722982010-07-17 00:59:30 +00001344static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001345 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001346 IdentifierInfo *II,
1347 SourceLocation NameLoc) {
1348 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001349 bool LookForIvars;
1350 if (Lookup.empty())
1351 LookForIvars = true;
1352 else if (CurMeth->isClassMethod())
1353 LookForIvars = false;
1354 else
1355 LookForIvars = (Lookup.isSingleResult() &&
1356 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1357 if (!LookForIvars)
1358 return 0;
1359
Fariborz Jahanian18722982010-07-17 00:59:30 +00001360 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1361 if (!IDecl)
1362 return 0;
1363 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001364 if (!ClassImpDecl)
1365 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001366 bool DynamicImplSeen = false;
1367 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1368 if (!property)
1369 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001370 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001371 DynamicImplSeen =
1372 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001373 // property implementation has a designated ivar. No need to assume a new
1374 // one.
1375 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1376 return 0;
1377 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001378 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001379 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1380 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001381 NameLoc,
1382 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001383 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001384 (Expr *)0, true);
1385 ClassImpDecl->addDecl(Ivar);
1386 IDecl->makeDeclVisibleInContext(Ivar, false);
1387 property->setPropertyIvarDecl(Ivar);
1388 return Ivar;
1389 }
1390 return 0;
1391}
1392
John McCalldadc5752010-08-24 06:29:42 +00001393ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001394 CXXScopeSpec &SS,
1395 UnqualifiedId &Id,
1396 bool HasTrailingLParen,
1397 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001398 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1399 "cannot be direct & operand and have a trailing lparen");
1400
1401 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001402 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001403
John McCall10eae182009-11-30 22:42:35 +00001404 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001405
1406 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001407 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001408 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001409 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001410
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001411 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001412 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001413 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001414
John McCalle66edc12009-11-24 19:00:30 +00001415 // C++ [temp.dep.expr]p3:
1416 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001417 // -- an identifier that was declared with a dependent type,
1418 // (note: handled after lookup)
1419 // -- a template-id that is dependent,
1420 // (note: handled in BuildTemplateIdExpr)
1421 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001422 // -- a nested-name-specifier that contains a class-name that
1423 // names a dependent type.
1424 // Determine whether this is a member of an unknown specialization;
1425 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001426 bool DependentID = false;
1427 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1428 Name.getCXXNameType()->isDependentType()) {
1429 DependentID = true;
1430 } else if (SS.isSet()) {
1431 DeclContext *DC = computeDeclContext(SS, false);
1432 if (DC) {
1433 if (RequireCompleteDeclContext(SS, DC))
1434 return ExprError();
1435 // FIXME: We should be checking whether DC is the current instantiation.
1436 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
1437 DependentID = !IsFullyFormedScope(*this, RD);
1438 } else {
1439 DependentID = true;
1440 }
1441 }
1442
1443 if (DependentID) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001444 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001445 TemplateArgs);
1446 }
Fariborz Jahanian86151342010-07-22 23:33:21 +00001447 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001448 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001449 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001450 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001451 // Lookup the template name again to correctly establish the context in
1452 // which it was found. This is really unfortunate as we already did the
1453 // lookup to determine that it was a template name in the first place. If
1454 // this becomes a performance hit, we can work harder to preserve those
1455 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001456 bool MemberOfUnknownSpecialization;
1457 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1458 MemberOfUnknownSpecialization);
John McCalle66edc12009-11-24 19:00:30 +00001459 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001460 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001461 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001462
John McCalle66edc12009-11-24 19:00:30 +00001463 // If this reference is in an Objective-C method, then we need to do
1464 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001465 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001466 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001467 if (E.isInvalid())
1468 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001469
John McCalle66edc12009-11-24 19:00:30 +00001470 Expr *Ex = E.takeAs<Expr>();
1471 if (Ex) return Owned(Ex);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001472 // Synthesize ivars lazily
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001473 if (getLangOptions().ObjCDefaultSynthProperties &&
1474 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001475 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1476 if (const ObjCPropertyDecl *Property =
1477 canSynthesizeProvisionalIvar(II)) {
1478 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1479 Diag(Property->getLocation(), diag::note_property_declare);
1480 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001481 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1482 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001483 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001484 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001485 // for further use, this must be set to false if in class method.
1486 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001487 }
Chris Lattner59a25942008-03-31 00:36:02 +00001488 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001489
John McCalle66edc12009-11-24 19:00:30 +00001490 if (R.isAmbiguous())
1491 return ExprError();
1492
Douglas Gregor171c45a2009-02-18 21:56:37 +00001493 // Determine whether this name might be a candidate for
1494 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001495 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001496
John McCalle66edc12009-11-24 19:00:30 +00001497 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001498 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001499 // in C90, extension in C99, forbidden in C++).
1500 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1501 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1502 if (D) R.addDecl(D);
1503 }
1504
1505 // If this name wasn't predeclared and if this is not a function
1506 // call, diagnose the problem.
1507 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001508 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001509 return ExprError();
1510
1511 assert(!R.empty() &&
1512 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001513
1514 // If we found an Objective-C instance variable, let
1515 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001516 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001517 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1518 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001519 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001520 assert(E.isInvalid() || E.get());
1521 return move(E);
1522 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001523 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001524 }
Mike Stump11289f42009-09-09 15:08:12 +00001525
John McCalle66edc12009-11-24 19:00:30 +00001526 // This is guaranteed from this point on.
1527 assert(!R.empty() || ADL);
1528
1529 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001530 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001531 !(getLangOptions().ObjCDefaultSynthProperties &&
1532 getLangOptions().ObjCNonFragileABI2) &&
Fariborz Jahanianc15dfd82010-07-29 16:53:53 +00001533 Var->isFileVarDecl()) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001534 ObjCPropertyDecl *Property = canSynthesizeProvisionalIvar(II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001535 if (Property) {
1536 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1537 Diag(Property->getLocation(), diag::note_property_declare);
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001538 Diag(Var->getLocation(), diag::note_global_declared_at);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001539 }
1540 }
John McCalle66edc12009-11-24 19:00:30 +00001541 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001542 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1543 // C99 DR 316 says that, if a function type comes from a
1544 // function definition (without a prototype), that type is only
1545 // used for checking compatibility. Therefore, when referencing
1546 // the function, we pretend that we don't have the full function
1547 // type.
John McCalle66edc12009-11-24 19:00:30 +00001548 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001549 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001550
Douglas Gregor3256d042009-06-30 15:47:41 +00001551 QualType T = Func->getType();
1552 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001553 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Eli Friedmanb41ad0f2010-05-17 02:50:18 +00001554 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(),
1555 Proto->getExtInfo());
John McCall7decc9e2010-11-18 06:31:45 +00001556 // Note that functions are r-values in C.
1557 return BuildDeclRefExpr(Func, NoProtoType, VK_RValue, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001558 }
1559 }
Mike Stump11289f42009-09-09 15:08:12 +00001560
John McCall2d74de92009-12-01 22:10:20 +00001561 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001562 // C++ [class.mfct.non-static]p3:
1563 // When an id-expression that is not part of a class member access
1564 // syntax and not used to form a pointer to member is used in the
1565 // body of a non-static member function of class X, if name lookup
1566 // resolves the name in the id-expression to a non-static non-type
1567 // member of some class C, the id-expression is transformed into a
1568 // class member access expression using (*this) as the
1569 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001570 //
1571 // But we don't actually need to do this for '&' operands if R
1572 // resolved to a function or overloaded function set, because the
1573 // expression is ill-formed if it actually works out to be a
1574 // non-static member function:
1575 //
1576 // C++ [expr.ref]p4:
1577 // Otherwise, if E1.E2 refers to a non-static member function. . .
1578 // [t]he expression can be used only as the left-hand operand of a
1579 // member function call.
1580 //
1581 // There are other safeguards against such uses, but it's important
1582 // to get this right here so that we don't end up making a
1583 // spuriously dependent expression if we're inside a dependent
1584 // instance method.
John McCall57500772009-12-16 12:17:52 +00001585 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001586 bool MightBeImplicitMember;
1587 if (!isAddressOfOperand)
1588 MightBeImplicitMember = true;
1589 else if (!SS.isEmpty())
1590 MightBeImplicitMember = false;
1591 else if (R.isOverloadedResult())
1592 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001593 else if (R.isUnresolvableResult())
1594 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001595 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001596 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1597 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001598
1599 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001600 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001601 }
1602
John McCalle66edc12009-11-24 19:00:30 +00001603 if (TemplateArgs)
1604 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001605
John McCalle66edc12009-11-24 19:00:30 +00001606 return BuildDeclarationNameExpr(SS, R, ADL);
1607}
1608
John McCall57500772009-12-16 12:17:52 +00001609/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001610ExprResult
John McCall57500772009-12-16 12:17:52 +00001611Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1612 LookupResult &R,
1613 const TemplateArgumentListInfo *TemplateArgs) {
1614 switch (ClassifyImplicitMemberAccess(*this, R)) {
1615 case IMA_Instance:
1616 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1617
John McCall57500772009-12-16 12:17:52 +00001618 case IMA_Mixed:
1619 case IMA_Mixed_Unrelated:
1620 case IMA_Unresolved:
1621 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1622
1623 case IMA_Static:
1624 case IMA_Mixed_StaticContext:
1625 case IMA_Unresolved_StaticContext:
1626 if (TemplateArgs)
1627 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1628 return BuildDeclarationNameExpr(SS, R, false);
1629
1630 case IMA_Error_StaticContext:
1631 case IMA_Error_Unrelated:
1632 DiagnoseInstanceReference(*this, SS, R);
1633 return ExprError();
1634 }
1635
1636 llvm_unreachable("unexpected instance member access kind");
1637 return ExprError();
1638}
1639
John McCall10eae182009-11-30 22:42:35 +00001640/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1641/// declaration name, generally during template instantiation.
1642/// There's a large number of things which don't need to be done along
1643/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001644ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001645Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001646 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001647 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001648 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001649 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001650
John McCall0b66eb32010-05-01 00:40:08 +00001651 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001652 return ExprError();
1653
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001654 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001655 LookupQualifiedName(R, DC);
1656
1657 if (R.isAmbiguous())
1658 return ExprError();
1659
1660 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001661 Diag(NameInfo.getLoc(), diag::err_no_member)
1662 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001663 return ExprError();
1664 }
1665
1666 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1667}
1668
1669/// LookupInObjCMethod - The parser has read a name in, and Sema has
1670/// detected that we're currently inside an ObjC method. Perform some
1671/// additional lookup.
1672///
1673/// Ideally, most of this would be done by lookup, but there's
1674/// actually quite a lot of extra work involved.
1675///
1676/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001677ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001678Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001679 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001680 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001681 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001682
John McCalle66edc12009-11-24 19:00:30 +00001683 // There are two cases to handle here. 1) scoped lookup could have failed,
1684 // in which case we should look for an ivar. 2) scoped lookup could have
1685 // found a decl, but that decl is outside the current instance method (i.e.
1686 // a global variable). In these two cases, we do a lookup for an ivar with
1687 // this name, if the lookup sucedes, we replace it our current decl.
1688
1689 // If we're in a class method, we don't normally want to look for
1690 // ivars. But if we don't find anything else, and there's an
1691 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001692 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001693
1694 bool LookForIvars;
1695 if (Lookup.empty())
1696 LookForIvars = true;
1697 else if (IsClassMethod)
1698 LookForIvars = false;
1699 else
1700 LookForIvars = (Lookup.isSingleResult() &&
1701 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001702 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001703 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001704 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001705 ObjCInterfaceDecl *ClassDeclared;
1706 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1707 // Diagnose using an ivar in a class method.
1708 if (IsClassMethod)
1709 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1710 << IV->getDeclName());
1711
1712 // If we're referencing an invalid decl, just return this as a silent
1713 // error node. The error diagnostic was already emitted on the decl.
1714 if (IV->isInvalidDecl())
1715 return ExprError();
1716
1717 // Check if referencing a field with __attribute__((deprecated)).
1718 if (DiagnoseUseOfDecl(IV, Loc))
1719 return ExprError();
1720
1721 // Diagnose the use of an ivar outside of the declaring class.
1722 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1723 ClassDeclared != IFace)
1724 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1725
1726 // FIXME: This should use a new expr for a direct reference, don't
1727 // turn this into Self->ivar, just return a BareIVarExpr or something.
1728 IdentifierInfo &II = Context.Idents.get("self");
1729 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001730 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001731 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001732 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001733 SelfName, false, false);
1734 if (SelfExpr.isInvalid())
1735 return ExprError();
1736
John McCall27584242010-12-06 20:48:59 +00001737 Expr *SelfE = SelfExpr.take();
1738 DefaultLvalueConversion(SelfE);
1739
John McCalle66edc12009-11-24 19:00:30 +00001740 MarkDeclarationReferenced(Loc, IV);
1741 return Owned(new (Context)
1742 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall27584242010-12-06 20:48:59 +00001743 SelfE, true, true));
John McCalle66edc12009-11-24 19:00:30 +00001744 }
Chris Lattner87313662010-04-12 05:10:17 +00001745 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001746 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001747 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001748 ObjCInterfaceDecl *ClassDeclared;
1749 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1750 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1751 IFace == ClassDeclared)
1752 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1753 }
1754 }
1755
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001756 if (Lookup.empty() && II && AllowBuiltinCreation) {
1757 // FIXME. Consolidate this with similar code in LookupName.
1758 if (unsigned BuiltinID = II->getBuiltinID()) {
1759 if (!(getLangOptions().CPlusPlus &&
1760 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1761 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1762 S, Lookup.isForRedeclaration(),
1763 Lookup.getNameLoc());
1764 if (D) Lookup.addDecl(D);
1765 }
1766 }
1767 }
John McCalle66edc12009-11-24 19:00:30 +00001768 // Sentinel value saying that we didn't do anything special.
1769 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001770}
John McCalld14a8642009-11-21 08:51:07 +00001771
John McCall16df1e52010-03-30 21:47:33 +00001772/// \brief Cast a base object to a member's actual type.
1773///
1774/// Logically this happens in three phases:
1775///
1776/// * First we cast from the base type to the naming class.
1777/// The naming class is the class into which we were looking
1778/// when we found the member; it's the qualifier type if a
1779/// qualifier was provided, and otherwise it's the base type.
1780///
1781/// * Next we cast from the naming class to the declaring class.
1782/// If the member we found was brought into a class's scope by
1783/// a using declaration, this is that class; otherwise it's
1784/// the class declaring the member.
1785///
1786/// * Finally we cast from the declaring class to the "true"
1787/// declaring class of the member. This conversion does not
1788/// obey access control.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001789bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001790Sema::PerformObjectMemberConversion(Expr *&From,
1791 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001792 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001793 NamedDecl *Member) {
1794 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1795 if (!RD)
1796 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001797
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001798 QualType DestRecordType;
1799 QualType DestType;
1800 QualType FromRecordType;
1801 QualType FromType = From->getType();
1802 bool PointerConversions = false;
1803 if (isa<FieldDecl>(Member)) {
1804 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001805
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001806 if (FromType->getAs<PointerType>()) {
1807 DestType = Context.getPointerType(DestRecordType);
1808 FromRecordType = FromType->getPointeeType();
1809 PointerConversions = true;
1810 } else {
1811 DestType = DestRecordType;
1812 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001813 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001814 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1815 if (Method->isStatic())
1816 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001817
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001818 DestType = Method->getThisType(Context);
1819 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001820
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001821 if (FromType->getAs<PointerType>()) {
1822 FromRecordType = FromType->getPointeeType();
1823 PointerConversions = true;
1824 } else {
1825 FromRecordType = FromType;
1826 DestType = DestRecordType;
1827 }
1828 } else {
1829 // No conversion necessary.
1830 return false;
1831 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001832
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001833 if (DestType->isDependentType() || FromType->isDependentType())
1834 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001835
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001836 // If the unqualified types are the same, no conversion is necessary.
1837 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1838 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001839
John McCall16df1e52010-03-30 21:47:33 +00001840 SourceRange FromRange = From->getSourceRange();
1841 SourceLocation FromLoc = FromRange.getBegin();
1842
John McCall2536c6d2010-08-25 10:28:54 +00001843 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001844
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001845 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001846 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001847 // class name.
1848 //
1849 // If the member was a qualified name and the qualified referred to a
1850 // specific base subobject type, we'll cast to that intermediate type
1851 // first and then to the object in which the member is declared. That allows
1852 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1853 //
1854 // class Base { public: int x; };
1855 // class Derived1 : public Base { };
1856 // class Derived2 : public Base { };
1857 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1858 //
1859 // void VeryDerived::f() {
1860 // x = 17; // error: ambiguous base subobjects
1861 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1862 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001863 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001864 QualType QType = QualType(Qualifier->getAsType(), 0);
1865 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1866 assert(QType->isRecordType() && "lookup done with non-record type");
1867
1868 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1869
1870 // In C++98, the qualifier type doesn't actually have to be a base
1871 // type of the object type, in which case we just ignore it.
1872 // Otherwise build the appropriate casts.
1873 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00001874 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001875 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001876 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001877 return true;
1878
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001879 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00001880 QType = Context.getPointerType(QType);
John McCall2536c6d2010-08-25 10:28:54 +00001881 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
1882 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00001883
1884 FromType = QType;
1885 FromRecordType = QRecordType;
1886
1887 // If the qualifier type was the same as the destination type,
1888 // we're done.
1889 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1890 return false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001891 }
1892 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001893
John McCall16df1e52010-03-30 21:47:33 +00001894 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001895
John McCall16df1e52010-03-30 21:47:33 +00001896 // If we actually found the member through a using declaration, cast
1897 // down to the using declaration's type.
1898 //
1899 // Pointer equality is fine here because only one declaration of a
1900 // class ever has member declarations.
1901 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1902 assert(isa<UsingShadowDecl>(FoundDecl));
1903 QualType URecordType = Context.getTypeDeclType(
1904 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1905
1906 // We only need to do this if the naming-class to declaring-class
1907 // conversion is non-trivial.
1908 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1909 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00001910 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001911 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001912 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001913 return true;
Alexis Huntc46382e2010-04-28 23:02:27 +00001914
John McCall16df1e52010-03-30 21:47:33 +00001915 QualType UType = URecordType;
1916 if (PointerConversions)
1917 UType = Context.getPointerType(UType);
John McCalle3027922010-08-25 11:45:40 +00001918 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001919 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00001920 FromType = UType;
1921 FromRecordType = URecordType;
1922 }
1923
1924 // We don't do access control for the conversion from the
1925 // declaring class to the true declaring class.
1926 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001927 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001928
John McCallcf142162010-08-07 06:22:56 +00001929 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00001930 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1931 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00001932 IgnoreAccess))
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001933 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001934
John McCalle3027922010-08-25 11:45:40 +00001935 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001936 VK, &BasePath);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001937 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001938}
Douglas Gregor3256d042009-06-30 15:47:41 +00001939
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001940/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001941static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001942 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00001943 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001944 const DeclarationNameInfo &MemberNameInfo,
1945 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00001946 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00001947 const TemplateArgumentListInfo *TemplateArgs = 0) {
1948 NestedNameSpecifier *Qualifier = 0;
1949 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001950 if (SS.isSet()) {
1951 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1952 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001953 }
Mike Stump11289f42009-09-09 15:08:12 +00001954
John McCalle66edc12009-11-24 19:00:30 +00001955 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001956 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00001957 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00001958}
1959
John McCallfeb624a2010-11-23 20:48:44 +00001960static ExprResult
1961BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1962 const CXXScopeSpec &SS, FieldDecl *Field,
1963 DeclAccessPair FoundDecl,
1964 const DeclarationNameInfo &MemberNameInfo) {
1965 // x.a is an l-value if 'a' has a reference type. Otherwise:
1966 // x.a is an l-value/x-value/pr-value if the base is (and note
1967 // that *x is always an l-value), except that if the base isn't
1968 // an ordinary object then we must have an rvalue.
1969 ExprValueKind VK = VK_LValue;
1970 ExprObjectKind OK = OK_Ordinary;
1971 if (!IsArrow) {
1972 if (BaseExpr->getObjectKind() == OK_Ordinary)
1973 VK = BaseExpr->getValueKind();
1974 else
1975 VK = VK_RValue;
1976 }
1977 if (VK != VK_RValue && Field->isBitField())
1978 OK = OK_BitField;
1979
1980 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1981 QualType MemberType = Field->getType();
1982 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1983 MemberType = Ref->getPointeeType();
1984 VK = VK_LValue;
1985 } else {
1986 QualType BaseType = BaseExpr->getType();
1987 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1988
1989 Qualifiers BaseQuals = BaseType.getQualifiers();
1990
1991 // GC attributes are never picked up by members.
1992 BaseQuals.removeObjCGCAttr();
1993
1994 // CVR attributes from the base are picked up by members,
1995 // except that 'mutable' members don't pick up 'const'.
1996 if (Field->isMutable()) BaseQuals.removeConst();
1997
1998 Qualifiers MemberQuals
1999 = S.Context.getCanonicalType(MemberType).getQualifiers();
2000
2001 // TR 18037 does not allow fields to be declared with address spaces.
2002 assert(!MemberQuals.hasAddressSpace());
2003
2004 Qualifiers Combined = BaseQuals + MemberQuals;
2005 if (Combined != MemberQuals)
2006 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2007 }
2008
2009 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2010 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2011 FoundDecl, Field))
2012 return ExprError();
2013 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2014 Field, FoundDecl, MemberNameInfo,
2015 MemberType, VK, OK));
2016}
2017
John McCall2d74de92009-12-01 22:10:20 +00002018/// Builds an implicit member access expression. The current context
2019/// is known to be an instance method, and the given unqualified lookup
2020/// set is known to contain only instance members, at least one of which
2021/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002022ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002023Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2024 LookupResult &R,
2025 const TemplateArgumentListInfo *TemplateArgs,
2026 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002027 assert(!R.empty() && !R.isAmbiguous());
2028
John McCalld14a8642009-11-21 08:51:07 +00002029 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002030
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002031 // We may have found a field within an anonymous union or struct
2032 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00002033 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00002034 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002035 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
2036 return BuildAnonymousStructUnionMemberReference(Loc, FD);
2037
Sebastian Redlffbcf962009-01-18 18:53:16 +00002038
John McCall2d74de92009-12-01 22:10:20 +00002039 // If this is known to be an instance access, go ahead and build a
2040 // 'this' expression now.
John McCall87fe5d52010-05-20 01:18:31 +00002041 DeclContext *DC = getFunctionLevelDeclContext();
2042 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2d74de92009-12-01 22:10:20 +00002043 Expr *This = 0; // null signifies implicit access
2044 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002045 SourceLocation Loc = R.getNameLoc();
2046 if (SS.getRange().isValid())
2047 Loc = SS.getRange().getBegin();
2048 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002049 }
2050
John McCallb268a282010-08-23 23:25:46 +00002051 return BuildMemberReferenceExpr(This, ThisType,
John McCall2d74de92009-12-01 22:10:20 +00002052 /*OpLoc*/ SourceLocation(),
2053 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002054 SS,
2055 /*FirstQualifierInScope*/ 0,
2056 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002057}
2058
John McCalle66edc12009-11-24 19:00:30 +00002059bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002060 const LookupResult &R,
2061 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002062 // Only when used directly as the postfix-expression of a call.
2063 if (!HasTrailingLParen)
2064 return false;
2065
2066 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002067 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002068 return false;
2069
2070 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002071 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002072 return false;
2073
2074 // Turn off ADL when we find certain kinds of declarations during
2075 // normal lookup:
2076 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2077 NamedDecl *D = *I;
2078
2079 // C++0x [basic.lookup.argdep]p3:
2080 // -- a declaration of a class member
2081 // Since using decls preserve this property, we check this on the
2082 // original decl.
John McCall57500772009-12-16 12:17:52 +00002083 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002084 return false;
2085
2086 // C++0x [basic.lookup.argdep]p3:
2087 // -- a block-scope function declaration that is not a
2088 // using-declaration
2089 // NOTE: we also trigger this for function templates (in fact, we
2090 // don't check the decl type at all, since all other decl types
2091 // turn off ADL anyway).
2092 if (isa<UsingShadowDecl>(D))
2093 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2094 else if (D->getDeclContext()->isFunctionOrMethod())
2095 return false;
2096
2097 // C++0x [basic.lookup.argdep]p3:
2098 // -- a declaration that is neither a function or a function
2099 // template
2100 // And also for builtin functions.
2101 if (isa<FunctionDecl>(D)) {
2102 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2103
2104 // But also builtin functions.
2105 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2106 return false;
2107 } else if (!isa<FunctionTemplateDecl>(D))
2108 return false;
2109 }
2110
2111 return true;
2112}
2113
2114
John McCalld14a8642009-11-21 08:51:07 +00002115/// Diagnoses obvious problems with the use of the given declaration
2116/// as an expression. This is only actually called for lookups that
2117/// were not overloaded, and it doesn't promise that the declaration
2118/// will in fact be used.
2119static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2120 if (isa<TypedefDecl>(D)) {
2121 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2122 return true;
2123 }
2124
2125 if (isa<ObjCInterfaceDecl>(D)) {
2126 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2127 return true;
2128 }
2129
2130 if (isa<NamespaceDecl>(D)) {
2131 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2132 return true;
2133 }
2134
2135 return false;
2136}
2137
John McCalldadc5752010-08-24 06:29:42 +00002138ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002139Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002140 LookupResult &R,
2141 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002142 // If this is a single, fully-resolved result and we don't need ADL,
2143 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002144 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002145 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2146 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002147
2148 // We only need to check the declaration if there's exactly one
2149 // result, because in the overloaded case the results can only be
2150 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002151 if (R.isSingleResult() &&
2152 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002153 return ExprError();
2154
John McCall58cc69d2010-01-27 01:50:18 +00002155 // Otherwise, just build an unresolved lookup expression. Suppress
2156 // any lookup-related diagnostics; we'll hash these out later, when
2157 // we've picked a target.
2158 R.suppressDiagnostics();
2159
John McCalld14a8642009-11-21 08:51:07 +00002160 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002161 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00002162 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002163 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002164 NeedsADL, R.isOverloadedResult(),
2165 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002166
2167 return Owned(ULE);
2168}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002169
John McCall7decc9e2010-11-18 06:31:45 +00002170static ExprValueKind getValueKindForDecl(ASTContext &Context,
2171 const ValueDecl *D) {
John McCall4bc41ae2010-11-18 19:01:18 +00002172 // FIXME: It's not clear to me why NonTypeTemplateParmDecl is a VarDecl.
2173 if (isa<VarDecl>(D) && !isa<NonTypeTemplateParmDecl>(D)) return VK_LValue;
2174 if (isa<FieldDecl>(D)) return VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00002175 if (!Context.getLangOptions().CPlusPlus) return VK_RValue;
2176 if (isa<FunctionDecl>(D)) {
2177 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
2178 return VK_RValue;
2179 return VK_LValue;
2180 }
2181 return Expr::getValueKindForType(D->getType());
2182}
2183
John McCalld14a8642009-11-21 08:51:07 +00002184
2185/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002186ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002187Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002188 const DeclarationNameInfo &NameInfo,
2189 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002190 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002191 assert(!isa<FunctionTemplateDecl>(D) &&
2192 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002193
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002194 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002195 if (CheckDeclInExpr(*this, Loc, D))
2196 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002197
Douglas Gregore7488b92009-12-01 16:58:18 +00002198 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2199 // Specifically diagnose references to class templates that are missing
2200 // a template argument list.
2201 Diag(Loc, diag::err_template_decl_ref)
2202 << Template << SS.getRange();
2203 Diag(Template->getLocation(), diag::note_template_decl_here);
2204 return ExprError();
2205 }
2206
2207 // Make sure that we're referring to a value.
2208 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2209 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002210 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002211 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002212 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002213 return ExprError();
2214 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002215
Douglas Gregor171c45a2009-02-18 21:56:37 +00002216 // Check whether this declaration can be used. Note that we suppress
2217 // this check when we're going to perform argument-dependent lookup
2218 // on this function name, because this might not be the function
2219 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002220 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002221 return ExprError();
2222
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002223 // Only create DeclRefExpr's for valid Decl's.
2224 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002225 return ExprError();
2226
Francois Pichet783dd6e2010-11-21 06:08:52 +00002227 // Handle anonymous.
2228 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(VD))
2229 return BuildAnonymousStructUnionMemberReference(Loc, FD);
2230
John McCall7decc9e2010-11-18 06:31:45 +00002231 ExprValueKind VK = getValueKindForDecl(Context, VD);
2232
Chris Lattner2a9d9892008-10-20 05:16:36 +00002233 // If the identifier reference is inside a block, and it refers to a value
2234 // that is outside the block, create a BlockDeclRefExpr instead of a
2235 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2236 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002237 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002238 // We do not do this for things like enum constants, global variables, etc,
2239 // as they do not get snapshotted.
2240 //
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002241 if (getCurBlock() &&
Douglas Gregor9a28e842010-03-01 23:15:13 +00002242 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
Mike Stump7dafa0d2010-01-05 02:56:35 +00002243 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
2244 Diag(Loc, diag::err_ref_vm_type);
2245 Diag(D->getLocation(), diag::note_declared_at);
2246 return ExprError();
2247 }
2248
Fariborz Jahanianfa24e102010-03-16 23:39:51 +00002249 if (VD->getType()->isArrayType()) {
Mike Stump8971a862010-01-05 03:10:36 +00002250 Diag(Loc, diag::err_ref_array_type);
2251 Diag(D->getLocation(), diag::note_declared_at);
2252 return ExprError();
2253 }
2254
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00002255 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00002256 QualType ExprTy = VD->getType().getNonReferenceType();
John McCall7decc9e2010-11-18 06:31:45 +00002257
Steve Naroff1d95e5a2008-10-10 01:28:17 +00002258 // The BlocksAttr indicates the variable is bound by-reference.
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002259 bool byrefVar = (VD->getAttr<BlocksAttr>() != 0);
Fariborz Jahanian70c0b082010-07-12 17:26:57 +00002260 QualType T = VD->getType();
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002261 BlockDeclRefExpr *BDRE;
2262
2263 if (!byrefVar) {
2264 // This is to record that a 'const' was actually synthesize and added.
2265 bool constAdded = !ExprTy.isConstQualified();
2266 // Variable will be bound by-copy, make it const within the closure.
2267 ExprTy.addConst();
John McCall7decc9e2010-11-18 06:31:45 +00002268 BDRE = new (Context) BlockDeclRefExpr(VD, ExprTy, VK,
2269 Loc, false, constAdded);
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002270 }
2271 else
John McCall7decc9e2010-11-18 06:31:45 +00002272 BDRE = new (Context) BlockDeclRefExpr(VD, ExprTy, VK, Loc, true);
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002273
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002274 if (getLangOptions().CPlusPlus) {
2275 if (!T->isDependentType() && !T->isReferenceType()) {
2276 Expr *E = new (Context)
2277 DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T,
John McCall7decc9e2010-11-18 06:31:45 +00002278 VK, SourceLocation());
Fariborz Jahanian2a5deb52010-11-11 00:11:38 +00002279 if (T->getAs<RecordType>())
2280 if (!T->isUnionType()) {
2281 ExprResult Res = PerformCopyInitialization(
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002282 InitializedEntity::InitializeBlock(VD->getLocation(),
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002283 T, false),
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002284 SourceLocation(),
2285 Owned(E));
Fariborz Jahanian2a5deb52010-11-11 00:11:38 +00002286 if (!Res.isInvalid()) {
Douglas Gregora40433a2010-12-07 00:41:46 +00002287 Res = MaybeCreateExprWithCleanups(Res);
Fariborz Jahanian2a5deb52010-11-11 00:11:38 +00002288 Expr *Init = Res.takeAs<Expr>();
2289 BDRE->setCopyConstructorExpr(Init);
2290 }
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002291 }
Fariborz Jahanianea882cd2010-06-04 21:35:44 +00002292 }
2293 }
2294 return Owned(BDRE);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00002295 }
2296 // If this reference is not in a block or if the referenced variable is
2297 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00002298
John McCall7decc9e2010-11-18 06:31:45 +00002299 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002300 NameInfo, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00002301}
Chris Lattnere168f762006-11-10 05:29:30 +00002302
John McCalldadc5752010-08-24 06:29:42 +00002303ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlffbcf962009-01-18 18:53:16 +00002304 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002305 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002306
Chris Lattnere168f762006-11-10 05:29:30 +00002307 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002308 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002309 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2310 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2311 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002312 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002313
Chris Lattnera81a0272008-01-12 08:14:25 +00002314 // Pre-defined identifiers are of type char[x], where x is the length of the
2315 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002316
Anders Carlsson2fb08242009-09-08 18:24:21 +00002317 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002318 if (!currentDecl && getCurBlock())
2319 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002320 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002321 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002322 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002323 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002324
Anders Carlsson0b209a82009-09-11 01:22:35 +00002325 QualType ResTy;
2326 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2327 ResTy = Context.DependentTy;
2328 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002329 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002330
Anders Carlsson0b209a82009-09-11 01:22:35 +00002331 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002332 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002333 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2334 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002335 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002336}
2337
John McCalldadc5752010-08-24 06:29:42 +00002338ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002339 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002340 bool Invalid = false;
2341 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2342 if (Invalid)
2343 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002344
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002345 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2346 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002347 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002348 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002349
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002350 QualType Ty;
2351 if (!getLangOptions().CPlusPlus)
2352 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2353 else if (Literal.isWide())
2354 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002355 else if (Literal.isMultiChar())
2356 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002357 else
2358 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002359
Sebastian Redl20614a72009-01-20 22:23:13 +00002360 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2361 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002362 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002363}
2364
John McCalldadc5752010-08-24 06:29:42 +00002365ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002366 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002367 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2368 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002369 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002370 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002371 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002372 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002373 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002374
Chris Lattner23b7eb62007-06-15 23:05:46 +00002375 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002376 // Add padding so that NumericLiteralParser can overread by one character.
2377 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002378 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002379
Chris Lattner67ca9252007-05-21 01:08:44 +00002380 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002381 bool Invalid = false;
2382 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2383 if (Invalid)
2384 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002385
Mike Stump11289f42009-09-09 15:08:12 +00002386 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002387 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002388 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002389 return ExprError();
2390
Chris Lattner1c20a172007-08-26 03:42:43 +00002391 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002392
Chris Lattner1c20a172007-08-26 03:42:43 +00002393 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002394 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002395 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002396 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002397 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002398 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002399 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002400 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002401
2402 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2403
John McCall53b93a02009-12-24 09:08:04 +00002404 using llvm::APFloat;
2405 APFloat Val(Format);
2406
2407 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002408
2409 // Overflow is always an error, but underflow is only an error if
2410 // we underflowed to zero (APFloat reports denormals as underflow).
2411 if ((result & APFloat::opOverflow) ||
2412 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002413 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002414 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002415 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002416 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002417 APFloat::getLargest(Format).toString(buffer);
2418 } else {
John McCall62abc942010-02-26 23:35:57 +00002419 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002420 APFloat::getSmallest(Format).toString(buffer);
2421 }
2422
2423 Diag(Tok.getLocation(), diagnostic)
2424 << Ty
2425 << llvm::StringRef(buffer.data(), buffer.size());
2426 }
2427
2428 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002429 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002430
Peter Collingbourne0b69e1a2010-12-04 01:50:56 +00002431 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2432 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2433
Chris Lattner1c20a172007-08-26 03:42:43 +00002434 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002435 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002436 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002437 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002438
Neil Boothac582c52007-08-29 22:00:19 +00002439 // long long is a C99 feature.
2440 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002441 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002442 Diag(Tok.getLocation(), diag::ext_longlong);
2443
Chris Lattner67ca9252007-05-21 01:08:44 +00002444 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002445 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002446
Chris Lattner67ca9252007-05-21 01:08:44 +00002447 if (Literal.GetIntegerValue(ResultVal)) {
2448 // If this value didn't fit into uintmax_t, warn and force to ull.
2449 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002450 Ty = Context.UnsignedLongLongTy;
2451 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002452 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002453 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002454 // If this value fits into a ULL, try to figure out what else it fits into
2455 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002456
Chris Lattner67ca9252007-05-21 01:08:44 +00002457 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2458 // be an unsigned int.
2459 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2460
2461 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002462 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002463 if (!Literal.isLong && !Literal.isLongLong) {
2464 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002465 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002466
Chris Lattner67ca9252007-05-21 01:08:44 +00002467 // Does it fit in a unsigned int?
2468 if (ResultVal.isIntN(IntSize)) {
2469 // Does it fit in a signed int?
2470 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002471 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002472 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002473 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002474 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002475 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002476 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002477
Chris Lattner67ca9252007-05-21 01:08:44 +00002478 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002479 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002480 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002481
Chris Lattner67ca9252007-05-21 01:08:44 +00002482 // Does it fit in a unsigned long?
2483 if (ResultVal.isIntN(LongSize)) {
2484 // Does it fit in a signed long?
2485 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002486 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002487 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002488 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002489 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002490 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002491 }
2492
Chris Lattner67ca9252007-05-21 01:08:44 +00002493 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002494 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002495 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002496
Chris Lattner67ca9252007-05-21 01:08:44 +00002497 // Does it fit in a unsigned long long?
2498 if (ResultVal.isIntN(LongLongSize)) {
2499 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002500 // To be compatible with MSVC, hex integer literals ending with the
2501 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002502 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2503 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002504 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002505 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002506 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002507 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002508 }
2509 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002510
Chris Lattner67ca9252007-05-21 01:08:44 +00002511 // If we still couldn't decide a type, we probably have something that
2512 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002513 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002514 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002515 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002516 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002517 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002518
Chris Lattner55258cf2008-05-09 05:59:00 +00002519 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002520 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002521 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002522 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002523 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002524
Chris Lattner1c20a172007-08-26 03:42:43 +00002525 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2526 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002527 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002528 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002529
2530 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002531}
2532
John McCalldadc5752010-08-24 06:29:42 +00002533ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002534 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002535 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002536 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002537}
2538
Steve Naroff71b59a92007-06-04 22:22:31 +00002539/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002540/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002541bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00002542 SourceLocation OpLoc,
John McCall36e7fe32010-10-12 00:20:44 +00002543 SourceRange ExprRange,
Sebastian Redl6f282892008-11-11 17:56:53 +00002544 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002545 if (exprType->isDependentType())
2546 return false;
2547
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002548 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2549 // the result is the size of the referenced type."
2550 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2551 // result shall be the alignment of the referenced type."
2552 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2553 exprType = Ref->getPointeeType();
2554
Steve Naroff043d45d2007-05-15 02:32:35 +00002555 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002556 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002557 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002558 if (isSizeof)
2559 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2560 return false;
2561 }
Mike Stump11289f42009-09-09 15:08:12 +00002562
Chris Lattner62975a72009-04-24 00:30:45 +00002563 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002564 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002565 Diag(OpLoc, diag::ext_sizeof_void_type)
2566 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002567 return false;
2568 }
Mike Stump11289f42009-09-09 15:08:12 +00002569
Chris Lattner62975a72009-04-24 00:30:45 +00002570 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002571 PDiag(diag::err_sizeof_alignof_incomplete_type)
2572 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002573 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002574
Chris Lattner62975a72009-04-24 00:30:45 +00002575 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002576 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002577 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002578 << exprType << isSizeof << ExprRange;
2579 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002580 }
Mike Stump11289f42009-09-09 15:08:12 +00002581
Chris Lattner62975a72009-04-24 00:30:45 +00002582 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002583}
2584
John McCall36e7fe32010-10-12 00:20:44 +00002585static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2586 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002587 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002588
Mike Stump11289f42009-09-09 15:08:12 +00002589 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002590 if (isa<DeclRefExpr>(E))
2591 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002592
2593 // Cannot know anything else if the expression is dependent.
2594 if (E->isTypeDependent())
2595 return false;
2596
Douglas Gregor71235ec2009-05-02 02:18:30 +00002597 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00002598 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00002599 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002600 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002601
2602 // Alignment of a field access is always okay, so long as it isn't a
2603 // bit-field.
2604 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002605 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002606 return false;
2607
John McCall36e7fe32010-10-12 00:20:44 +00002608 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
Chris Lattner8dff0172009-01-24 20:17:12 +00002609}
2610
Douglas Gregor0950e412009-03-13 21:01:28 +00002611/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002612ExprResult
John McCallbcd03502009-12-07 02:54:59 +00002613Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00002614 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002615 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002616 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002617 return ExprError();
2618
John McCallbcd03502009-12-07 02:54:59 +00002619 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002620
Douglas Gregor0950e412009-03-13 21:01:28 +00002621 if (!T->isDependentType() &&
2622 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2623 return ExprError();
2624
2625 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00002626 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00002627 Context.getSizeType(), OpLoc,
2628 R.getEnd()));
2629}
2630
2631/// \brief Build a sizeof or alignof expression given an expression
2632/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002633ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00002634Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002635 bool isSizeOf, SourceRange R) {
2636 // Verify that the operand is valid.
2637 bool isInvalid = false;
2638 if (E->isTypeDependent()) {
2639 // Delay type-checking for type-dependent expressions.
2640 } else if (!isSizeOf) {
John McCall36e7fe32010-10-12 00:20:44 +00002641 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002642 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002643 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2644 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00002645 } else if (E->getType()->isPlaceholderType()) {
2646 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2647 if (PE.isInvalid()) return ExprError();
2648 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00002649 } else {
2650 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2651 }
2652
2653 if (isInvalid)
2654 return ExprError();
2655
2656 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2657 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2658 Context.getSizeType(), OpLoc,
2659 R.getEnd()));
2660}
2661
Sebastian Redl6f282892008-11-11 17:56:53 +00002662/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2663/// the same for @c alignof and @c __alignof
2664/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002665ExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00002666Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2667 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002668 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002669 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002670
Sebastian Redl6f282892008-11-11 17:56:53 +00002671 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002672 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002673 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
John McCallbcd03502009-12-07 02:54:59 +00002674 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002675 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002676
Douglas Gregor0950e412009-03-13 21:01:28 +00002677 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00002678 ExprResult Result
Douglas Gregor0950e412009-03-13 21:01:28 +00002679 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2680
Douglas Gregor0950e412009-03-13 21:01:28 +00002681 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002682}
2683
John McCall4bc41ae2010-11-18 19:01:18 +00002684static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2685 bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002686 if (V->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002687 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002688
John McCall34376a62010-12-04 03:47:34 +00002689 // _Real and _Imag are only l-values for normal l-values.
2690 if (V->getObjectKind() != OK_Ordinary)
John McCall27584242010-12-06 20:48:59 +00002691 S.DefaultLvalueConversion(V);
John McCall34376a62010-12-04 03:47:34 +00002692
Chris Lattnere267f5d2007-08-26 05:39:26 +00002693 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00002694 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002695 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002696
Chris Lattnere267f5d2007-08-26 05:39:26 +00002697 // Otherwise they pass through real integer and floating point types here.
2698 if (V->getType()->isArithmeticType())
2699 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002700
John McCall36226622010-10-12 02:09:17 +00002701 // Test for placeholders.
John McCall4bc41ae2010-11-18 19:01:18 +00002702 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall36226622010-10-12 02:09:17 +00002703 if (PR.isInvalid()) return QualType();
2704 if (PR.take() != V) {
2705 V = PR.take();
John McCall4bc41ae2010-11-18 19:01:18 +00002706 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002707 }
2708
Chris Lattnere267f5d2007-08-26 05:39:26 +00002709 // Reject anything else.
John McCall4bc41ae2010-11-18 19:01:18 +00002710 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002711 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002712 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002713}
2714
2715
Chris Lattnere168f762006-11-10 05:29:30 +00002716
John McCalldadc5752010-08-24 06:29:42 +00002717ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002718Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002719 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002720 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002721 switch (Kind) {
2722 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002723 case tok::plusplus: Opc = UO_PostInc; break;
2724 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002725 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002726
John McCallb268a282010-08-23 23:25:46 +00002727 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002728}
2729
John McCall4bc41ae2010-11-18 19:01:18 +00002730/// Expressions of certain arbitrary types are forbidden by C from
2731/// having l-value type. These are:
2732/// - 'void', but not qualified void
2733/// - function types
2734///
2735/// The exact rule here is C99 6.3.2.1:
2736/// An lvalue is an expression with an object type or an incomplete
2737/// type other than void.
2738static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2739 return ((T->isVoidType() && !T.hasQualifiers()) ||
2740 T->isFunctionType());
2741}
2742
John McCalldadc5752010-08-24 06:29:42 +00002743ExprResult
John McCallb268a282010-08-23 23:25:46 +00002744Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2745 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002746 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002747 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002748 if (Result.isInvalid()) return ExprError();
2749 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002750
John McCallb268a282010-08-23 23:25:46 +00002751 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002752
Douglas Gregor40412ac2008-11-19 17:17:41 +00002753 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002754 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002755 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002756 Context.DependentTy,
2757 VK_LValue, OK_Ordinary,
2758 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002759 }
2760
Mike Stump11289f42009-09-09 15:08:12 +00002761 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002762 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002763 LHSExp->getType()->isEnumeralType() ||
2764 RHSExp->getType()->isRecordType() ||
2765 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002766 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002767 }
2768
John McCallb268a282010-08-23 23:25:46 +00002769 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002770}
2771
2772
John McCalldadc5752010-08-24 06:29:42 +00002773ExprResult
John McCallb268a282010-08-23 23:25:46 +00002774Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2775 Expr *Idx, SourceLocation RLoc) {
2776 Expr *LHSExp = Base;
2777 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002778
Chris Lattner36d572b2007-07-16 00:14:47 +00002779 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002780 if (!LHSExp->getType()->getAs<VectorType>())
2781 DefaultFunctionArrayLvalueConversion(LHSExp);
2782 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002783
Chris Lattner36d572b2007-07-16 00:14:47 +00002784 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00002785 ExprValueKind VK = VK_LValue;
2786 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00002787
Steve Naroffc1aadb12007-03-28 21:49:40 +00002788 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002789 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002790 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002791 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002792 Expr *BaseExpr, *IndexExpr;
2793 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002794 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2795 BaseExpr = LHSExp;
2796 IndexExpr = RHSExp;
2797 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002798 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002799 BaseExpr = LHSExp;
2800 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002801 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002802 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002803 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002804 BaseExpr = RHSExp;
2805 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002806 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002807 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002808 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002809 BaseExpr = LHSExp;
2810 IndexExpr = RHSExp;
2811 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002812 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002813 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002814 // Handle the uncommon case of "123[Ptr]".
2815 BaseExpr = RHSExp;
2816 IndexExpr = LHSExp;
2817 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00002818 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00002819 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00002820 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00002821 VK = LHSExp->getValueKind();
2822 if (VK != VK_RValue)
2823 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00002824
Chris Lattner36d572b2007-07-16 00:14:47 +00002825 // FIXME: need to deal with const...
2826 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002827 } else if (LHSTy->isArrayType()) {
2828 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00002829 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00002830 // wasn't promoted because of the C90 rule that doesn't
2831 // allow promoting non-lvalue arrays. Warn, then
2832 // force the promotion here.
2833 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2834 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002835 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCalle3027922010-08-25 11:45:40 +00002836 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002837 LHSTy = LHSExp->getType();
2838
2839 BaseExpr = LHSExp;
2840 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002841 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002842 } else if (RHSTy->isArrayType()) {
2843 // Same as previous, except for 123[f().a] case
2844 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2845 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002846 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCalle3027922010-08-25 11:45:40 +00002847 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002848 RHSTy = RHSExp->getType();
2849
2850 BaseExpr = RHSExp;
2851 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002852 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00002853 } else {
Chris Lattner003af242009-04-25 22:50:55 +00002854 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2855 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002856 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00002857 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002858 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00002859 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2860 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00002861
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002862 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00002863 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2864 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00002865 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2866
Douglas Gregorac1fb652009-03-24 19:52:54 +00002867 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00002868 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2869 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00002870 // incomplete types are not object types.
2871 if (ResultType->isFunctionType()) {
2872 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2873 << ResultType << BaseExpr->getSourceRange();
2874 return ExprError();
2875 }
Mike Stump11289f42009-09-09 15:08:12 +00002876
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00002877 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
2878 // GNU extension: subscripting on pointer to void
2879 Diag(LLoc, diag::ext_gnu_void_ptr)
2880 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00002881
2882 // C forbids expressions of unqualified void type from being l-values.
2883 // See IsCForbiddenLValueType.
2884 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00002885 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00002886 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00002887 PDiag(diag::err_subscript_incomplete_type)
2888 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00002889 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002890
Chris Lattner62975a72009-04-24 00:30:45 +00002891 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00002892 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00002893 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2894 << ResultType << BaseExpr->getSourceRange();
2895 return ExprError();
2896 }
Mike Stump11289f42009-09-09 15:08:12 +00002897
John McCall4bc41ae2010-11-18 19:01:18 +00002898 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
2899 !IsCForbiddenLValueType(Context, ResultType));
2900
Mike Stump4e1f26a2009-02-19 03:04:26 +00002901 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002902 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00002903}
2904
John McCall4bc41ae2010-11-18 19:01:18 +00002905/// Check an ext-vector component access expression.
2906///
2907/// VK should be set in advance to the value kind of the base
2908/// expression.
2909static QualType
2910CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
2911 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00002912 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00002913 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2914 // see FIXME there.
2915 //
2916 // FIXME: This logic can be greatly simplified by splitting it along
2917 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00002918 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00002919
Steve Narofff8fd09e2007-07-27 22:15:19 +00002920 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002921 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002922
Mike Stump4e1f26a2009-02-19 03:04:26 +00002923 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00002924 // special names that indicate a subset of exactly half the elements are
2925 // to be selected.
2926 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002927
Nate Begemanbb70bf62009-01-18 01:47:54 +00002928 // This flag determines whether or not CompName has an 's' char prefix,
2929 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00002930 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00002931
John McCall4bc41ae2010-11-18 19:01:18 +00002932 bool HasRepeated = false;
2933 bool HasIndex[16] = {};
2934
2935 int Idx;
2936
Nate Begemanf322eab2008-05-09 06:41:27 +00002937 // Check that we've found one of the special components, or that the component
2938 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002939 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00002940 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2941 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00002942 } else if (!HexSwizzle &&
2943 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
2944 do {
2945 if (HasIndex[Idx]) HasRepeated = true;
2946 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00002947 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00002948 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
2949 } else {
2950 if (HexSwizzle) compStr++;
2951 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
2952 if (HasIndex[Idx]) HasRepeated = true;
2953 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00002954 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00002955 }
Chris Lattner7e152db2007-08-02 22:33:49 +00002956 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002957
Mike Stump4e1f26a2009-02-19 03:04:26 +00002958 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002959 // We didn't get to the end of the string. This means the component names
2960 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00002961 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00002962 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002963 return QualType();
2964 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002965
Nate Begemanbb70bf62009-01-18 01:47:54 +00002966 // Ensure no component accessor exceeds the width of the vector type it
2967 // operates on.
2968 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002969 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002970
2971 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002972 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002973
2974 while (*compStr) {
2975 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00002976 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00002977 << baseType << SourceRange(CompLoc);
2978 return QualType();
2979 }
2980 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002981 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002982
Steve Narofff8fd09e2007-07-27 22:15:19 +00002983 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002984 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002985 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002986 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002987 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00002988 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002989 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002990 if (HexSwizzle)
2991 CompSize--;
2992
Steve Narofff8fd09e2007-07-27 22:15:19 +00002993 if (CompSize == 1)
2994 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002995
John McCall4bc41ae2010-11-18 19:01:18 +00002996 if (HasRepeated) VK = VK_RValue;
2997
2998 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002999 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003000 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003001 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3002 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3003 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003004 }
3005 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003006}
3007
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003008static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003009 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003010 const Selector &Sel,
3011 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003012 if (Member)
3013 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3014 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003015 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003016 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003017
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003018 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3019 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003020 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3021 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003022 return D;
3023 }
3024 return 0;
3025}
3026
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003027static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3028 IdentifierInfo *Member,
3029 const Selector &Sel,
3030 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003031 // Check protocols on qualified interfaces.
3032 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003033 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003034 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003035 if (Member)
3036 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3037 GDecl = PD;
3038 break;
3039 }
3040 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003041 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003042 GDecl = OMD;
3043 break;
3044 }
3045 }
3046 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003047 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003048 E = QIdTy->qual_end(); I != E; ++I) {
3049 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003050 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3051 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003052 if (GDecl)
3053 return GDecl;
3054 }
3055 }
3056 return GDecl;
3057}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003058
John McCalldadc5752010-08-24 06:29:42 +00003059ExprResult
John McCallb268a282010-08-23 23:25:46 +00003060Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003061 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003062 const CXXScopeSpec &SS,
3063 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003064 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003065 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003066 // Even in dependent contexts, try to diagnose base expressions with
3067 // obviously wrong types, e.g.:
3068 //
3069 // T* t;
3070 // t.f;
3071 //
3072 // In Obj-C++, however, the above expression is valid, since it could be
3073 // accessing the 'f' property if T is an Obj-C interface. The extra check
3074 // allows this, while still reporting an error if T is a struct pointer.
3075 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003076 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003077 if (PT && (!getLangOptions().ObjC1 ||
3078 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003079 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003080 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003081 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003082 return ExprError();
3083 }
3084 }
3085
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003086 assert(BaseType->isDependentType() ||
3087 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003088 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003089
3090 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3091 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003092 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003093 IsArrow, OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003094 SS.getScopeRep(),
John McCall10eae182009-11-30 22:42:35 +00003095 SS.getRange(),
3096 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003097 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003098}
3099
3100/// We know that the given qualified member reference points only to
3101/// declarations which do not belong to the static type of the base
3102/// expression. Diagnose the problem.
3103static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3104 Expr *BaseExpr,
3105 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003106 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003107 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00003108 // If this is an implicit member access, use a different set of
3109 // diagnostics.
3110 if (!BaseExpr)
3111 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00003112
John McCall1e67dd62010-04-27 01:43:38 +00003113 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
3114 << SS.getRange() << R.getRepresentativeDecl() << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003115}
3116
3117// Check whether the declarations we found through a nested-name
3118// specifier in a member expression are actually members of the base
3119// type. The restriction here is:
3120//
3121// C++ [expr.ref]p2:
3122// ... In these cases, the id-expression shall name a
3123// member of the class or of one of its base classes.
3124//
3125// So it's perfectly legitimate for the nested-name specifier to name
3126// an unrelated class, and for us to find an overload set including
3127// decls from classes which are not superclasses, as long as the decl
3128// we actually pick through overload resolution is from a superclass.
3129bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3130 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003131 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003132 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003133 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3134 if (!BaseRT) {
3135 // We can't check this yet because the base type is still
3136 // dependent.
3137 assert(BaseType->isDependentType());
3138 return false;
3139 }
3140 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003141
3142 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003143 // If this is an implicit member reference and we find a
3144 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003145 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003146 return false;
John McCall10eae182009-11-30 22:42:35 +00003147
John McCall2d74de92009-12-01 22:10:20 +00003148 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003149 DeclContext *DC = (*I)->getDeclContext();
3150 while (DC->isTransparentContext())
3151 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003152
Douglas Gregora9c3e822010-07-28 22:27:52 +00003153 if (!DC->isRecord())
3154 continue;
3155
John McCall2d74de92009-12-01 22:10:20 +00003156 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003157 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003158
3159 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3160 return false;
3161 }
3162
John McCallcd4b4772009-12-02 03:53:29 +00003163 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00003164 return true;
3165}
3166
3167static bool
3168LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3169 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003170 SourceLocation OpLoc, CXXScopeSpec &SS,
3171 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003172 RecordDecl *RDecl = RTy->getDecl();
3173 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003174 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003175 << BaseRange))
3176 return true;
3177
John McCalle9cccd82010-06-16 08:42:20 +00003178 if (HasTemplateArgs) {
3179 // LookupTemplateName doesn't expect these both to exist simultaneously.
3180 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3181
3182 bool MOUS;
3183 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3184 return false;
3185 }
3186
John McCall2d74de92009-12-01 22:10:20 +00003187 DeclContext *DC = RDecl;
3188 if (SS.isSet()) {
3189 // If the member name was a qualified-id, look into the
3190 // nested-name-specifier.
3191 DC = SemaRef.computeDeclContext(SS, false);
3192
John McCall0b66eb32010-05-01 00:40:08 +00003193 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003194 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3195 << SS.getRange() << DC;
3196 return true;
3197 }
3198
John McCall2d74de92009-12-01 22:10:20 +00003199 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003200
John McCall2d74de92009-12-01 22:10:20 +00003201 if (!isa<TypeDecl>(DC)) {
3202 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3203 << DC << SS.getRange();
3204 return true;
John McCall10eae182009-11-30 22:42:35 +00003205 }
3206 }
3207
John McCall2d74de92009-12-01 22:10:20 +00003208 // The record definition is complete, now look up the member.
3209 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003210
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003211 if (!R.empty())
3212 return false;
3213
3214 // We didn't find anything with the given name, so try to correct
3215 // for typos.
3216 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003217 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003218 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003219 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3220 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3221 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003222 << FixItHint::CreateReplacement(R.getNameLoc(),
3223 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003224 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3225 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3226 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003227 return false;
3228 } else {
3229 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003230 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003231 }
3232
John McCall10eae182009-11-30 22:42:35 +00003233 return false;
3234}
3235
John McCalldadc5752010-08-24 06:29:42 +00003236ExprResult
John McCallb268a282010-08-23 23:25:46 +00003237Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003238 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003239 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003240 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003241 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003242 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003243 if (BaseType->isDependentType() ||
3244 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003245 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003246 IsArrow, OpLoc,
3247 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003248 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003249
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003250 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003251
John McCall2d74de92009-12-01 22:10:20 +00003252 // Implicit member accesses.
3253 if (!Base) {
3254 QualType RecordTy = BaseType;
3255 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3256 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3257 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003258 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003259 return ExprError();
3260
3261 // Explicit member accesses.
3262 } else {
John McCalldadc5752010-08-24 06:29:42 +00003263 ExprResult Result =
John McCall2d74de92009-12-01 22:10:20 +00003264 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003265 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003266
3267 if (Result.isInvalid()) {
3268 Owned(Base);
3269 return ExprError();
3270 }
3271
3272 if (Result.get())
3273 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003274
3275 // LookupMemberExpr can modify Base, and thus change BaseType
3276 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003277 }
3278
John McCallb268a282010-08-23 23:25:46 +00003279 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003280 OpLoc, IsArrow, SS, FirstQualifierInScope,
3281 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003282}
3283
John McCalldadc5752010-08-24 06:29:42 +00003284ExprResult
John McCallb268a282010-08-23 23:25:46 +00003285Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003286 SourceLocation OpLoc, bool IsArrow,
3287 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003288 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003289 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003290 const TemplateArgumentListInfo *TemplateArgs,
3291 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003292 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003293 if (IsArrow) {
3294 assert(BaseType->isPointerType());
3295 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3296 }
John McCalla8ae2222010-04-06 21:38:20 +00003297 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003298
John McCallb268a282010-08-23 23:25:46 +00003299 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003300 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3301 DeclarationName MemberName = MemberNameInfo.getName();
3302 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003303
3304 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003305 return ExprError();
3306
John McCall10eae182009-11-30 22:42:35 +00003307 if (R.empty()) {
3308 // Rederive where we looked up.
3309 DeclContext *DC = (SS.isSet()
3310 ? computeDeclContext(SS, false)
3311 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003312
John McCall10eae182009-11-30 22:42:35 +00003313 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003314 << MemberName << DC
3315 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003316 return ExprError();
3317 }
3318
John McCall38836f02010-01-15 08:34:02 +00003319 // Diagnose lookups that find only declarations from a non-base
3320 // type. This is possible for either qualified lookups (which may
3321 // have been qualified with an unrelated type) or implicit member
3322 // expressions (which were found with unqualified lookup and thus
3323 // may have come from an enclosing scope). Note that it's okay for
3324 // lookup to find declarations from a non-base type as long as those
3325 // aren't the ones picked by overload resolution.
3326 if ((SS.isSet() || !BaseExpr ||
3327 (isa<CXXThisExpr>(BaseExpr) &&
3328 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003329 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003330 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003331 return ExprError();
3332
3333 // Construct an unresolved result if we in fact got an unresolved
3334 // result.
3335 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003336 // Suppress any lookup-related diagnostics; we'll do these when we
3337 // pick a member.
3338 R.suppressDiagnostics();
3339
John McCall10eae182009-11-30 22:42:35 +00003340 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003341 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003342 BaseExpr, BaseExprType,
3343 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003344 Qualifier, SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003345 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003346 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003347
3348 return Owned(MemExpr);
3349 }
3350
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003351 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003352 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003353 NamedDecl *MemberDecl = R.getFoundDecl();
3354
3355 // FIXME: diagnose the presence of template arguments now.
3356
3357 // If the decl being referenced had an error, return an error for this
3358 // sub-expr without emitting another error, in order to avoid cascading
3359 // error cases.
3360 if (MemberDecl->isInvalidDecl())
3361 return ExprError();
3362
John McCall2d74de92009-12-01 22:10:20 +00003363 // Handle the implicit-member-access case.
3364 if (!BaseExpr) {
3365 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003366 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003367 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003368
Douglas Gregorb15af892010-01-07 23:12:05 +00003369 SourceLocation Loc = R.getNameLoc();
3370 if (SS.getRange().isValid())
3371 Loc = SS.getRange().getBegin();
3372 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003373 }
3374
John McCall10eae182009-11-30 22:42:35 +00003375 bool ShouldCheckUse = true;
3376 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3377 // Don't diagnose the use of a virtual member function unless it's
3378 // explicitly qualified.
3379 if (MD->isVirtual() && !SS.isSet())
3380 ShouldCheckUse = false;
3381 }
3382
3383 // Check the use of this member.
3384 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3385 Owned(BaseExpr);
3386 return ExprError();
3387 }
3388
John McCall34376a62010-12-04 03:47:34 +00003389 // Perform a property load on the base regardless of whether we
3390 // actually need it for the declaration.
3391 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3392 ConvertPropertyForRValue(BaseExpr);
3393
John McCallfeb624a2010-11-23 20:48:44 +00003394 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3395 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3396 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003397
Francois Pichet783dd6e2010-11-21 06:08:52 +00003398 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3399 // We may have found a field within an anonymous union or struct
3400 // (C++ [class.union]).
3401 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00003402 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003403
John McCall10eae182009-11-30 22:42:35 +00003404 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3405 MarkDeclarationReferenced(MemberLoc, Var);
3406 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003407 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003408 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003409 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003410 }
3411
John McCall7decc9e2010-11-18 06:31:45 +00003412 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall10eae182009-11-30 22:42:35 +00003413 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3414 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003415 MemberFn, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003416 MemberFn->getType(),
3417 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3418 OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003419 }
John McCall7decc9e2010-11-18 06:31:45 +00003420 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003421
3422 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3423 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3424 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003425 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003426 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003427 }
3428
3429 Owned(BaseExpr);
3430
Douglas Gregor861eb802010-04-25 20:55:08 +00003431 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003432 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003433 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003434 << MemberName << BaseType << int(IsArrow);
3435 else
3436 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3437 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003438
Douglas Gregor861eb802010-04-25 20:55:08 +00003439 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3440 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003441 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003442 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003443}
3444
John McCall68fc88ec2010-12-15 16:46:44 +00003445/// Given that normal member access failed on the given expression,
3446/// and given that the expression's type involves builtin-id or
3447/// builtin-Class, decide whether substituting in the redefinition
3448/// types would be profitable. The redefinition type is whatever
3449/// this translation unit tried to typedef to id/Class; we store
3450/// it to the side and then re-use it in places like this.
3451static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3452 const ObjCObjectPointerType *opty
3453 = base->getType()->getAs<ObjCObjectPointerType>();
3454 if (!opty) return false;
3455
3456 const ObjCObjectType *ty = opty->getObjectType();
3457
3458 QualType redef;
3459 if (ty->isObjCId()) {
3460 redef = S.Context.ObjCIdRedefinitionType;
3461 } else if (ty->isObjCClass()) {
3462 redef = S.Context.ObjCClassRedefinitionType;
3463 } else {
3464 return false;
3465 }
3466
3467 // Do the substitution as long as the redefinition type isn't just a
3468 // possibly-qualified pointer to builtin-id or builtin-Class again.
3469 opty = redef->getAs<ObjCObjectPointerType>();
3470 if (opty && !opty->getObjectType()->getInterface() != 0)
3471 return false;
3472
3473 S.ImpCastExprToType(base, redef, CK_BitCast);
3474 return true;
3475}
3476
John McCall10eae182009-11-30 22:42:35 +00003477/// Look up the given member of the given non-type-dependent
3478/// expression. This can return in one of two ways:
3479/// * If it returns a sentinel null-but-valid result, the caller will
3480/// assume that lookup was performed and the results written into
3481/// the provided structure. It will take over from there.
3482/// * Otherwise, the returned expression will be produced in place of
3483/// an ordinary member expression.
3484///
3485/// The ObjCImpDecl bit is a gross hack that will need to be properly
3486/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00003487ExprResult
John McCall10eae182009-11-30 22:42:35 +00003488Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00003489 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003490 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00003491 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003492 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00003493
Steve Naroffeaaae462007-12-16 21:42:28 +00003494 // Perform default conversions.
3495 DefaultFunctionArrayConversion(BaseExpr);
John McCall15317a22010-12-15 04:42:30 +00003496 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003497
Steve Naroff185616f2007-07-26 03:11:44 +00003498 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00003499 assert(!BaseType->isDependentType());
3500
3501 DeclarationName MemberName = R.getLookupName();
3502 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00003503
John McCall68fc88ec2010-12-15 16:46:44 +00003504 // For later type-checking purposes, turn arrow accesses into dot
3505 // accesses. The only access type we support that doesn't follow
3506 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3507 // and those never use arrows, so this is unaffected.
3508 if (IsArrow) {
3509 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3510 BaseType = Ptr->getPointeeType();
3511 else if (const ObjCObjectPointerType *Ptr
3512 = BaseType->getAs<ObjCObjectPointerType>())
3513 BaseType = Ptr->getPointeeType();
3514 else if (BaseType->isRecordType()) {
3515 // Recover from arrow accesses to records, e.g.:
3516 // struct MyRecord foo;
3517 // foo->bar
3518 // This is actually well-formed in C++ if MyRecord has an
3519 // overloaded operator->, but that should have been dealt with
3520 // by now.
3521 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3522 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3523 << FixItHint::CreateReplacement(OpLoc, ".");
3524 IsArrow = false;
3525 } else {
3526 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3527 << BaseType << BaseExpr->getSourceRange();
3528 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00003529 }
3530 }
3531
John McCall68fc88ec2010-12-15 16:46:44 +00003532 // Handle field access to simple records.
3533 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3534 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3535 RTy, OpLoc, SS, HasTemplateArgs))
3536 return ExprError();
3537
3538 // Returning valid-but-null is how we indicate to the caller that
3539 // the lookup result was filled in.
3540 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00003541 }
John McCall10eae182009-11-30 22:42:35 +00003542
John McCall68fc88ec2010-12-15 16:46:44 +00003543 // Handle ivar access to Objective-C objects.
3544 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003545 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00003546
3547 // There are three cases for the base type:
3548 // - builtin id (qualified or unqualified)
3549 // - builtin Class (qualified or unqualified)
3550 // - an interface
3551 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3552 if (!IDecl) {
3553 // There's an implicit 'isa' ivar on all objects.
3554 // But we only actually find it this way on objects of type 'id',
3555 // apparently.
3556 if (OTy->isObjCId() && Member->isStr("isa"))
3557 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3558 Context.getObjCClassType()));
3559
3560 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3561 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3562 ObjCImpDecl, HasTemplateArgs);
3563 goto fail;
3564 }
3565
3566 ObjCInterfaceDecl *ClassDeclared;
3567 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3568
3569 if (!IV) {
3570 // Attempt to correct for typos in ivar names.
3571 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3572 LookupMemberName);
3573 if (CorrectTypo(Res, 0, 0, IDecl, false,
3574 IsArrow ? CTC_ObjCIvarLookup
3575 : CTC_ObjCPropertyLookup) &&
3576 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3577 Diag(R.getNameLoc(),
3578 diag::err_typecheck_member_reference_ivar_suggest)
3579 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3580 << FixItHint::CreateReplacement(R.getNameLoc(),
3581 IV->getNameAsString());
3582 Diag(IV->getLocation(), diag::note_previous_decl)
3583 << IV->getDeclName();
3584 } else {
3585 Res.clear();
3586 Res.setLookupName(Member);
3587
3588 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3589 << IDecl->getDeclName() << MemberName
3590 << BaseExpr->getSourceRange();
3591 return ExprError();
3592 }
3593 }
3594
3595 // If the decl being referenced had an error, return an error for this
3596 // sub-expr without emitting another error, in order to avoid cascading
3597 // error cases.
3598 if (IV->isInvalidDecl())
3599 return ExprError();
3600
3601 // Check whether we can reference this field.
3602 if (DiagnoseUseOfDecl(IV, MemberLoc))
3603 return ExprError();
3604 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3605 IV->getAccessControl() != ObjCIvarDecl::Package) {
3606 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3607 if (ObjCMethodDecl *MD = getCurMethodDecl())
3608 ClassOfMethodDecl = MD->getClassInterface();
3609 else if (ObjCImpDecl && getCurFunctionDecl()) {
3610 // Case of a c-function declared inside an objc implementation.
3611 // FIXME: For a c-style function nested inside an objc implementation
3612 // class, there is no implementation context available, so we pass
3613 // down the context as argument to this routine. Ideally, this context
3614 // need be passed down in the AST node and somehow calculated from the
3615 // AST for a function decl.
3616 if (ObjCImplementationDecl *IMPD =
3617 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3618 ClassOfMethodDecl = IMPD->getClassInterface();
3619 else if (ObjCCategoryImplDecl* CatImplClass =
3620 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3621 ClassOfMethodDecl = CatImplClass->getClassInterface();
3622 }
3623
3624 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3625 if (ClassDeclared != IDecl ||
3626 ClassOfMethodDecl != ClassDeclared)
3627 Diag(MemberLoc, diag::error_private_ivar_access)
3628 << IV->getDeclName();
3629 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3630 // @protected
3631 Diag(MemberLoc, diag::error_protected_ivar_access)
3632 << IV->getDeclName();
3633 }
3634
3635 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3636 MemberLoc, BaseExpr,
3637 IsArrow));
3638 }
3639
3640 // Objective-C property access.
3641 const ObjCObjectPointerType *OPT;
3642 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3643 // This actually uses the base as an r-value.
3644 DefaultLvalueConversion(BaseExpr);
3645 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3646
3647 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3648
3649 const ObjCObjectType *OT = OPT->getObjectType();
3650
3651 // id, with and without qualifiers.
3652 if (OT->isObjCId()) {
3653 // Check protocols on qualified interfaces.
3654 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3655 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3656 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3657 // Check the use of this declaration
3658 if (DiagnoseUseOfDecl(PD, MemberLoc))
3659 return ExprError();
3660
3661 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3662 VK_LValue,
3663 OK_ObjCProperty,
3664 MemberLoc,
3665 BaseExpr));
3666 }
3667
3668 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3669 // Check the use of this method.
3670 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3671 return ExprError();
3672 Selector SetterSel =
3673 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3674 PP.getSelectorTable(), Member);
3675 ObjCMethodDecl *SMD = 0;
3676 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3677 SetterSel, Context))
3678 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3679 QualType PType = OMD->getSendResultType();
3680
3681 ExprValueKind VK = VK_LValue;
3682 if (!getLangOptions().CPlusPlus &&
3683 IsCForbiddenLValueType(Context, PType))
3684 VK = VK_RValue;
3685 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3686
3687 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3688 VK, OK,
3689 MemberLoc, BaseExpr));
3690 }
3691 }
3692
3693 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3694 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3695 ObjCImpDecl, HasTemplateArgs);
3696
3697 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3698 << MemberName << BaseType);
3699 }
3700
3701 // 'Class', unqualified only.
3702 if (OT->isObjCClass()) {
3703 // Only works in a method declaration (??!).
3704 ObjCMethodDecl *MD = getCurMethodDecl();
3705 if (!MD) {
3706 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3707 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3708 ObjCImpDecl, HasTemplateArgs);
3709
3710 goto fail;
3711 }
3712
3713 // Also must look for a getter name which uses property syntax.
3714 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003715 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3716 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003717 if ((Getter = IFace->lookupClassMethod(Sel))) {
3718 // Check the use of this method.
3719 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3720 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00003721 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003722 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003723 // If we found a getter then this may be a valid dot-reference, we
3724 // will look for the matching setter, in case it is needed.
3725 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00003726 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3727 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003728 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3729 if (!Setter) {
3730 // If this reference is in an @implementation, also check for 'private'
3731 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003732 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003733 }
3734 // Look through local category implementations associated with the class.
3735 if (!Setter)
3736 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003737
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003738 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3739 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003740
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003741 if (Getter || Setter) {
3742 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003743
John McCall4bc41ae2010-11-18 19:01:18 +00003744 ExprValueKind VK = VK_LValue;
3745 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00003746 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00003747 if (!getLangOptions().CPlusPlus &&
3748 IsCForbiddenLValueType(Context, PType))
3749 VK = VK_RValue;
3750 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003751 // Get the expression type from Setter's incoming parameter.
3752 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00003753 }
3754 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3755
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003756 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00003757 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3758 PType, VK, OK,
3759 MemberLoc, BaseExpr));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003760 }
John McCall68fc88ec2010-12-15 16:46:44 +00003761
3762 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3763 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3764 ObjCImpDecl, HasTemplateArgs);
3765
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003766 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00003767 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003768 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003769
John McCall68fc88ec2010-12-15 16:46:44 +00003770 // Normal property access.
3771 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3772 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003773 }
Alexis Huntc46382e2010-04-28 23:02:27 +00003774
Chris Lattnerb63a7452008-07-21 04:28:12 +00003775 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003776 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00003777 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00003778 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall15317a22010-12-15 04:42:30 +00003779 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00003780 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3781 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00003782 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003783 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00003784
3785 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3786 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003787 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003788
John McCall68fc88ec2010-12-15 16:46:44 +00003789 // Adjust builtin-sel to the appropriate redefinition type if that's
3790 // not just a pointer to builtin-sel again.
3791 if (IsArrow &&
3792 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
3793 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
3794 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
3795 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3796 ObjCImpDecl, HasTemplateArgs);
3797 }
3798
3799 // Failure cases.
3800 fail:
3801
3802 // There's a possible road to recovery for function types.
3803 const FunctionType *Fun = 0;
3804
3805 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
3806 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
3807 // fall out, handled below.
3808
3809 // Recover from dot accesses to pointers, e.g.:
3810 // type *foo;
3811 // foo.bar
3812 // This is actually well-formed in two cases:
3813 // - 'type' is an Objective C type
3814 // - 'bar' is a pseudo-destructor name which happens to refer to
3815 // the appropriate pointer type
3816 } else if (Ptr->getPointeeType()->isRecordType() &&
3817 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3818 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3819 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3820 << FixItHint::CreateReplacement(OpLoc, "->");
3821
3822 // Recurse as an -> access.
3823 IsArrow = true;
3824 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3825 ObjCImpDecl, HasTemplateArgs);
3826 }
3827 } else {
3828 Fun = BaseType->getAs<FunctionType>();
3829 }
3830
3831 // If the user is trying to apply -> or . to a function pointer
3832 // type, it's probably because they forgot parentheses to call that
3833 // function. Suggest the addition of those parentheses, build the
3834 // call, and continue on.
3835 if (Fun || BaseType == Context.OverloadTy) {
3836 bool TryCall;
3837 if (BaseType == Context.OverloadTy) {
3838 TryCall = true;
3839 } else {
3840 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
3841 TryCall = (FPT->getNumArgs() == 0);
3842 } else {
3843 TryCall = true;
3844 }
3845
3846 if (TryCall) {
3847 QualType ResultTy = Fun->getResultType();
3848 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
3849 (IsArrow && ResultTy->isPointerType() &&
3850 ResultTy->getAs<PointerType>()->getPointeeType()->isRecordType());
3851 }
3852 }
3853
3854
3855 if (TryCall) {
3856 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
3857 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
3858 << QualType(Fun, 0)
3859 << FixItHint::CreateInsertion(Loc, "()");
3860
3861 ExprResult NewBase
3862 = ActOnCallExpr(0, BaseExpr, Loc, MultiExprArg(*this, 0, 0), Loc);
3863 if (NewBase.isInvalid())
3864 return ExprError();
3865 BaseExpr = NewBase.takeAs<Expr>();
3866
3867
3868 DefaultFunctionArrayConversion(BaseExpr);
3869 BaseType = BaseExpr->getType();
3870
3871 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3872 ObjCImpDecl, HasTemplateArgs);
3873 }
3874 }
3875
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003876 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3877 << BaseType << BaseExpr->getSourceRange();
3878
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003879 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00003880}
3881
John McCall10eae182009-11-30 22:42:35 +00003882/// The main callback when the parser finds something like
3883/// expression . [nested-name-specifier] identifier
3884/// expression -> [nested-name-specifier] identifier
3885/// where 'identifier' encompasses a fairly broad spectrum of
3886/// possibilities, including destructor and operator references.
3887///
3888/// \param OpKind either tok::arrow or tok::period
3889/// \param HasTrailingLParen whether the next token is '(', which
3890/// is used to diagnose mis-uses of special members that can
3891/// only be called
3892/// \param ObjCImpDecl the current ObjC @implementation decl;
3893/// this is an ugly hack around the fact that ObjC @implementations
3894/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00003895ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00003896 SourceLocation OpLoc,
3897 tok::TokenKind OpKind,
3898 CXXScopeSpec &SS,
3899 UnqualifiedId &Id,
3900 Decl *ObjCImpDecl,
3901 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00003902 if (SS.isSet() && SS.isInvalid())
3903 return ExprError();
3904
Francois Pichet64225792011-01-18 05:04:39 +00003905 // Warn about the explicit constructor calls Microsoft extension.
3906 if (getLangOptions().Microsoft &&
3907 Id.getKind() == UnqualifiedId::IK_ConstructorName)
3908 Diag(Id.getSourceRange().getBegin(),
3909 diag::ext_ms_explicit_constructor_call);
3910
John McCall10eae182009-11-30 22:42:35 +00003911 TemplateArgumentListInfo TemplateArgsBuffer;
3912
3913 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003914 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00003915 const TemplateArgumentListInfo *TemplateArgs;
3916 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003917 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003918
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003919 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00003920 bool IsArrow = (OpKind == tok::arrow);
3921
3922 NamedDecl *FirstQualifierInScope
3923 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3924 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3925
3926 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003927 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003928 if (Result.isInvalid()) return ExprError();
3929 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00003930
Douglas Gregor41f90302010-04-12 20:54:26 +00003931 if (Base->getType()->isDependentType() || Name.isDependentName() ||
3932 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00003933 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00003934 IsArrow, OpLoc,
3935 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003936 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003937 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003938 LookupResult R(*this, NameInfo, LookupMemberName);
John McCalle9cccd82010-06-16 08:42:20 +00003939 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3940 SS, ObjCImpDecl, TemplateArgs != 0);
Alexis Huntc46382e2010-04-28 23:02:27 +00003941
John McCalle9cccd82010-06-16 08:42:20 +00003942 if (Result.isInvalid()) {
3943 Owned(Base);
3944 return ExprError();
3945 }
John McCall10eae182009-11-30 22:42:35 +00003946
John McCalle9cccd82010-06-16 08:42:20 +00003947 if (Result.get()) {
3948 // The only way a reference to a destructor can be used is to
3949 // immediately call it, which falls into this case. If the
3950 // next token is not a '(', produce a diagnostic and build the
3951 // call now.
3952 if (!HasTrailingLParen &&
3953 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00003954 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00003955
John McCalle9cccd82010-06-16 08:42:20 +00003956 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00003957 }
3958
John McCallb268a282010-08-23 23:25:46 +00003959 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00003960 OpLoc, IsArrow, SS, FirstQualifierInScope,
3961 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003962 }
3963
3964 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003965}
3966
John McCalldadc5752010-08-24 06:29:42 +00003967ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003968 FunctionDecl *FD,
3969 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003970 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003971 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003972 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003973 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003974 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003975 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003976 return ExprError();
3977 }
3978
3979 if (Param->hasUninstantiatedDefaultArg()) {
3980 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003981
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003982 // Instantiate the expression.
3983 MultiLevelTemplateArgumentList ArgList
3984 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003985
Nico Weber44887f62010-11-29 18:19:25 +00003986 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003987 = ArgList.getInnermost();
3988 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3989 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003990
Nico Weber44887f62010-11-29 18:19:25 +00003991 ExprResult Result;
3992 {
3993 // C++ [dcl.fct.default]p5:
3994 // The names in the [default argument] expression are bound, and
3995 // the semantic constraints are checked, at the point where the
3996 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003997 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003998 Result = SubstExpr(UninstExpr, ArgList);
3999 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004000 if (Result.isInvalid())
4001 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004002
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004003 // Check the expression as an initializer for the parameter.
4004 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004005 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004006 InitializationKind Kind
4007 = InitializationKind::CreateCopy(Param->getLocation(),
4008 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4009 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004010
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004011 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4012 Result = InitSeq.Perform(*this, Entity, Kind,
4013 MultiExprArg(*this, &ResultE, 1));
4014 if (Result.isInvalid())
4015 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004016
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004017 // Build the default argument expression.
4018 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4019 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004020 }
4021
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004022 // If the default expression creates temporaries, we need to
4023 // push them to the current stack of expression temporaries so they'll
4024 // be properly destroyed.
4025 // FIXME: We should really be rebuilding the default argument with new
4026 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004027 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4028 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4029 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4030 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4031 ExprTemporaries.push_back(Temporary);
4032 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004033
4034 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004035 // Just mark all of the declarations in this potentially-evaluated expression
4036 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004037 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004038 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004039}
4040
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004041/// ConvertArgumentsForCall - Converts the arguments specified in
4042/// Args/NumArgs to the parameter types of the function FDecl with
4043/// function prototype Proto. Call is the call expression itself, and
4044/// Fn is the function expression. For a C++ member function, this
4045/// routine does not attempt to convert the object argument. Returns
4046/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004047bool
4048Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004049 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004050 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004051 Expr **Args, unsigned NumArgs,
4052 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004053 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004054 // assignment, to the types of the corresponding parameter, ...
4055 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004056 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004057
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004058 // If too few arguments are available (and we don't have default
4059 // arguments for the remaining parameters), don't make the call.
4060 if (NumArgs < NumArgsInProto) {
4061 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4062 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004063 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004064 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004065 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004066 }
4067
4068 // If too many are passed and not variadic, error on the extras and drop
4069 // them.
4070 if (NumArgs > NumArgsInProto) {
4071 if (!Proto->isVariadic()) {
4072 Diag(Args[NumArgsInProto]->getLocStart(),
4073 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004074 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004075 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004076 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4077 Args[NumArgs-1]->getLocEnd());
4078 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004079 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004080 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004081 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004082 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004083 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004084 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004085 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4086 if (Fn->getType()->isBlockPointerType())
4087 CallType = VariadicBlock; // Block
4088 else if (isa<MemberExpr>(Fn))
4089 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004090 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004091 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004092 if (Invalid)
4093 return true;
4094 unsigned TotalNumArgs = AllArgs.size();
4095 for (unsigned i = 0; i < TotalNumArgs; ++i)
4096 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004097
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004098 return false;
4099}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004100
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004101bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4102 FunctionDecl *FDecl,
4103 const FunctionProtoType *Proto,
4104 unsigned FirstProtoArg,
4105 Expr **Args, unsigned NumArgs,
4106 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004107 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004108 unsigned NumArgsInProto = Proto->getNumArgs();
4109 unsigned NumArgsToCheck = NumArgs;
4110 bool Invalid = false;
4111 if (NumArgs != NumArgsInProto)
4112 // Use default arguments for missing arguments
4113 NumArgsToCheck = NumArgsInProto;
4114 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004115 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004116 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004117 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004118
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004119 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004120 if (ArgIx < NumArgs) {
4121 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004122
Eli Friedman3164fb12009-03-22 22:00:50 +00004123 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4124 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004125 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004126 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004127 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004128
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004129 // Pass the argument
4130 ParmVarDecl *Param = 0;
4131 if (FDecl && i < FDecl->getNumParams())
4132 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004133
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004134 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004135 Param? InitializedEntity::InitializeParameter(Context, Param)
4136 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004137 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004138 SourceLocation(),
4139 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004140 if (ArgE.isInvalid())
4141 return true;
4142
4143 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004144 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004145 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004146
John McCalldadc5752010-08-24 06:29:42 +00004147 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004148 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004149 if (ArgExpr.isInvalid())
4150 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004151
Anders Carlsson355933d2009-08-25 03:49:14 +00004152 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004153 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004154 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004155 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004156
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004157 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004158 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004159 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004160 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004161 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004162 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004163 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004164 }
4165 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004166 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004167}
4168
Steve Naroff83895f72007-09-16 03:34:24 +00004169/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004170/// This provides the location of the left/right parens and a list of comma
4171/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004172ExprResult
John McCallb268a282010-08-23 23:25:46 +00004173Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004174 MultiExprArg args, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004175 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004176
4177 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004178 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004179 if (Result.isInvalid()) return ExprError();
4180 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004181
John McCallb268a282010-08-23 23:25:46 +00004182 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004183
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004184 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004185 // If this is a pseudo-destructor expression, build the call immediately.
4186 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4187 if (NumArgs > 0) {
4188 // Pseudo-destructor calls should not have any arguments.
4189 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004190 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004191 SourceRange(Args[0]->getLocStart(),
4192 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004193
Douglas Gregorad8a3362009-09-04 17:36:40 +00004194 NumArgs = 0;
4195 }
Mike Stump11289f42009-09-09 15:08:12 +00004196
Douglas Gregorad8a3362009-09-04 17:36:40 +00004197 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004198 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004199 }
Mike Stump11289f42009-09-09 15:08:12 +00004200
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004201 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004202 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004203 // FIXME: Will need to cache the results of name lookup (including ADL) in
4204 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004205 bool Dependent = false;
4206 if (Fn->isTypeDependent())
4207 Dependent = true;
4208 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4209 Dependent = true;
4210
4211 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004212 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00004213 Context.DependentTy, VK_RValue,
4214 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004215
4216 // Determine whether this is a call to an object (C++ [over.call.object]).
4217 if (Fn->getType()->isRecordType())
4218 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004219 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004220
John McCall10eae182009-11-30 22:42:35 +00004221 Expr *NakedFn = Fn->IgnoreParens();
4222
4223 // Determine whether this is a call to an unresolved member function.
4224 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4225 // If lookup was unresolved but not dependent (i.e. didn't find
4226 // an unresolved using declaration), it has to be an overloaded
4227 // function set, which means it must contain either multiple
4228 // declarations (all methods or method templates) or a single
4229 // method template.
4230 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00004231 isa<FunctionTemplateDecl>(
4232 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00004233 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00004234
John McCall2d74de92009-12-01 22:10:20 +00004235 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004236 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004237 }
4238
Douglas Gregore254f902009-02-04 00:32:51 +00004239 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00004240 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004241 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00004242 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00004243 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004244 RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004245 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004246
Anders Carlsson61914b52009-10-03 17:40:22 +00004247 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00004248 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCalle3027922010-08-25 11:45:40 +00004249 if (BO->getOpcode() == BO_PtrMemD ||
4250 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00004251 if (const FunctionProtoType *FPT
4252 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004253 QualType ResultTy = FPT->getCallResultType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004254 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004255
John McCallb268a282010-08-23 23:25:46 +00004256 CXXMemberCallExpr *TheCall
Abramo Bagnara21e9d862010-12-03 21:39:42 +00004257 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCall7decc9e2010-11-18 06:31:45 +00004258 NumArgs, ResultTy, VK,
John McCallb268a282010-08-23 23:25:46 +00004259 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004260
4261 if (CheckCallReturnType(FPT->getResultType(),
4262 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00004263 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004264 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00004265
John McCallb268a282010-08-23 23:25:46 +00004266 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004267 RParenLoc))
4268 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00004269
John McCallb268a282010-08-23 23:25:46 +00004270 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004271 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004272 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004273 diag::err_typecheck_call_not_function)
4274 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00004275 }
4276 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004277 }
4278
Douglas Gregore254f902009-02-04 00:32:51 +00004279 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004280 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00004281 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004282
Eli Friedmane14b1992009-12-26 03:35:45 +00004283 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004284 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4285 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4286 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4287 RParenLoc);
4288 }
4289
John McCall57500772009-12-16 12:17:52 +00004290 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004291 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4292 if (UnOp->getOpcode() == UO_AddrOf)
4293 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4294
John McCall57500772009-12-16 12:17:52 +00004295 if (isa<DeclRefExpr>(NakedFn))
4296 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4297
John McCall2d74de92009-12-01 22:10:20 +00004298 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
4299}
4300
John McCall57500772009-12-16 12:17:52 +00004301/// BuildResolvedCallExpr - Build a call to a resolved expression,
4302/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004303/// unary-convert to an expression of function-pointer or
4304/// block-pointer type.
4305///
4306/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004307ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004308Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4309 SourceLocation LParenLoc,
4310 Expr **Args, unsigned NumArgs,
4311 SourceLocation RParenLoc) {
4312 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4313
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004314 // Promote the function operand.
4315 UsualUnaryConversions(Fn);
4316
Chris Lattner08464942007-12-28 05:29:59 +00004317 // Make the call expr early, before semantic checks. This guarantees cleanup
4318 // of arguments and function on error.
John McCallb268a282010-08-23 23:25:46 +00004319 CallExpr *TheCall = new (Context) CallExpr(Context, Fn,
4320 Args, NumArgs,
4321 Context.BoolTy,
John McCall7decc9e2010-11-18 06:31:45 +00004322 VK_RValue,
John McCallb268a282010-08-23 23:25:46 +00004323 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004324
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004325 const FunctionType *FuncT;
4326 if (!Fn->getType()->isBlockPointerType()) {
4327 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4328 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004329 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004330 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004331 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4332 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00004333 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004334 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004335 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00004336 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004337 }
Chris Lattner08464942007-12-28 05:29:59 +00004338 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004339 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4340 << Fn->getType() << Fn->getSourceRange());
4341
Eli Friedman3164fb12009-03-22 22:00:50 +00004342 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004343 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00004344 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004345 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004346 return ExprError();
4347
Chris Lattner08464942007-12-28 05:29:59 +00004348 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004349 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004350 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004351
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004352 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00004353 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004354 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004355 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004356 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004357 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004358
Douglas Gregord8e97de2009-04-02 15:37:10 +00004359 if (FDecl) {
4360 // Check if we have too few/too many template arguments, based
4361 // on our knowledge of the function definition.
4362 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004363 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004364 const FunctionProtoType *Proto
4365 = Def->getType()->getAs<FunctionProtoType>();
4366 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004367 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4368 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004369 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004370
4371 // If the function we're calling isn't a function prototype, but we have
4372 // a function prototype from a prior declaratiom, use that prototype.
4373 if (!FDecl->hasPrototype())
4374 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004375 }
4376
Steve Naroff0b661582007-08-28 23:30:39 +00004377 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004378 for (unsigned i = 0; i != NumArgs; i++) {
4379 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004380
4381 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004382 InitializedEntity Entity
4383 = InitializedEntity::InitializeParameter(Context,
4384 Proto->getArgType(i));
4385 ExprResult ArgE = PerformCopyInitialization(Entity,
4386 SourceLocation(),
4387 Owned(Arg));
4388 if (ArgE.isInvalid())
4389 return true;
4390
4391 Arg = ArgE.takeAs<Expr>();
4392
4393 } else {
4394 DefaultArgumentPromotion(Arg);
Douglas Gregor8e09a722010-10-25 20:39:23 +00004395 }
4396
Douglas Gregor83025412010-10-26 05:45:40 +00004397 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4398 Arg->getType(),
4399 PDiag(diag::err_call_incomplete_argument)
4400 << Arg->getSourceRange()))
4401 return ExprError();
4402
Chris Lattner08464942007-12-28 05:29:59 +00004403 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004404 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004405 }
Chris Lattner08464942007-12-28 05:29:59 +00004406
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004407 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4408 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004409 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4410 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004411
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004412 // Check for sentinels
4413 if (NDecl)
4414 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004415
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004416 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004417 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00004418 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004419 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004420
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004421 if (unsigned BuiltinID = FDecl->getBuiltinID())
4422 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004423 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00004424 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004425 return ExprError();
4426 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004427
John McCallb268a282010-08-23 23:25:46 +00004428 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004429}
4430
John McCalldadc5752010-08-24 06:29:42 +00004431ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004432Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004433 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004434 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004435 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004436 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004437
4438 TypeSourceInfo *TInfo;
4439 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4440 if (!TInfo)
4441 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4442
John McCallb268a282010-08-23 23:25:46 +00004443 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004444}
4445
John McCalldadc5752010-08-24 06:29:42 +00004446ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004447Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00004448 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004449 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004450
Eli Friedman37a186d2008-05-20 05:22:08 +00004451 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004452 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4453 PDiag(diag::err_illegal_decl_array_incomplete_type)
4454 << SourceRange(LParenLoc,
4455 literalExpr->getSourceRange().getEnd())))
4456 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004457 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004458 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4459 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004460 } else if (!literalType->isDependentType() &&
4461 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00004462 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00004463 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00004464 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004465 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004466
Douglas Gregor85dabae2009-12-16 01:38:02 +00004467 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004468 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004469 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004470 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004471 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004472 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004473 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004474 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004475 &literalType);
4476 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004477 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004478 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004479
Chris Lattner79413952008-12-04 23:50:19 +00004480 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004481 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00004482 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004483 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004484 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004485
John McCall7decc9e2010-11-18 06:31:45 +00004486 // In C, compound literals are l-values for some reason.
4487 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4488
John McCall5d7aa7f2010-01-19 22:33:45 +00004489 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00004490 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004491}
4492
John McCalldadc5752010-08-24 06:29:42 +00004493ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00004494Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004495 SourceLocation RBraceLoc) {
4496 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00004497 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004498
Steve Naroff30d242c2007-09-15 18:49:24 +00004499 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004500 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004501
Ted Kremenekac034612010-04-13 23:39:13 +00004502 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4503 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004504 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004505 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004506}
4507
John McCalld7646252010-11-14 08:17:51 +00004508/// Prepares for a scalar cast, performing all the necessary stages
4509/// except the final cast and returning the kind required.
4510static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4511 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4512 // Also, callers should have filtered out the invalid cases with
4513 // pointers. Everything else should be possible.
4514
Abramo Bagnaraba854972011-01-04 09:50:03 +00004515 QualType SrcTy = Src->getType();
John McCalld7646252010-11-14 08:17:51 +00004516 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004517 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004518
John McCall8cb679e2010-11-15 09:13:47 +00004519 switch (SrcTy->getScalarTypeKind()) {
4520 case Type::STK_MemberPointer:
4521 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004522
John McCall8cb679e2010-11-15 09:13:47 +00004523 case Type::STK_Pointer:
4524 switch (DestTy->getScalarTypeKind()) {
4525 case Type::STK_Pointer:
4526 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00004527 CK_AnyPointerToObjCPointerCast :
4528 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00004529 case Type::STK_Bool:
4530 return CK_PointerToBoolean;
4531 case Type::STK_Integral:
4532 return CK_PointerToIntegral;
4533 case Type::STK_Floating:
4534 case Type::STK_FloatingComplex:
4535 case Type::STK_IntegralComplex:
4536 case Type::STK_MemberPointer:
4537 llvm_unreachable("illegal cast from pointer");
4538 }
4539 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004540
John McCall8cb679e2010-11-15 09:13:47 +00004541 case Type::STK_Bool: // casting from bool is like casting from an integer
4542 case Type::STK_Integral:
4543 switch (DestTy->getScalarTypeKind()) {
4544 case Type::STK_Pointer:
John McCalld7646252010-11-14 08:17:51 +00004545 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004546 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004547 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004548 case Type::STK_Bool:
4549 return CK_IntegralToBoolean;
4550 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004551 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004552 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004553 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004554 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004555 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004556 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004557 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004558 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004559 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004560 CK_IntegralToFloating);
4561 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004562 case Type::STK_MemberPointer:
4563 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004564 }
4565 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004566
John McCall8cb679e2010-11-15 09:13:47 +00004567 case Type::STK_Floating:
4568 switch (DestTy->getScalarTypeKind()) {
4569 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004570 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004571 case Type::STK_Bool:
4572 return CK_FloatingToBoolean;
4573 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004574 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004575 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004576 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004577 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004578 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004579 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004580 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004581 CK_FloatingToIntegral);
4582 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004583 case Type::STK_Pointer:
4584 llvm_unreachable("valid float->pointer cast?");
4585 case Type::STK_MemberPointer:
4586 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004587 }
4588 break;
4589
John McCall8cb679e2010-11-15 09:13:47 +00004590 case Type::STK_FloatingComplex:
4591 switch (DestTy->getScalarTypeKind()) {
4592 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004593 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004594 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004595 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004596 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004597 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004598 if (S.Context.hasSameType(ET, DestTy))
4599 return CK_FloatingComplexToReal;
4600 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4601 return CK_FloatingCast;
4602 }
John McCall8cb679e2010-11-15 09:13:47 +00004603 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004604 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004605 case Type::STK_Integral:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004606 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004607 CK_FloatingComplexToReal);
4608 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004609 case Type::STK_Pointer:
4610 llvm_unreachable("valid complex float->pointer cast?");
4611 case Type::STK_MemberPointer:
4612 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004613 }
4614 break;
4615
John McCall8cb679e2010-11-15 09:13:47 +00004616 case Type::STK_IntegralComplex:
4617 switch (DestTy->getScalarTypeKind()) {
4618 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004619 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004620 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004621 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004622 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004623 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004624 if (S.Context.hasSameType(ET, DestTy))
4625 return CK_IntegralComplexToReal;
4626 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4627 return CK_IntegralCast;
4628 }
John McCall8cb679e2010-11-15 09:13:47 +00004629 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004630 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004631 case Type::STK_Floating:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004632 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004633 CK_IntegralComplexToReal);
4634 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004635 case Type::STK_Pointer:
4636 llvm_unreachable("valid complex int->pointer cast?");
4637 case Type::STK_MemberPointer:
4638 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004639 }
4640 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004641 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004642
John McCalld7646252010-11-14 08:17:51 +00004643 llvm_unreachable("Unhandled scalar cast");
4644 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00004645}
4646
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004647/// CheckCastTypes - Check type constraints for casting between types.
John McCall7decc9e2010-11-18 06:31:45 +00004648bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4649 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4650 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00004651 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00004652 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4653 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00004654 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00004655 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00004656
John McCall7decc9e2010-11-18 06:31:45 +00004657 // We only support r-value casts in C.
4658 VK = VK_RValue;
4659
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004660 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4661 // type needs to be scalar.
4662 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004663 // We don't necessarily do lvalue-to-rvalue conversions on this.
4664 IgnoredValueConversions(castExpr);
4665
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004666 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004667 Kind = CK_ToVoid;
Anders Carlssonef918ac2009-10-16 02:35:04 +00004668 return false;
4669 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004670
John McCall34376a62010-12-04 03:47:34 +00004671 DefaultFunctionArrayLvalueConversion(castExpr);
4672
Eli Friedmane98194d2010-07-17 20:43:49 +00004673 if (RequireCompleteType(TyR.getBegin(), castType,
4674 diag::err_typecheck_cast_to_incomplete))
4675 return true;
4676
Anders Carlssonef918ac2009-10-16 02:35:04 +00004677 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004678 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004679 (castType->isStructureType() || castType->isUnionType())) {
4680 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004681 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004682 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4683 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004684 Kind = CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00004685 return false;
4686 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004687
Anders Carlsson525b76b2009-10-16 02:48:28 +00004688 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004689 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004690 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004691 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004692 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004693 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004694 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004695 castExpr->getType()) &&
4696 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004697 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4698 << castExpr->getSourceRange();
4699 break;
4700 }
4701 }
4702 if (Field == FieldEnd)
4703 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4704 << castExpr->getType() << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004705 Kind = CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00004706 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004707 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004708
Anders Carlsson525b76b2009-10-16 02:48:28 +00004709 // Reject any other conversions to non-scalar types.
4710 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
4711 << castType << castExpr->getSourceRange();
4712 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004713
John McCalld7646252010-11-14 08:17:51 +00004714 // The type we're casting to is known to be a scalar or vector.
4715
4716 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004717 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00004718 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004719 return Diag(castExpr->getLocStart(),
4720 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004721 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004722 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004723
4724 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00004725 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004726
Anders Carlsson525b76b2009-10-16 02:48:28 +00004727 if (castType->isVectorType())
4728 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
4729 if (castExpr->getType()->isVectorType())
4730 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
4731
John McCalld7646252010-11-14 08:17:51 +00004732 // The source and target types are both scalars, i.e.
4733 // - arithmetic types (fundamental, enum, and complex)
4734 // - all kinds of pointers
4735 // Note that member pointers were filtered out with C++, above.
4736
Anders Carlsson43d70f82009-10-16 05:23:41 +00004737 if (isa<ObjCSelectorExpr>(castExpr))
4738 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004739
John McCalld7646252010-11-14 08:17:51 +00004740 // If either type is a pointer, the other type has to be either an
4741 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00004742 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004743 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00004744 if (!castExprType->isIntegralType(Context) &&
Douglas Gregorb90df602010-06-16 00:17:44 +00004745 castExprType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004746 return Diag(castExpr->getLocStart(),
4747 diag::err_cast_pointer_from_non_pointer_int)
4748 << castExprType << castExpr->getSourceRange();
4749 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004750 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004751 return Diag(castExpr->getLocStart(),
4752 diag::err_cast_pointer_to_non_pointer_int)
4753 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004754 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004755
John McCalld7646252010-11-14 08:17:51 +00004756 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCall2b5c1b22010-08-12 21:44:57 +00004757
John McCalld7646252010-11-14 08:17:51 +00004758 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004759 CheckCastAlign(castExpr, castType, TyR);
4760
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004761 return false;
4762}
4763
Anders Carlsson525b76b2009-10-16 02:48:28 +00004764bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004765 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004766 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004767
Anders Carlssonde71adf2007-11-27 05:51:55 +00004768 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004769 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004770 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004771 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004772 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004773 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004774 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004775 } else
4776 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004777 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004778 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004779
John McCalle3027922010-08-25 11:45:40 +00004780 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004781 return false;
4782}
4783
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004784bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCalle3027922010-08-25 11:45:40 +00004785 CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004786 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004787
Anders Carlsson43d70f82009-10-16 05:23:41 +00004788 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004789
Nate Begemanc8961a42009-06-27 22:05:55 +00004790 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4791 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004792 if (SrcTy->isVectorType()) {
4793 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
4794 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4795 << DestTy << SrcTy << R;
John McCalle3027922010-08-25 11:45:40 +00004796 Kind = CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00004797 return false;
4798 }
4799
Nate Begemanbd956c42009-06-28 02:36:38 +00004800 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004801 // conversion will take place first from scalar to elt type, and then
4802 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004803 if (SrcTy->isPointerType())
4804 return Diag(R.getBegin(),
4805 diag::err_invalid_conversion_between_vector_and_scalar)
4806 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004807
4808 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4809 ImpCastExprToType(CastExpr, DestElemTy,
John McCalld7646252010-11-14 08:17:51 +00004810 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004811
John McCalle3027922010-08-25 11:45:40 +00004812 Kind = CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00004813 return false;
4814}
4815
John McCalldadc5752010-08-24 06:29:42 +00004816ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004817Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004818 SourceLocation RParenLoc, Expr *castExpr) {
4819 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004820 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004821
John McCall97513962010-01-15 18:39:57 +00004822 TypeSourceInfo *castTInfo;
4823 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4824 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00004825 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00004826
Nate Begeman5ec4b312009-08-10 23:49:36 +00004827 // If the Expr being casted is a ParenListExpr, handle it specially.
4828 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00004829 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00004830 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00004831
John McCallb268a282010-08-23 23:25:46 +00004832 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004833}
4834
John McCalldadc5752010-08-24 06:29:42 +00004835ExprResult
John McCallebe54742010-01-15 18:56:44 +00004836Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004837 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004838 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004839 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004840 CXXCastPath BasePath;
John McCallebe54742010-01-15 18:56:44 +00004841 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCall7decc9e2010-11-18 06:31:45 +00004842 Kind, VK, BasePath))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004843 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00004844
John McCallcf142162010-08-07 06:22:56 +00004845 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +00004846 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00004847 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00004848 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004849}
4850
Nate Begeman5ec4b312009-08-10 23:49:36 +00004851/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4852/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004853ExprResult
John McCallb268a282010-08-23 23:25:46 +00004854Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004855 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4856 if (!E)
4857 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004858
John McCalldadc5752010-08-24 06:29:42 +00004859 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004860
Nate Begeman5ec4b312009-08-10 23:49:36 +00004861 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004862 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4863 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004864
John McCallb268a282010-08-23 23:25:46 +00004865 if (Result.isInvalid()) return ExprError();
4866
4867 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004868}
4869
John McCalldadc5752010-08-24 06:29:42 +00004870ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00004871Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00004872 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00004873 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00004874 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00004875 QualType Ty = TInfo->getType();
John Thompson781ad172010-06-30 22:55:51 +00004876 bool isAltiVecLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00004877
John Thompson781ad172010-06-30 22:55:51 +00004878 // Check for an altivec literal,
4879 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004880 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4881 if (PE->getNumExprs() == 0) {
4882 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4883 return ExprError();
4884 }
John Thompson781ad172010-06-30 22:55:51 +00004885 if (PE->getNumExprs() == 1) {
4886 if (!PE->getExpr(0)->getType()->isVectorType())
4887 isAltiVecLiteral = true;
4888 }
4889 else
4890 isAltiVecLiteral = true;
4891 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004892
John Thompson781ad172010-06-30 22:55:51 +00004893 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
4894 // then handle it as such.
4895 if (isAltiVecLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004896 llvm::SmallVector<Expr *, 8> initExprs;
4897 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4898 initExprs.push_back(PE->getExpr(i));
4899
4900 // FIXME: This means that pretty-printing the final AST will produce curly
4901 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00004902 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4903 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00004904 initExprs.size(), RParenLoc);
4905 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00004906 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004907 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004908 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00004909 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00004910 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00004911 if (Result.isInvalid()) return ExprError();
4912 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004913 }
4914}
4915
John McCalldadc5752010-08-24 06:29:42 +00004916ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004917 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004918 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00004919 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004920 unsigned nexprs = Val.size();
4921 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004922 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4923 Expr *expr;
4924 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4925 expr = new (Context) ParenExpr(L, R, exprs[0]);
4926 else
4927 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004928 return Owned(expr);
4929}
4930
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004931/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4932/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004933/// C99 6.5.15
4934QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall7decc9e2010-11-18 06:31:45 +00004935 Expr *&SAVE, ExprValueKind &VK,
John McCall4bc41ae2010-11-18 19:01:18 +00004936 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004937 SourceLocation QuestionLoc) {
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004938 // If both LHS and RHS are overloaded functions, try to resolve them.
4939 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
4940 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
4941 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
4942 if (LHSResult.isInvalid())
4943 return QualType();
4944
4945 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
4946 if (RHSResult.isInvalid())
4947 return QualType();
4948
4949 LHS = LHSResult.take();
4950 RHS = RHSResult.take();
4951 }
4952
Sebastian Redl1a99f442009-04-16 17:51:27 +00004953 // C++ is sufficiently different to merit its own checker.
4954 if (getLangOptions().CPlusPlus)
John McCall4bc41ae2010-11-18 19:01:18 +00004955 return CXXCheckConditionalOperands(Cond, LHS, RHS, SAVE,
4956 VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004957
4958 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004959 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004960
Chris Lattner432cff52009-02-18 04:28:32 +00004961 UsualUnaryConversions(Cond);
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00004962 if (SAVE) {
4963 SAVE = LHS = Cond;
4964 }
4965 else
4966 UsualUnaryConversions(LHS);
Chris Lattner432cff52009-02-18 04:28:32 +00004967 UsualUnaryConversions(RHS);
4968 QualType CondTy = Cond->getType();
4969 QualType LHSTy = LHS->getType();
4970 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004971
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004972 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004973 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00004974 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4975 // Throw an error if its not either.
4976 if (getLangOptions().OpenCL) {
4977 if (!CondTy->isVectorType()) {
4978 Diag(Cond->getLocStart(),
4979 diag::err_typecheck_cond_expect_scalar_or_vector)
4980 << CondTy;
4981 return QualType();
4982 }
4983 }
4984 else {
4985 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4986 << CondTy;
4987 return QualType();
4988 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004989 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004990
Chris Lattnere2949f42008-01-06 22:42:25 +00004991 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004992 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4993 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00004994
Nate Begemanabb5a732010-09-20 22:41:17 +00004995 // OpenCL: If the condition is a vector, and both operands are scalar,
4996 // attempt to implicity convert them to the vector type to act like the
4997 // built in select.
4998 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4999 // Both operands should be of scalar type.
5000 if (!LHSTy->isScalarType()) {
5001 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5002 << CondTy;
5003 return QualType();
5004 }
5005 if (!RHSTy->isScalarType()) {
5006 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5007 << CondTy;
5008 return QualType();
5009 }
5010 // Implicity convert these scalars to the type of the condition.
5011 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5012 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5013 }
5014
Chris Lattnere2949f42008-01-06 22:42:25 +00005015 // If both operands have arithmetic type, do the usual arithmetic conversions
5016 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005017 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5018 UsualArithmeticConversions(LHS, RHS);
5019 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005020 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005021
Chris Lattnere2949f42008-01-06 22:42:25 +00005022 // If both operands are the same structure or union type, the result is that
5023 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005024 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5025 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005026 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005027 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005028 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005029 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005030 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005031 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005032
Chris Lattnere2949f42008-01-06 22:42:25 +00005033 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005034 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005035 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5036 if (!LHSTy->isVoidType())
5037 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5038 << RHS->getSourceRange();
5039 if (!RHSTy->isVoidType())
5040 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5041 << LHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005042 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5043 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005044 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005045 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005046 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5047 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005048 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005049 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005050 // promote the null to a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005051 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005052 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005053 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005054 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005055 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00005056 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005057 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005058 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005059
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005060 // All objective-c pointer type analysis is done here.
5061 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5062 QuestionLoc);
5063 if (!compositeType.isNull())
5064 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005065
5066
Steve Naroff05efa972009-07-01 14:36:47 +00005067 // Handle block pointer types.
5068 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5069 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5070 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5071 QualType destType = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005072 ImpCastExprToType(LHS, destType, CK_BitCast);
5073 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005074 return destType;
5075 }
5076 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005077 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005078 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005079 }
Steve Naroff05efa972009-07-01 14:36:47 +00005080 // We have 2 block pointer types.
5081 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5082 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005083 return LHSTy;
5084 }
Steve Naroff05efa972009-07-01 14:36:47 +00005085 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005086 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5087 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005088
Steve Naroff05efa972009-07-01 14:36:47 +00005089 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5090 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005091 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005092 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005093 // In this situation, we assume void* type. No especially good
5094 // reason, but this is what gcc does, and we do have to pick
5095 // to get a consistent AST.
5096 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005097 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5098 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005099 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005100 }
Steve Naroff05efa972009-07-01 14:36:47 +00005101 // The block pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005102 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5103 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005104 return LHSTy;
5105 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005106
Steve Naroff05efa972009-07-01 14:36:47 +00005107 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5108 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5109 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005110 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5111 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005112
5113 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5114 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5115 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005116 QualType destPointee
5117 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005118 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005119 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005120 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005121 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005122 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005123 return destType;
5124 }
5125 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005126 QualType destPointee
5127 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005128 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005129 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005130 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005131 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005132 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005133 return destType;
5134 }
5135
5136 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5137 // Two identical pointer types are always compatible.
5138 return LHSTy;
5139 }
5140 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5141 rhptee.getUnqualifiedType())) {
5142 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5143 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5144 // In this situation, we assume void* type. No especially good
5145 // reason, but this is what gcc does, and we do have to pick
5146 // to get a consistent AST.
5147 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005148 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5149 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005150 return incompatTy;
5151 }
5152 // The pointer types are compatible.
5153 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5154 // differently qualified versions of compatible types, the result type is
5155 // a pointer to an appropriately qualified version of the *composite*
5156 // type.
5157 // FIXME: Need to calculate the composite type.
5158 // FIXME: Need to add qualifiers
John McCalle3027922010-08-25 11:45:40 +00005159 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5160 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005161 return LHSTy;
5162 }
Mike Stump11289f42009-09-09 15:08:12 +00005163
John McCalle84af4e2010-11-13 01:35:44 +00005164 // GCC compatibility: soften pointer/integer mismatch. Note that
5165 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005166 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5167 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5168 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005169 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005170 return RHSTy;
5171 }
5172 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5173 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5174 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005175 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005176 return LHSTy;
5177 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005178
Chris Lattnere2949f42008-01-06 22:42:25 +00005179 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005180 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5181 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005182 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005183}
5184
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005185/// FindCompositeObjCPointerType - Helper method to find composite type of
5186/// two objective-c pointer types of the two input expressions.
5187QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5188 SourceLocation QuestionLoc) {
5189 QualType LHSTy = LHS->getType();
5190 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005191
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005192 // Handle things like Class and struct objc_class*. Here we case the result
5193 // to the pseudo-builtin, because that will be implicitly cast back to the
5194 // redefinition type if an attempt is made to access its fields.
5195 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005196 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005197 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005198 return LHSTy;
5199 }
5200 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005201 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005202 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005203 return RHSTy;
5204 }
5205 // And the same for struct objc_object* / id
5206 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005207 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005208 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005209 return LHSTy;
5210 }
5211 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005212 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005213 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005214 return RHSTy;
5215 }
5216 // And the same for struct objc_selector* / SEL
5217 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005218 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005219 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005220 return LHSTy;
5221 }
5222 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005223 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005224 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005225 return RHSTy;
5226 }
5227 // Check constraints for Objective-C object pointers types.
5228 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005229
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005230 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5231 // Two identical object pointer types are always compatible.
5232 return LHSTy;
5233 }
5234 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5235 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5236 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005237
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005238 // If both operands are interfaces and either operand can be
5239 // assigned to the other, use that type as the composite
5240 // type. This allows
5241 // xxx ? (A*) a : (B*) b
5242 // where B is a subclass of A.
5243 //
5244 // Additionally, as for assignment, if either type is 'id'
5245 // allow silent coercion. Finally, if the types are
5246 // incompatible then make sure to use 'id' as the composite
5247 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005248
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005249 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5250 // It could return the composite type.
5251 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5252 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5253 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5254 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5255 } else if ((LHSTy->isObjCQualifiedIdType() ||
5256 RHSTy->isObjCQualifiedIdType()) &&
5257 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5258 // Need to handle "id<xx>" explicitly.
5259 // GCC allows qualified id and any Objective-C type to devolve to
5260 // id. Currently localizing to here until clear this should be
5261 // part of ObjCQualifiedIdTypesAreCompatible.
5262 compositeType = Context.getObjCIdType();
5263 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5264 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005265 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005266 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5267 ;
5268 else {
5269 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5270 << LHSTy << RHSTy
5271 << LHS->getSourceRange() << RHS->getSourceRange();
5272 QualType incompatTy = Context.getObjCIdType();
John McCalle3027922010-08-25 11:45:40 +00005273 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5274 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005275 return incompatTy;
5276 }
5277 // The object pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005278 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5279 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005280 return compositeType;
5281 }
5282 // Check Objective-C object pointer types and 'void *'
5283 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5284 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5285 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5286 QualType destPointee
5287 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5288 QualType destType = Context.getPointerType(destPointee);
5289 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005290 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005291 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005292 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005293 return destType;
5294 }
5295 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5296 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5297 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5298 QualType destPointee
5299 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5300 QualType destType = Context.getPointerType(destPointee);
5301 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005302 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005303 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005304 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005305 return destType;
5306 }
5307 return QualType();
5308}
5309
Steve Naroff83895f72007-09-16 03:34:24 +00005310/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005311/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005312ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005313 SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +00005314 Expr *CondExpr, Expr *LHSExpr,
5315 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005316 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5317 // was the condition.
5318 bool isLHSNull = LHSExpr == 0;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005319 Expr *SAVEExpr = 0;
5320 if (isLHSNull) {
5321 LHSExpr = SAVEExpr = CondExpr;
5322 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005323
John McCall7decc9e2010-11-18 06:31:45 +00005324 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005325 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00005326 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCall4bc41ae2010-11-18 19:01:18 +00005327 SAVEExpr, VK, OK, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00005328 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005329 return ExprError();
5330
Douglas Gregor7e112b02009-08-26 14:37:04 +00005331 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005332 LHSExpr, ColonLoc,
5333 RHSExpr, SAVEExpr,
John McCall4bc41ae2010-11-18 19:01:18 +00005334 result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005335}
5336
Steve Naroff3f597292007-05-11 22:18:03 +00005337// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005338// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005339// routine is it effectively iqnores the qualifiers on the top level pointee.
5340// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5341// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005342Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00005343Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00005344 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005345
David Chisnall9f57c292009-08-17 16:35:33 +00005346 if ((lhsType->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005347 (Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType))) ||
David Chisnall9f57c292009-08-17 16:35:33 +00005348 (rhsType->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005349 (Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)))) {
David Chisnall9f57c292009-08-17 16:35:33 +00005350 return Compatible;
5351 }
5352
Steve Naroff1f4d7272007-05-11 04:00:31 +00005353 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005354 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
5355 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005356
Steve Naroff1f4d7272007-05-11 04:00:31 +00005357 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00005358 lhptee = Context.getCanonicalType(lhptee);
5359 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00005360
Chris Lattner9bad62c2008-01-04 18:04:52 +00005361 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005362
5363 // C99 6.5.16.1p1: This following citation is common to constraints
5364 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5365 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00005366 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00005367 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00005368 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00005369
Mike Stump4e1f26a2009-02-19 03:04:26 +00005370 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5371 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005372 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005373 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005374 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005375 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005376
Chris Lattner0a788432008-01-03 22:56:36 +00005377 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005378 assert(rhptee->isFunctionType());
5379 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005380 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005381
Chris Lattner0a788432008-01-03 22:56:36 +00005382 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005383 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005384 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005385
5386 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005387 assert(lhptee->isFunctionType());
5388 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005389 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005390 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005391 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00005392 lhptee = lhptee.getUnqualifiedType();
5393 rhptee = rhptee.getUnqualifiedType();
5394 if (!Context.typesAreCompatible(lhptee, rhptee)) {
5395 // Check if the pointee types are compatible ignoring the sign.
5396 // We explicitly check for char so that we catch "char" vs
5397 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005398 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00005399 lhptee = Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005400 else if (lhptee->hasSignedIntegerRepresentation())
Eli Friedman80160bd2009-03-22 23:59:44 +00005401 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005402
Chris Lattnerec3a1562009-10-17 20:33:28 +00005403 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00005404 rhptee = Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005405 else if (rhptee->hasSignedIntegerRepresentation())
Eli Friedman80160bd2009-03-22 23:59:44 +00005406 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005407
Eli Friedman80160bd2009-03-22 23:59:44 +00005408 if (lhptee == rhptee) {
5409 // Types are compatible ignoring the sign. Qualifier incompatibility
5410 // takes priority over sign incompatibility because the sign
5411 // warning can be disabled.
5412 if (ConvTy != Compatible)
5413 return ConvTy;
5414 return IncompatiblePointerSign;
5415 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005416
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005417 // If we are a multi-level pointer, it's possible that our issue is simply
5418 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5419 // the eventual target type is the same and the pointers have the same
5420 // level of indirection, this must be the issue.
5421 if (lhptee->isPointerType() && rhptee->isPointerType()) {
5422 do {
5423 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
5424 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005425
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005426 lhptee = Context.getCanonicalType(lhptee);
5427 rhptee = Context.getCanonicalType(rhptee);
5428 } while (lhptee->isPointerType() && rhptee->isPointerType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005429
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005430 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00005431 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005432 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005433
Eli Friedman80160bd2009-03-22 23:59:44 +00005434 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00005435 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005436 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005437 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005438}
5439
Steve Naroff081c7422008-09-04 15:10:53 +00005440/// CheckBlockPointerTypesForAssignment - This routine determines whether two
5441/// block pointer types are compatible or whether a block and normal pointer
5442/// are compatible. It is more restrict than comparing two function pointer
5443// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005444Sema::AssignConvertType
5445Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00005446 QualType rhsType) {
5447 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005448
Steve Naroff081c7422008-09-04 15:10:53 +00005449 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005450 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
5451 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005452
Steve Naroff081c7422008-09-04 15:10:53 +00005453 // make sure we operate on the canonical type
5454 lhptee = Context.getCanonicalType(lhptee);
5455 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005456
Steve Naroff081c7422008-09-04 15:10:53 +00005457 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005458
Steve Naroff081c7422008-09-04 15:10:53 +00005459 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005460 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00005461 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005462
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005463 if (!getLangOptions().CPlusPlus) {
5464 if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5465 return IncompatibleBlockPointer;
5466 }
5467 else if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00005468 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00005469 return ConvTy;
5470}
5471
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005472/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
5473/// for assignment compatibility.
5474Sema::AssignConvertType
5475Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005476 if (lhsType->isObjCBuiltinType()) {
5477 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005478 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5479 !rhsType->isObjCQualifiedClassType())
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005480 return IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005481 return Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005482 }
5483 if (rhsType->isObjCBuiltinType()) {
5484 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005485 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5486 !lhsType->isObjCQualifiedClassType())
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005487 return IncompatiblePointer;
5488 return Compatible;
5489 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005490 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005491 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005492 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005493 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
5494 // make sure we operate on the canonical type
5495 lhptee = Context.getCanonicalType(lhptee);
5496 rhptee = Context.getCanonicalType(rhptee);
5497 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5498 return CompatiblePointerDiscardsQualifiers;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005499
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005500 if (Context.typesAreCompatible(lhsType, rhsType))
5501 return Compatible;
5502 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
5503 return IncompatibleObjCQualifiedId;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005504 return IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005505}
5506
John McCall29600e12010-11-16 02:32:08 +00005507Sema::AssignConvertType
5508Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
5509 // Fake up an opaque expression. We don't actually care about what
5510 // cast operations are required, so if CheckAssignmentConstraints
5511 // adds casts to this they'll be wasted, but fortunately that doesn't
5512 // usually happen on valid code.
5513 OpaqueValueExpr rhs(rhsType, VK_RValue);
5514 Expr *rhsPtr = &rhs;
5515 CastKind K = CK_Invalid;
5516
5517 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5518}
5519
Mike Stump4e1f26a2009-02-19 03:04:26 +00005520/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5521/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005522/// pointers. Here are some objectionable examples that GCC considers warnings:
5523///
5524/// int a, *pint;
5525/// short *pshort;
5526/// struct foo *pfoo;
5527///
5528/// pint = pshort; // warning: assignment from incompatible pointer type
5529/// a = pint; // warning: assignment makes integer from pointer without a cast
5530/// pint = a; // warning: assignment makes pointer from integer without a cast
5531/// pint = pfoo; // warning: assignment from incompatible pointer type
5532///
5533/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005534/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005535///
John McCall8cb679e2010-11-15 09:13:47 +00005536/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005537Sema::AssignConvertType
John McCall29600e12010-11-16 02:32:08 +00005538Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005539 CastKind &Kind) {
John McCall29600e12010-11-16 02:32:08 +00005540 QualType rhsType = rhs->getType();
5541
Chris Lattnera52c2f22008-01-04 23:18:45 +00005542 // Get canonical types. We're not formatting these types, just comparing
5543 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005544 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5545 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005546
John McCall8cb679e2010-11-15 09:13:47 +00005547 if (lhsType == rhsType) {
5548 Kind = CK_NoOp;
Chris Lattnerf5c973d2008-01-07 17:51:46 +00005549 return Compatible; // Common case: fast path an exact match.
John McCall8cb679e2010-11-15 09:13:47 +00005550 }
Steve Naroff44fd8ff2007-07-24 21:46:40 +00005551
David Chisnall9f57c292009-08-17 16:35:33 +00005552 if ((lhsType->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005553 (Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType))) ||
David Chisnall9f57c292009-08-17 16:35:33 +00005554 (rhsType->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005555 (Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)))) {
John McCall8cb679e2010-11-15 09:13:47 +00005556 Kind = CK_BitCast;
5557 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005558 }
5559
Douglas Gregor6b754842008-10-28 00:22:11 +00005560 // If the left-hand side is a reference type, then we are in a
5561 // (rare!) case where we've allowed the use of references in C,
5562 // e.g., as a parameter type in a built-in function. In this case,
5563 // just make sure that the type referenced is compatible with the
5564 // right-hand side type. The caller is responsible for adjusting
5565 // lhsType so that the resulting expression does not have reference
5566 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005567 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005568 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5569 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005570 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005571 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005572 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005573 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005574 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5575 // to the same ExtVector type.
5576 if (lhsType->isExtVectorType()) {
5577 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005578 return Incompatible;
5579 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005580 // CK_VectorSplat does T -> vector T, so first cast to the
5581 // element type.
5582 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5583 if (elType != rhsType) {
5584 Kind = PrepareScalarCast(*this, rhs, elType);
5585 ImpCastExprToType(rhs, elType, Kind);
5586 }
5587 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005588 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005589 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005590 }
Mike Stump11289f42009-09-09 15:08:12 +00005591
Nate Begeman191a6b12008-07-14 18:02:46 +00005592 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005593 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005594 // Allow assignments of an AltiVec vector type to an equivalent GCC
5595 // vector type and vice versa
5596 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5597 Kind = CK_BitCast;
5598 return Compatible;
5599 }
5600
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005601 // If we are allowing lax vector conversions, and LHS and RHS are both
5602 // vectors, the total size only needs to be the same. This is a bitcast;
5603 // no bits are changed but the result type is different.
5604 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005605 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005606 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005607 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005608 }
Chris Lattner881a2122008-01-04 23:32:24 +00005609 }
5610 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005611 }
Eli Friedman3360d892008-05-30 18:07:22 +00005612
Douglas Gregorbea453a2010-05-23 21:53:47 +00005613 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005614 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005615 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005616 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005617 }
Eli Friedman3360d892008-05-30 18:07:22 +00005618
Chris Lattnerec646832008-04-07 06:49:41 +00005619 if (isa<PointerType>(lhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005620 if (rhsType->isIntegerType()) {
5621 Kind = CK_IntegralToPointer; // FIXME: null?
Chris Lattner940cfeb2008-01-04 18:22:42 +00005622 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005623 }
Eli Friedman3360d892008-05-30 18:07:22 +00005624
John McCall8cb679e2010-11-15 09:13:47 +00005625 if (isa<PointerType>(rhsType)) {
5626 Kind = CK_BitCast;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005627 return CheckPointerTypesForAssignment(lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005628 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005629
Steve Naroffaccc4882009-07-20 17:56:53 +00005630 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005631 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005632 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005633 if (lhsType->isVoidPointerType()) // an exception to the rule.
5634 return Compatible;
5635 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005636 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005637 if (rhsType->getAs<BlockPointerType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005638 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5639 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005640 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005641 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005642
5643 // Treat block pointers as objects.
John McCall8cb679e2010-11-15 09:13:47 +00005644 if (getLangOptions().ObjC1 && lhsType->isObjCIdType()) {
5645 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005646 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005647 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005648 }
Steve Naroff081c7422008-09-04 15:10:53 +00005649 return Incompatible;
5650 }
5651
5652 if (isa<BlockPointerType>(lhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005653 if (rhsType->isIntegerType()) {
5654 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005655 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005656 }
5657
5658 Kind = CK_AnyPointerToObjCPointerCast;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005659
Steve Naroff32d072c2008-09-29 18:10:17 +00005660 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005661 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00005662 return Compatible;
5663
Steve Naroff081c7422008-09-04 15:10:53 +00005664 if (rhsType->isBlockPointerType())
5665 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005666
John McCall8cb679e2010-11-15 09:13:47 +00005667 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
Steve Naroff081c7422008-09-04 15:10:53 +00005668 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00005669 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005670
Chris Lattnera52c2f22008-01-04 23:18:45 +00005671 return Incompatible;
5672 }
5673
Steve Naroff7cae42b2009-07-10 23:34:53 +00005674 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005675 if (rhsType->isIntegerType()) {
5676 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005677 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005678 }
5679
5680 Kind = CK_BitCast;
Mike Stump11289f42009-09-09 15:08:12 +00005681
Steve Naroffaccc4882009-07-20 17:56:53 +00005682 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005683 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005684 if (rhsType->isVoidPointerType()) // an exception to the rule.
5685 return Compatible;
5686 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005687 }
5688 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005689 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005690 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005691 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005692 if (RHSPT->getPointeeType()->isVoidType())
5693 return Compatible;
5694 }
5695 // Treat block pointers as objects.
5696 if (rhsType->isBlockPointerType())
5697 return Compatible;
5698 return Incompatible;
5699 }
Chris Lattnerec646832008-04-07 06:49:41 +00005700 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00005701 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005702 if (lhsType == Context.BoolTy) {
5703 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005704 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005705 }
Eli Friedman3360d892008-05-30 18:07:22 +00005706
John McCall8cb679e2010-11-15 09:13:47 +00005707 if (lhsType->isIntegerType()) {
5708 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005709 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005710 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005711
5712 if (isa<BlockPointerType>(lhsType) &&
John McCall8cb679e2010-11-15 09:13:47 +00005713 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5714 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005715 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005716 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005717 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005718 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005719 if (isa<ObjCObjectPointerType>(rhsType)) {
5720 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005721 if (lhsType == Context.BoolTy) {
5722 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005723 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005724 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005725
John McCall8cb679e2010-11-15 09:13:47 +00005726 if (lhsType->isIntegerType()) {
5727 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005728 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005729 }
5730
5731 Kind = CK_BitCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005732
Steve Naroffaccc4882009-07-20 17:56:53 +00005733 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005734 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005735 if (lhsType->isVoidPointerType()) // an exception to the rule.
5736 return Compatible;
5737 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005738 }
5739 if (isa<BlockPointerType>(lhsType) &&
John McCall8cb679e2010-11-15 09:13:47 +00005740 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5741 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005742 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005743 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005744 return Incompatible;
5745 }
Eli Friedman3360d892008-05-30 18:07:22 +00005746
Chris Lattnera52c2f22008-01-04 23:18:45 +00005747 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005748 if (Context.typesAreCompatible(lhsType, rhsType)) {
5749 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005750 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005751 }
Bill Wendling216423b2007-05-30 06:30:29 +00005752 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00005753 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005754}
5755
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005756/// \brief Constructs a transparent union from an expression that is
5757/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00005758static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005759 QualType UnionType, FieldDecl *Field) {
5760 // Build an initializer list that designates the appropriate member
5761 // of the transparent union.
Ted Kremenekac034612010-04-13 23:39:13 +00005762 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005763 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005764 SourceLocation());
5765 Initializer->setType(UnionType);
5766 Initializer->setInitializedFieldInUnion(Field);
5767
5768 // Build a compound literal constructing a value of the transparent
5769 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005770 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00005771 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall7decc9e2010-11-18 06:31:45 +00005772 VK_RValue, Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005773}
5774
5775Sema::AssignConvertType
5776Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
5777 QualType FromType = rExpr->getType();
5778
Mike Stump11289f42009-09-09 15:08:12 +00005779 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005780 // transparent_union GCC extension.
5781 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005782 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005783 return Incompatible;
5784
5785 // The field to initialize within the transparent union.
5786 RecordDecl *UD = UT->getDecl();
5787 FieldDecl *InitField = 0;
5788 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005789 for (RecordDecl::field_iterator it = UD->field_begin(),
5790 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005791 it != itend; ++it) {
5792 if (it->getType()->isPointerType()) {
5793 // If the transparent union contains a pointer type, we allow:
5794 // 1) void pointer
5795 // 2) null pointer constant
5796 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005797 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +00005798 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005799 InitField = *it;
5800 break;
5801 }
Mike Stump11289f42009-09-09 15:08:12 +00005802
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005803 if (rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005804 Expr::NPC_ValueDependentIsNull)) {
John McCalle84af4e2010-11-13 01:35:44 +00005805 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005806 InitField = *it;
5807 break;
5808 }
5809 }
5810
John McCall29600e12010-11-16 02:32:08 +00005811 Expr *rhs = rExpr;
John McCall8cb679e2010-11-15 09:13:47 +00005812 CastKind Kind = CK_Invalid;
John McCall29600e12010-11-16 02:32:08 +00005813 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005814 == Compatible) {
John McCall29600e12010-11-16 02:32:08 +00005815 ImpCastExprToType(rhs, it->getType(), Kind);
5816 rExpr = rhs;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005817 InitField = *it;
5818 break;
5819 }
5820 }
5821
5822 if (!InitField)
5823 return Incompatible;
5824
5825 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
5826 return Compatible;
5827}
5828
Chris Lattner9bad62c2008-01-04 18:04:52 +00005829Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005830Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005831 if (getLangOptions().CPlusPlus) {
5832 if (!lhsType->isRecordType()) {
5833 // C++ 5.17p3: If the left operand is not of class type, the
5834 // expression is implicitly converted (C++ 4) to the
5835 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00005836 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005837 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00005838 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00005839 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00005840 }
5841
5842 // FIXME: Currently, we fall through and treat C++ classes like C
5843 // structures.
John McCall34376a62010-12-04 03:47:34 +00005844 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005845
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005846 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5847 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00005848 if ((lhsType->isPointerType() ||
5849 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00005850 lhsType->isBlockPointerType())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005851 && rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005852 Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00005853 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005854 return Compatible;
5855 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005856
Chris Lattnere6dcd502007-10-16 02:55:40 +00005857 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005858 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005859 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005860 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005861 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005862 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00005863 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00005864 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005865
John McCall8cb679e2010-11-15 09:13:47 +00005866 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005867 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00005868 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005869
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005870 // C99 6.5.16.1p2: The value of the right operand is converted to the
5871 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005872 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5873 // so that we can use references in built-in functions even in C.
5874 // The getNonReferenceType() call makes sure that the resulting expression
5875 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005876 if (result != Incompatible && rExpr->getType() != lhsType)
John McCall8cb679e2010-11-15 09:13:47 +00005877 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005878 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005879}
5880
Chris Lattner326f7572008-11-18 01:30:42 +00005881QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005882 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005883 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00005884 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005885 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005886}
5887
Chris Lattnerfaa54172010-01-12 21:23:57 +00005888QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005889 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005890 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00005891 QualType lhsType =
5892 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
5893 QualType rhsType =
5894 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005895
Nate Begeman191a6b12008-07-14 18:02:46 +00005896 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005897 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00005898 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005899
Nate Begeman191a6b12008-07-14 18:02:46 +00005900 // Handle the case of a vector & extvector type of the same size and element
5901 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005902 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00005903 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00005904 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00005905 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005906 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005907 if (lhsType->isExtVectorType()) {
John McCalle3027922010-08-25 11:45:40 +00005908 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005909 return lhsType;
5910 }
5911
John McCalle3027922010-08-25 11:45:40 +00005912 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005913 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00005914 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
5915 // If we are allowing lax vector conversions, and LHS and RHS are both
5916 // vectors, the total size only needs to be the same. This is a
5917 // bitcast; no bits are changed but the result type is different.
5918 ImpCastExprToType(rex, lhsType, CK_BitCast);
5919 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005920 }
Eric Christophera613f562010-08-26 00:42:16 +00005921 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00005922 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005923 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005924
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005925 // Handle the case of equivalent AltiVec and GCC vector types
5926 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5927 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCalle3027922010-08-25 11:45:40 +00005928 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005929 return rhsType;
5930 }
5931
Nate Begemanbd956c42009-06-28 02:36:38 +00005932 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5933 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5934 bool swapped = false;
5935 if (rhsType->isExtVectorType()) {
5936 swapped = true;
5937 std::swap(rex, lex);
5938 std::swap(rhsType, lhsType);
5939 }
Mike Stump11289f42009-09-09 15:08:12 +00005940
Nate Begeman886448d2009-06-28 19:12:57 +00005941 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005942 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005943 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005944 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00005945 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5946 if (order > 0)
5947 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
5948 if (order >= 0) {
5949 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005950 if (swapped) std::swap(rex, lex);
5951 return lhsType;
5952 }
5953 }
5954 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5955 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005956 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5957 if (order > 0)
5958 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
5959 if (order >= 0) {
5960 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005961 if (swapped) std::swap(rex, lex);
5962 return lhsType;
5963 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005964 }
5965 }
Mike Stump11289f42009-09-09 15:08:12 +00005966
Nate Begeman886448d2009-06-28 19:12:57 +00005967 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00005968 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005969 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00005970 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005971 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005972}
5973
Chris Lattnerfaa54172010-01-12 21:23:57 +00005974QualType Sema::CheckMultiplyDivideOperands(
5975 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00005976 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005977 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005978
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005979 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005980
Chris Lattnerfaa54172010-01-12 21:23:57 +00005981 if (!lex->getType()->isArithmeticType() ||
5982 !rex->getType()->isArithmeticType())
5983 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005984
Chris Lattnerfaa54172010-01-12 21:23:57 +00005985 // Check for division by zero.
5986 if (isDiv &&
5987 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005988 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattner70117952010-01-12 21:30:55 +00005989 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005990
Chris Lattnerfaa54172010-01-12 21:23:57 +00005991 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005992}
5993
Chris Lattnerfaa54172010-01-12 21:23:57 +00005994QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005995 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005996 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005997 if (lex->getType()->hasIntegerRepresentation() &&
5998 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005999 return CheckVectorOperands(Loc, lex, rex);
6000 return InvalidOperands(Loc, lex, rex);
6001 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006002
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006003 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006004
Chris Lattnerfaa54172010-01-12 21:23:57 +00006005 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6006 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006007
Chris Lattnerfaa54172010-01-12 21:23:57 +00006008 // Check for remainder by zero.
6009 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00006010 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
6011 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006012
Chris Lattnerfaa54172010-01-12 21:23:57 +00006013 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006014}
6015
Chris Lattnerfaa54172010-01-12 21:23:57 +00006016QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00006017 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006018 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6019 QualType compType = CheckVectorOperands(Loc, lex, rex);
6020 if (CompLHSTy) *CompLHSTy = compType;
6021 return compType;
6022 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006023
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006024 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006025
Steve Naroffe4718892007-04-27 18:30:00 +00006026 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006027 if (lex->getType()->isArithmeticType() &&
6028 rex->getType()->isArithmeticType()) {
6029 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006030 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006031 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006032
Eli Friedman8e122982008-05-18 18:08:51 +00006033 // Put any potential pointer into PExp
6034 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00006035 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006036 std::swap(PExp, IExp);
6037
Steve Naroff6b712a72009-07-14 18:25:06 +00006038 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006039
Eli Friedman8e122982008-05-18 18:08:51 +00006040 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006041 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006042
Chris Lattner12bdebb2009-04-24 23:50:08 +00006043 // Check for arithmetic on pointers to incomplete types.
6044 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006045 if (getLangOptions().CPlusPlus) {
6046 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00006047 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00006048 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006049 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006050
6051 // GNU extension: arithmetic on pointer to void
6052 Diag(Loc, diag::ext_gnu_void_ptr)
6053 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006054 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006055 if (getLangOptions().CPlusPlus) {
6056 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6057 << lex->getType() << lex->getSourceRange();
6058 return QualType();
6059 }
6060
6061 // GNU extension: arithmetic on pointer to function
6062 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6063 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00006064 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006065 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00006066 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00006067 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006068 PExp->getType()->isObjCObjectPointerType()) &&
6069 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00006070 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6071 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006072 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006073 return QualType();
6074 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00006075 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006076 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006077 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6078 << PointeeTy << PExp->getSourceRange();
6079 return QualType();
6080 }
Mike Stump11289f42009-09-09 15:08:12 +00006081
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006082 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00006083 QualType LHSTy = Context.isPromotableBitField(lex);
6084 if (LHSTy.isNull()) {
6085 LHSTy = lex->getType();
6086 if (LHSTy->isPromotableIntegerType())
6087 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006088 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006089 *CompLHSTy = LHSTy;
6090 }
Eli Friedman8e122982008-05-18 18:08:51 +00006091 return PExp->getType();
6092 }
6093 }
6094
Chris Lattner326f7572008-11-18 01:30:42 +00006095 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006096}
6097
Chris Lattner2a3569b2008-04-07 05:30:13 +00006098// C99 6.5.6
6099QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006100 SourceLocation Loc, QualType* CompLHSTy) {
6101 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6102 QualType compType = CheckVectorOperands(Loc, lex, rex);
6103 if (CompLHSTy) *CompLHSTy = compType;
6104 return compType;
6105 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006106
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006107 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006108
Chris Lattner4d62f422007-12-09 21:53:25 +00006109 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006110
Chris Lattner4d62f422007-12-09 21:53:25 +00006111 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00006112 if (lex->getType()->isArithmeticType()
6113 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006114 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006115 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006116 }
Mike Stump11289f42009-09-09 15:08:12 +00006117
Chris Lattner4d62f422007-12-09 21:53:25 +00006118 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00006119 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00006120 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006121
Douglas Gregorac1fb652009-03-24 19:52:54 +00006122 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006123
Douglas Gregorac1fb652009-03-24 19:52:54 +00006124 bool ComplainAboutVoid = false;
6125 Expr *ComplainAboutFunc = 0;
6126 if (lpointee->isVoidType()) {
6127 if (getLangOptions().CPlusPlus) {
6128 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6129 << lex->getSourceRange() << rex->getSourceRange();
6130 return QualType();
6131 }
6132
6133 // GNU C extension: arithmetic on pointer to void
6134 ComplainAboutVoid = true;
6135 } else if (lpointee->isFunctionType()) {
6136 if (getLangOptions().CPlusPlus) {
6137 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006138 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006139 return QualType();
6140 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006141
6142 // GNU C extension: arithmetic on pointer to function
6143 ComplainAboutFunc = lex;
6144 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00006145 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006146 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00006147 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006148 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006149 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006150
Chris Lattner12bdebb2009-04-24 23:50:08 +00006151 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006152 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006153 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6154 << lpointee << lex->getSourceRange();
6155 return QualType();
6156 }
Mike Stump11289f42009-09-09 15:08:12 +00006157
Chris Lattner4d62f422007-12-09 21:53:25 +00006158 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00006159 if (rex->getType()->isIntegerType()) {
6160 if (ComplainAboutVoid)
6161 Diag(Loc, diag::ext_gnu_void_ptr)
6162 << lex->getSourceRange() << rex->getSourceRange();
6163 if (ComplainAboutFunc)
6164 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006165 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006166 << ComplainAboutFunc->getSourceRange();
6167
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006168 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006169 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006170 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006171
Chris Lattner4d62f422007-12-09 21:53:25 +00006172 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006173 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006174 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006175
Douglas Gregorac1fb652009-03-24 19:52:54 +00006176 // RHS must be a completely-type object type.
6177 // Handle the GNU void* extension.
6178 if (rpointee->isVoidType()) {
6179 if (getLangOptions().CPlusPlus) {
6180 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6181 << lex->getSourceRange() << rex->getSourceRange();
6182 return QualType();
6183 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006184
Douglas Gregorac1fb652009-03-24 19:52:54 +00006185 ComplainAboutVoid = true;
6186 } else if (rpointee->isFunctionType()) {
6187 if (getLangOptions().CPlusPlus) {
6188 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006189 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006190 return QualType();
6191 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006192
6193 // GNU extension: arithmetic on pointer to function
6194 if (!ComplainAboutFunc)
6195 ComplainAboutFunc = rex;
6196 } else if (!rpointee->isDependentType() &&
6197 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006198 PDiag(diag::err_typecheck_sub_ptr_object)
6199 << rex->getSourceRange()
6200 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006201 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006202
Eli Friedman168fe152009-05-16 13:54:38 +00006203 if (getLangOptions().CPlusPlus) {
6204 // Pointee types must be the same: C++ [expr.add]
6205 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6206 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6207 << lex->getType() << rex->getType()
6208 << lex->getSourceRange() << rex->getSourceRange();
6209 return QualType();
6210 }
6211 } else {
6212 // Pointee types must be compatible C99 6.5.6p3
6213 if (!Context.typesAreCompatible(
6214 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6215 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6216 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6217 << lex->getType() << rex->getType()
6218 << lex->getSourceRange() << rex->getSourceRange();
6219 return QualType();
6220 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006221 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006222
Douglas Gregorac1fb652009-03-24 19:52:54 +00006223 if (ComplainAboutVoid)
6224 Diag(Loc, diag::ext_gnu_void_ptr)
6225 << lex->getSourceRange() << rex->getSourceRange();
6226 if (ComplainAboutFunc)
6227 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006228 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006229 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006230
6231 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006232 return Context.getPointerDiffType();
6233 }
6234 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006235
Chris Lattner326f7572008-11-18 01:30:42 +00006236 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006237}
6238
Douglas Gregor0bf31402010-10-08 23:50:27 +00006239static bool isScopedEnumerationType(QualType T) {
6240 if (const EnumType *ET = dyn_cast<EnumType>(T))
6241 return ET->getDecl()->isScoped();
6242 return false;
6243}
6244
Chris Lattner2a3569b2008-04-07 05:30:13 +00006245// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00006246QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00006247 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006248 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006249 if (!lex->getType()->hasIntegerRepresentation() ||
6250 !rex->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006251 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006252
Douglas Gregor0bf31402010-10-08 23:50:27 +00006253 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6254 // hasIntegerRepresentation() above instead of this.
6255 if (isScopedEnumerationType(lex->getType()) ||
6256 isScopedEnumerationType(rex->getType())) {
6257 return InvalidOperands(Loc, lex, rex);
6258 }
6259
Nate Begemane46ee9a2009-10-25 02:26:48 +00006260 // Vector shifts promote their scalar inputs to vector type.
6261 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6262 return CheckVectorOperands(Loc, lex, rex);
6263
Chris Lattner5c11c412007-12-12 05:47:28 +00006264 // Shifts don't perform usual arithmetic conversions, they just do integer
6265 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006266
John McCall57cdd882010-12-16 19:28:59 +00006267 // For the LHS, do usual unary conversions, but then reset them away
6268 // if this is a compound assignment.
6269 Expr *old_lex = lex;
6270 UsualUnaryConversions(lex);
6271 QualType LHSTy = lex->getType();
6272 if (isCompAssign) lex = old_lex;
6273
6274 // The RHS is simpler.
Chris Lattner5c11c412007-12-12 05:47:28 +00006275 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006276
Ryan Flynnf53fab82009-08-07 16:20:20 +00006277 // Sanity-check shift operands
6278 llvm::APSInt Right;
6279 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00006280 if (!rex->isValueDependent() &&
6281 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00006282 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00006283 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6284 else {
6285 llvm::APInt LeftBits(Right.getBitWidth(),
6286 Context.getTypeSize(lex->getType()));
6287 if (Right.uge(LeftBits))
6288 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6289 }
6290 }
6291
Chris Lattner5c11c412007-12-12 05:47:28 +00006292 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006293 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006294}
6295
Chandler Carruth17773fc2010-07-10 12:30:03 +00006296static bool IsWithinTemplateSpecialization(Decl *D) {
6297 if (DeclContext *DC = D->getDeclContext()) {
6298 if (isa<ClassTemplateSpecializationDecl>(DC))
6299 return true;
6300 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6301 return FD->isFunctionTemplateSpecialization();
6302 }
6303 return false;
6304}
6305
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006306// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00006307QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006308 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006309 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006310
Chris Lattner9a152e22009-12-05 05:40:13 +00006311 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00006312 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006313 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006314
Steve Naroff31090012007-07-16 21:54:35 +00006315 QualType lType = lex->getType();
6316 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006317
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006318 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006319 !(lType->isBlockPointerType() && isRelational) &&
6320 !lex->getLocStart().isMacroID() &&
6321 !rex->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006322 // For non-floating point types, check for self-comparisons of the form
6323 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6324 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006325 //
6326 // NOTE: Don't warn about comparison expressions resulting from macro
6327 // expansion. Also don't warn about comparisons which are only self
6328 // comparisons within a template specialization. The warnings should catch
6329 // obvious cases in the definition of the template anyways. The idea is to
6330 // warn when the typed comparison operator will always evaluate to the same
6331 // result.
John McCall34376a62010-12-04 03:47:34 +00006332 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6333 Expr *RHSStripped = rex->IgnoreParenImpCasts();
Chandler Carruth17773fc2010-07-10 12:30:03 +00006334 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006335 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006336 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006337 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006338 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6339 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006340 << (Opc == BO_EQ
6341 || Opc == BO_LE
6342 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006343 } else if (lType->isArrayType() && rType->isArrayType() &&
6344 !DRL->getDecl()->getType()->isReferenceType() &&
6345 !DRR->getDecl()->getType()->isReferenceType()) {
6346 // what is it always going to eval to?
6347 char always_evals_to;
6348 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006349 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006350 always_evals_to = 0; // false
6351 break;
John McCalle3027922010-08-25 11:45:40 +00006352 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006353 always_evals_to = 1; // true
6354 break;
6355 default:
6356 // best we can say is 'a constant'
6357 always_evals_to = 2; // e.g. array1 <= array2
6358 break;
6359 }
6360 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6361 << 1 // array
6362 << always_evals_to);
6363 }
6364 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006365 }
Mike Stump11289f42009-09-09 15:08:12 +00006366
Chris Lattner222b8bd2009-03-08 19:39:53 +00006367 if (isa<CastExpr>(LHSStripped))
6368 LHSStripped = LHSStripped->IgnoreParenCasts();
6369 if (isa<CastExpr>(RHSStripped))
6370 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006371
Chris Lattner222b8bd2009-03-08 19:39:53 +00006372 // Warn about comparisons against a string constant (unless the other
6373 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006374 Expr *literalString = 0;
6375 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006376 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006377 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006378 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006379 literalString = lex;
6380 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006381 } else if ((isa<StringLiteral>(RHSStripped) ||
6382 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006383 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006384 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006385 literalString = rex;
6386 literalStringStripped = RHSStripped;
6387 }
6388
6389 if (literalString) {
6390 std::string resultComparison;
6391 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006392 case BO_LT: resultComparison = ") < 0"; break;
6393 case BO_GT: resultComparison = ") > 0"; break;
6394 case BO_LE: resultComparison = ") <= 0"; break;
6395 case BO_GE: resultComparison = ") >= 0"; break;
6396 case BO_EQ: resultComparison = ") == 0"; break;
6397 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006398 default: assert(false && "Invalid comparison operator");
6399 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006400
Douglas Gregor49862b82010-01-12 23:18:54 +00006401 DiagRuntimeBehavior(Loc,
6402 PDiag(diag::warn_stringcompare)
6403 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006404 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006405 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006406 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006407
Douglas Gregorec170db2010-06-08 19:50:34 +00006408 // C99 6.5.8p3 / C99 6.5.9p4
6409 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6410 UsualArithmeticConversions(lex, rex);
6411 else {
6412 UsualUnaryConversions(lex);
6413 UsualUnaryConversions(rex);
6414 }
6415
6416 lType = lex->getType();
6417 rType = rex->getType();
6418
Douglas Gregorca63811b2008-11-19 03:25:36 +00006419 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00006420 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00006421
Chris Lattnerb620c342007-08-26 01:18:55 +00006422 if (isRelational) {
6423 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006424 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006425 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006426 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006427 if (lType->hasFloatingRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006428 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006429
Chris Lattnerb620c342007-08-26 01:18:55 +00006430 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006431 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006432 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006433
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006434 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006435 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006436 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006437 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006438
Douglas Gregorf267edd2010-06-15 21:38:40 +00006439 // All of the following pointer-related warnings are GCC extensions, except
6440 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006441 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006442 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006443 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006444 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006445 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006446
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006447 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006448 if (LCanPointeeTy == RCanPointeeTy)
6449 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006450 if (!isRelational &&
6451 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6452 // Valid unless comparison between non-null pointer and function pointer
6453 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006454 // In a SFINAE context, we treat this as a hard error to maintain
6455 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006456 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6457 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006458 Diag(Loc,
6459 isSFINAEContext()?
6460 diag::err_typecheck_comparison_of_fptr_to_void
6461 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006462 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006463
6464 if (isSFINAEContext())
6465 return QualType();
6466
John McCalle3027922010-08-25 11:45:40 +00006467 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006468 return ResultTy;
6469 }
6470 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006471
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006472 // C++ [expr.rel]p2:
6473 // [...] Pointer conversions (4.10) and qualification
6474 // conversions (4.4) are performed on pointer operands (or on
6475 // a pointer operand and a null pointer constant) to bring
6476 // them to their composite pointer type. [...]
6477 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006478 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006479 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006480 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006481 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006482 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006483 if (T.isNull()) {
6484 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6485 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6486 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006487 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006488 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006489 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006490 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006491 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006492 }
6493
John McCalle3027922010-08-25 11:45:40 +00006494 ImpCastExprToType(lex, T, CK_BitCast);
6495 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006496 return ResultTy;
6497 }
Eli Friedman16c209612009-08-23 00:27:47 +00006498 // C99 6.5.9p2 and C99 6.5.8p2
6499 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6500 RCanPointeeTy.getUnqualifiedType())) {
6501 // Valid unless a relational comparison of function pointers
6502 if (isRelational && LCanPointeeTy->isFunctionType()) {
6503 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6504 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6505 }
6506 } else if (!isRelational &&
6507 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6508 // Valid unless comparison between non-null pointer and function pointer
6509 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6510 && !LHSIsNull && !RHSIsNull) {
6511 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6512 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6513 }
6514 } else {
6515 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006516 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006517 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006518 }
Eli Friedman16c209612009-08-23 00:27:47 +00006519 if (LCanPointeeTy != RCanPointeeTy)
John McCalle3027922010-08-25 11:45:40 +00006520 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006521 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006522 }
Mike Stump11289f42009-09-09 15:08:12 +00006523
Sebastian Redl576fd422009-05-10 18:38:11 +00006524 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006525 // Comparison of nullptr_t with itself.
6526 if (lType->isNullPtrType() && rType->isNullPtrType())
6527 return ResultTy;
6528
Mike Stump11289f42009-09-09 15:08:12 +00006529 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006530 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006531 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006532 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006533 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006534 ImpCastExprToType(rex, lType,
6535 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006536 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006537 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006538 return ResultTy;
6539 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006540 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006541 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006542 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006543 ImpCastExprToType(lex, rType,
6544 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006545 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006546 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006547 return ResultTy;
6548 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006549
6550 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006551 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006552 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6553 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006554 // In addition, pointers to members can be compared, or a pointer to
6555 // member and a null pointer constant. Pointer to member conversions
6556 // (4.11) and qualification conversions (4.4) are performed to bring
6557 // them to a common type. If one operand is a null pointer constant,
6558 // the common type is the type of the other operand. Otherwise, the
6559 // common type is a pointer to member type similar (4.4) to the type
6560 // of one of the operands, with a cv-qualification signature (4.4)
6561 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006562 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006563 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006564 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006565 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006566 if (T.isNull()) {
6567 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006568 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006569 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006570 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006571 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006572 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006573 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006574 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006575 }
Mike Stump11289f42009-09-09 15:08:12 +00006576
John McCalle3027922010-08-25 11:45:40 +00006577 ImpCastExprToType(lex, T, CK_BitCast);
6578 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006579 return ResultTy;
6580 }
Sebastian Redl576fd422009-05-10 18:38:11 +00006581 }
Mike Stump11289f42009-09-09 15:08:12 +00006582
Steve Naroff081c7422008-09-04 15:10:53 +00006583 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00006584 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006585 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6586 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006587
Steve Naroff081c7422008-09-04 15:10:53 +00006588 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006589 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006590 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006591 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006592 }
John McCalle3027922010-08-25 11:45:40 +00006593 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006594 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006595 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00006596 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006597 if (!isRelational
6598 && ((lType->isBlockPointerType() && rType->isPointerType())
6599 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006600 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006601 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006602 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006603 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006604 ->getPointeeType()->isVoidType())))
6605 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6606 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006607 }
John McCalle3027922010-08-25 11:45:40 +00006608 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006609 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006610 }
Steve Naroff081c7422008-09-04 15:10:53 +00006611
Steve Naroff7cae42b2009-07-10 23:34:53 +00006612 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006613 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006614 const PointerType *LPT = lType->getAs<PointerType>();
6615 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006616 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00006617 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006618 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00006619 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006620
Steve Naroff753567f2008-11-17 19:49:16 +00006621 if (!LPtrToVoid && !RPtrToVoid &&
6622 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006623 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006624 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006625 }
John McCalle3027922010-08-25 11:45:40 +00006626 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006627 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006628 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006629 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006630 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006631 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6632 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006633 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006634 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006635 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006636 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006637 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6638 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006639 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006640 bool isError = false;
6641 if ((LHSIsNull && lType->isIntegerType()) ||
6642 (RHSIsNull && rType->isIntegerType())) {
6643 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006644 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006645 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006646 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006647 else if (getLangOptions().CPlusPlus) {
6648 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6649 isError = true;
6650 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006651 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006652
Chris Lattnerd99bd522009-08-23 00:03:44 +00006653 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006654 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00006655 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006656 if (isError)
6657 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006658 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006659
6660 if (lType->isIntegerType())
John McCalle84af4e2010-11-13 01:35:44 +00006661 ImpCastExprToType(lex, rType,
6662 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006663 else
John McCalle84af4e2010-11-13 01:35:44 +00006664 ImpCastExprToType(rex, lType,
6665 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006666 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006667 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006668
Steve Naroff4b191572008-09-04 16:56:14 +00006669 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006670 if (!isRelational && RHSIsNull
6671 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00006672 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006673 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006674 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006675 if (!isRelational && LHSIsNull
6676 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00006677 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006678 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006679 }
Chris Lattner326f7572008-11-18 01:30:42 +00006680 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006681}
6682
Nate Begeman191a6b12008-07-14 18:02:46 +00006683/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006684/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006685/// like a scalar comparison, a vector comparison produces a vector of integer
6686/// types.
6687QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00006688 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006689 bool isRelational) {
6690 // Check to make sure we're operating on vectors of the same type and width,
6691 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00006692 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00006693 if (vType.isNull())
6694 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006695
Anton Yartsev3f8f2882010-11-18 03:19:30 +00006696 // If AltiVec, the comparison results in a numeric type, i.e.
6697 // bool for C++, int for C
6698 if (getLangOptions().AltiVec)
6699 return (getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy);
6700
Nate Begeman191a6b12008-07-14 18:02:46 +00006701 QualType lType = lex->getType();
6702 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006703
Nate Begeman191a6b12008-07-14 18:02:46 +00006704 // For non-floating point types, check for self-comparisons of the form
6705 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6706 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006707 if (!lType->hasFloatingRepresentation()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006708 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
6709 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
6710 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregorec170db2010-06-08 19:50:34 +00006711 DiagRuntimeBehavior(Loc,
6712 PDiag(diag::warn_comparison_always)
6713 << 0 // self-
6714 << 2 // "a constant"
6715 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006716 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006717
Nate Begeman191a6b12008-07-14 18:02:46 +00006718 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006719 if (!isRelational && lType->hasFloatingRepresentation()) {
6720 assert (rType->hasFloatingRepresentation());
Chris Lattner326f7572008-11-18 01:30:42 +00006721 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00006722 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006723
Nate Begeman191a6b12008-07-14 18:02:46 +00006724 // Return the type for the comparison, which is the same as vector type for
6725 // integer vectors, or an integer type of identical size and number of
6726 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006727 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00006728 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006729
John McCall9dd450b2009-09-21 23:43:11 +00006730 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006731 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006732 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006733 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006734 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006735 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6736
Mike Stump4e1f26a2009-02-19 03:04:26 +00006737 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006738 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006739 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6740}
6741
Steve Naroff218bc2b2007-05-04 21:54:46 +00006742inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00006743 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006744 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6745 if (lex->getType()->hasIntegerRepresentation() &&
6746 rex->getType()->hasIntegerRepresentation())
6747 return CheckVectorOperands(Loc, lex, rex);
6748
6749 return InvalidOperands(Loc, lex, rex);
6750 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006751
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006752 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006753
Douglas Gregor0bf31402010-10-08 23:50:27 +00006754 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
6755 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006756 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00006757 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006758}
6759
Steve Naroff218bc2b2007-05-04 21:54:46 +00006760inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner8406c512010-07-13 19:41:32 +00006761 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
6762
6763 // Diagnose cases where the user write a logical and/or but probably meant a
6764 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6765 // is a constant.
6766 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman6b197e02010-07-27 19:14:53 +00006767 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00006768 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00006769 !Loc.isMacroID()) {
6770 // If the RHS can be constant folded, and if it constant folds to something
6771 // that isn't 0 or 1 (which indicate a potential logical operation that
6772 // happened to fold to true/false) then warn.
6773 Expr::EvalResult Result;
6774 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
6775 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
6776 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6777 << rex->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00006778 << (Opc == BO_LAnd ? "&&" : "||")
6779 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00006780 }
6781 }
Chris Lattner8406c512010-07-13 19:41:32 +00006782
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006783 if (!Context.getLangOptions().CPlusPlus) {
6784 UsualUnaryConversions(lex);
6785 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006786
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006787 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
6788 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006789
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006790 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006791 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006792
John McCall4a2429a2010-06-04 00:29:51 +00006793 // The following is safe because we only use this method for
6794 // non-overloadable operands.
6795
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006796 // C++ [expr.log.and]p1
6797 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006798 // The operands are both contextually converted to type bool.
6799 if (PerformContextuallyConvertToBool(lex) ||
6800 PerformContextuallyConvertToBool(rex))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006801 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006802
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006803 // C++ [expr.log.and]p2
6804 // C++ [expr.log.or]p2
6805 // The result is a bool.
6806 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006807}
6808
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006809/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6810/// is a read-only property; return true if so. A readonly property expression
6811/// depends on various declarations and thus must be treated specially.
6812///
Mike Stump11289f42009-09-09 15:08:12 +00006813static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006814 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6815 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006816 if (PropExpr->isImplicitProperty()) return false;
6817
6818 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6819 QualType BaseType = PropExpr->isSuperReceiver() ?
6820 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006821 PropExpr->getBase()->getType();
6822
John McCallb7bd14f2010-12-02 01:19:52 +00006823 if (const ObjCObjectPointerType *OPT =
6824 BaseType->getAsObjCInterfacePointerType())
6825 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6826 if (S.isPropertyReadonly(PDecl, IFace))
6827 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006828 }
6829 return false;
6830}
6831
Chris Lattner30bd3272008-11-18 01:22:49 +00006832/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6833/// emit an error and return true. If so, return false.
6834static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006835 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006836 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006837 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006838 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6839 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00006840 if (IsLV == Expr::MLV_Valid)
6841 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006842
Chris Lattner30bd3272008-11-18 01:22:49 +00006843 unsigned Diag = 0;
6844 bool NeedType = false;
6845 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00006846 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006847 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006848 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6849 NeedType = true;
6850 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006851 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006852 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6853 NeedType = true;
6854 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006855 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006856 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6857 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006858 case Expr::MLV_Valid:
6859 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006860 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006861 case Expr::MLV_MemberFunction:
6862 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006863 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6864 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006865 case Expr::MLV_IncompleteType:
6866 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006867 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006868 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006869 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006870 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006871 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6872 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006873 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006874 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6875 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006876 case Expr::MLV_ReadonlyProperty:
6877 Diag = diag::error_readonly_property_assignment;
6878 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006879 case Expr::MLV_NoSetterProperty:
6880 Diag = diag::error_nosetter_property_assignment;
6881 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006882 case Expr::MLV_SubObjCPropertySetting:
6883 Diag = diag::error_no_subobject_property_setting;
6884 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006885 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006886
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006887 SourceRange Assign;
6888 if (Loc != OrigLoc)
6889 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006890 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006891 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006892 else
Mike Stump11289f42009-09-09 15:08:12 +00006893 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006894 return true;
6895}
6896
6897
6898
6899// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00006900QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
6901 SourceLocation Loc,
6902 QualType CompoundType) {
6903 // Verify that LHS is a modifiable lvalue, and emit error if not.
6904 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00006905 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00006906
6907 QualType LHSType = LHS->getType();
6908 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006909 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00006910 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006911 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006912 // Simple assignment "x = y".
John McCall34376a62010-12-04 03:47:34 +00006913 if (LHS->getObjectKind() == OK_ObjCProperty)
6914 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006915 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006916 // Special case of NSObject attributes on c-style pointer types.
6917 if (ConvTy == IncompatiblePointer &&
6918 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006919 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006920 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006921 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006922 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006923
John McCall7decc9e2010-11-18 06:31:45 +00006924 if (ConvTy == Compatible &&
6925 getLangOptions().ObjCNonFragileABI &&
6926 LHSType->isObjCObjectType())
6927 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6928 << LHSType;
6929
Chris Lattnerea714382008-08-21 18:04:13 +00006930 // If the RHS is a unary plus or minus, check to see if they = and + are
6931 // right next to each other. If so, the user may have typo'd "x =+ 4"
6932 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00006933 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00006934 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6935 RHSCheck = ICE->getSubExpr();
6936 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00006937 if ((UO->getOpcode() == UO_Plus ||
6938 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00006939 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00006940 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00006941 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6942 // And there is a space or other character before the subexpr of the
6943 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00006944 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6945 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006946 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00006947 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00006948 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00006949 }
Chris Lattnerea714382008-08-21 18:04:13 +00006950 }
6951 } else {
6952 // Compound assignment "x += y"
John McCall29600e12010-11-16 02:32:08 +00006953 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006954 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006955
Chris Lattner326f7572008-11-18 01:30:42 +00006956 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006957 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00006958 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006959
Chris Lattner39561062010-07-07 06:14:23 +00006960
6961 // Check to see if the destination operand is a dereferenced null pointer. If
6962 // so, and if not volatile-qualified, this is undefined behavior that the
6963 // optimizer will delete, so warn about it. People sometimes try to use this
6964 // to get a deterministic trap and are surprised by clang's behavior. This
6965 // only handles the pattern "*null = whatever", which is a very syntactic
6966 // check.
6967 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCalle3027922010-08-25 11:45:40 +00006968 if (UO->getOpcode() == UO_Deref &&
Chris Lattner39561062010-07-07 06:14:23 +00006969 UO->getSubExpr()->IgnoreParenCasts()->
6970 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
6971 !UO->getType().isVolatileQualified()) {
6972 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
6973 << UO->getSubExpr()->getSourceRange();
6974 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
6975 }
6976
Steve Naroff98cf3e92007-06-06 18:38:38 +00006977 // C99 6.5.16p3: The type of an assignment expression is the type of the
6978 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00006979 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00006980 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6981 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00006982 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00006983 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00006984 return (getLangOptions().CPlusPlus
6985 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00006986}
6987
Chris Lattner326f7572008-11-18 01:30:42 +00006988// C99 6.5.17
John McCall34376a62010-12-04 03:47:34 +00006989static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00006990 SourceLocation Loc) {
6991 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00006992
John McCall4bc41ae2010-11-18 19:01:18 +00006993 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006994 if (LHSResult.isInvalid())
6995 return QualType();
6996
John McCall4bc41ae2010-11-18 19:01:18 +00006997 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006998 if (RHSResult.isInvalid())
6999 return QualType();
7000 RHS = RHSResult.take();
7001
John McCall73d36182010-10-12 07:14:40 +00007002 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7003 // operands, but not unary promotions.
7004 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007005
John McCall34376a62010-12-04 03:47:34 +00007006 // So we treat the LHS as a ignored value, and in C++ we allow the
7007 // containing site to determine what should be done with the RHS.
7008 S.IgnoredValueConversions(LHS);
7009
7010 if (!S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007011 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCall73d36182010-10-12 07:14:40 +00007012 if (!RHS->getType()->isVoidType())
John McCall4bc41ae2010-11-18 19:01:18 +00007013 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007014 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007015
Chris Lattner326f7572008-11-18 01:30:42 +00007016 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007017}
7018
Steve Naroff7a5af782007-07-13 16:58:59 +00007019/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7020/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007021static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7022 ExprValueKind &VK,
7023 SourceLocation OpLoc,
7024 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007025 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007026 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007027
Chris Lattner6b0cf142008-11-21 07:05:48 +00007028 QualType ResType = Op->getType();
7029 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007030
John McCall4bc41ae2010-11-18 19:01:18 +00007031 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007032 // Decrement of bool is not allowed.
7033 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007034 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007035 return QualType();
7036 }
7037 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007038 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007039 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007040 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007041 } else if (ResType->isAnyPointerType()) {
7042 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007043
Chris Lattner6b0cf142008-11-21 07:05:48 +00007044 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00007045 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007046 if (S.getLangOptions().CPlusPlus) {
7047 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007048 << Op->getSourceRange();
7049 return QualType();
7050 }
7051
7052 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00007053 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007054 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007055 if (S.getLangOptions().CPlusPlus) {
7056 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007057 << Op->getType() << Op->getSourceRange();
7058 return QualType();
7059 }
7060
John McCall4bc41ae2010-11-18 19:01:18 +00007061 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007062 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007063 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7064 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00007065 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00007066 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00007067 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007068 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00007069 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7070 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007071 << PointeeTy << Op->getSourceRange();
7072 return QualType();
7073 }
Eli Friedman090addd2010-01-03 00:20:48 +00007074 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007075 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007076 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007077 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007078 } else if (ResType->isPlaceholderType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007079 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007080 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007081 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7082 isInc, isPrefix);
Chris Lattner6b0cf142008-11-21 07:05:48 +00007083 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007084 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007085 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007086 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007087 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007088 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007089 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007090 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007091 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007092 // In C++, a prefix increment is the same type as the operand. Otherwise
7093 // (in C or with postfix), the increment is the unqualified type of the
7094 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007095 if (isPrefix && S.getLangOptions().CPlusPlus) {
7096 VK = VK_LValue;
7097 return ResType;
7098 } else {
7099 VK = VK_RValue;
7100 return ResType.getUnqualifiedType();
7101 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007102}
7103
John McCall34376a62010-12-04 03:47:34 +00007104void Sema::ConvertPropertyForRValue(Expr *&E) {
7105 assert(E->getValueKind() == VK_LValue &&
7106 E->getObjectKind() == OK_ObjCProperty);
7107 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7108
7109 ExprValueKind VK = VK_RValue;
7110 if (PRE->isImplicitProperty()) {
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007111 if (const ObjCMethodDecl *GetterMethod =
7112 PRE->getImplicitPropertyGetter()) {
7113 QualType Result = GetterMethod->getResultType();
7114 VK = Expr::getValueKindForType(Result);
7115 }
7116 else {
7117 Diag(PRE->getLocation(), diag::err_getter_not_found)
7118 << PRE->getBase()->getType();
7119 }
John McCall34376a62010-12-04 03:47:34 +00007120 }
7121
7122 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7123 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007124
7125 ExprResult Result = MaybeBindToTemporary(E);
7126 if (!Result.isInvalid())
7127 E = Result.take();
John McCall34376a62010-12-04 03:47:34 +00007128}
7129
7130void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7131 assert(LHS->getValueKind() == VK_LValue &&
7132 LHS->getObjectKind() == OK_ObjCProperty);
7133 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7134
7135 if (PRE->isImplicitProperty()) {
7136 // If using property-dot syntax notation for assignment, and there is a
7137 // setter, RHS expression is being passed to the setter argument. So,
7138 // type conversion (and comparison) is RHS to setter's argument type.
7139 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7140 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7141 LHSTy = (*P)->getType();
7142
7143 // Otherwise, if the getter returns an l-value, just call that.
7144 } else {
7145 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7146 ExprValueKind VK = Expr::getValueKindForType(Result);
7147 if (VK == VK_LValue) {
7148 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7149 CK_GetObjCProperty, LHS, 0, VK);
7150 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007151 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007152 }
John McCall34376a62010-12-04 03:47:34 +00007153 }
7154
7155 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007156 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007157 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007158 Expr *Arg = RHS;
7159 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7160 Owned(Arg));
7161 if (!ArgE.isInvalid())
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007162 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007163 }
7164}
7165
7166
Anders Carlsson806700f2008-02-01 07:15:58 +00007167/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007168/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007169/// where the declaration is needed for type checking. We only need to
7170/// handle cases when the expression references a function designator
7171/// or is an lvalue. Here are some examples:
7172/// - &(x) => x
7173/// - &*****f => f for f a function designator.
7174/// - &s.xx => s
7175/// - &s.zz[1].yy -> s, if zz is an array
7176/// - *(x + 1) -> x, if x is an array
7177/// - &"123"[2] -> 0
7178/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007179static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007180 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007181 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007182 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007183 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007184 // If this is an arrow operator, the address is an offset from
7185 // the base's value, so the object the base refers to is
7186 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007187 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007188 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007189 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007190 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007191 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007192 // FIXME: This code shouldn't be necessary! We should catch the implicit
7193 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007194 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7195 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7196 if (ICE->getSubExpr()->getType()->isArrayType())
7197 return getPrimaryDecl(ICE->getSubExpr());
7198 }
7199 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007200 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007201 case Stmt::UnaryOperatorClass: {
7202 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007203
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007204 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007205 case UO_Real:
7206 case UO_Imag:
7207 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007208 return getPrimaryDecl(UO->getSubExpr());
7209 default:
7210 return 0;
7211 }
7212 }
Steve Naroff47500512007-04-19 23:00:49 +00007213 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007214 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007215 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007216 // If the result of an implicit cast is an l-value, we care about
7217 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007218 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007219 default:
7220 return 0;
7221 }
7222}
7223
7224/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007225/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007226/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007227/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007228/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007229/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007230/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007231static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7232 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007233 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007234 return S.Context.DependentTy;
7235 if (OrigOp->getType() == S.Context.OverloadTy)
7236 return S.Context.OverloadTy;
John McCall8d08b9b2010-08-27 09:08:28 +00007237
John McCall4bc41ae2010-11-18 19:01:18 +00007238 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007239 if (PR.isInvalid()) return QualType();
7240 OrigOp = PR.take();
7241
John McCall8d08b9b2010-08-27 09:08:28 +00007242 // Make sure to ignore parentheses in subsequent checks
7243 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007244
John McCall4bc41ae2010-11-18 19:01:18 +00007245 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007246 // Implement C99-only parts of addressof rules.
7247 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007248 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007249 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7250 // (assuming the deref expression is valid).
7251 return uOp->getSubExpr()->getType();
7252 }
7253 // Technically, there should be a check for array subscript
7254 // expressions here, but the result of one is always an lvalue anyway.
7255 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007256 NamedDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007257 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007258
Chris Lattner9156f1b2010-07-05 19:17:26 +00007259 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007260 bool sfinae = S.isSFINAEContext();
7261 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7262 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007263 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007264 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007265 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007266 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007267 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007268 } else if (lval == Expr::LV_MemberFunction) {
7269 // If it's an instance method, make a member pointer.
7270 // The expression must have exactly the form &A::foo.
7271
7272 // If the underlying expression isn't a decl ref, give up.
7273 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007274 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007275 << OrigOp->getSourceRange();
7276 return QualType();
7277 }
7278 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7279 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7280
7281 // The id-expression was parenthesized.
7282 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007283 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007284 << OrigOp->getSourceRange();
7285
7286 // The method was named without a qualifier.
7287 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007288 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007289 << op->getSourceRange();
7290 }
7291
John McCall4bc41ae2010-11-18 19:01:18 +00007292 return S.Context.getMemberPointerType(op->getType(),
7293 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007294 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007295 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007296 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007297 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007298 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007299 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007300 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007301 return QualType();
7302 }
John McCall086a4642010-11-24 05:12:34 +00007303 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007304 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007305 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007306 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007307 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007308 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007309 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007310 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007311 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007312 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007313 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007314 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007315 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007316 << "property expression" << op->getSourceRange();
7317 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007318 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007319 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007320 // with the register storage-class specifier.
7321 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007322 // in C++ it is not error to take address of a register
7323 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007324 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007325 !S.getLangOptions().CPlusPlus) {
7326 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007327 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007328 return QualType();
7329 }
John McCalld14a8642009-11-21 08:51:07 +00007330 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007331 return S.Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00007332 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007333 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007334 // Could be a pointer to member, though, if there is an explicit
7335 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007336 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007337 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007338 if (Ctx && Ctx->isRecord()) {
7339 if (FD->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007340 S.Diag(OpLoc,
7341 diag::err_cannot_form_pointer_to_member_of_reference_type)
Anders Carlsson0b675f52009-07-08 21:45:58 +00007342 << FD->getDeclName() << FD->getType();
7343 return QualType();
7344 }
Mike Stump11289f42009-09-09 15:08:12 +00007345
John McCall4bc41ae2010-11-18 19:01:18 +00007346 return S.Context.getMemberPointerType(op->getType(),
7347 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007348 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007349 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007350 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007351 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007352 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007353
Eli Friedmance7f9002009-05-16 23:27:50 +00007354 if (lval == Expr::LV_IncompleteVoidType) {
7355 // Taking the address of a void variable is technically illegal, but we
7356 // allow it in cases which are otherwise valid.
7357 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007358 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007359 }
7360
Steve Naroff47500512007-04-19 23:00:49 +00007361 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007362 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007363 return S.Context.getObjCObjectPointerType(op->getType());
7364 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007365}
7366
Chris Lattner9156f1b2010-07-05 19:17:26 +00007367/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007368static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7369 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007370 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007371 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007372
John McCall4bc41ae2010-11-18 19:01:18 +00007373 S.UsualUnaryConversions(Op);
Chris Lattner9156f1b2010-07-05 19:17:26 +00007374 QualType OpTy = Op->getType();
7375 QualType Result;
7376
7377 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7378 // is an incomplete type or void. It would be possible to warn about
7379 // dereferencing a void pointer, but it's completely well-defined, and such a
7380 // warning is unlikely to catch any mistakes.
7381 if (const PointerType *PT = OpTy->getAs<PointerType>())
7382 Result = PT->getPointeeType();
7383 else if (const ObjCObjectPointerType *OPT =
7384 OpTy->getAs<ObjCObjectPointerType>())
7385 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007386 else {
John McCall4bc41ae2010-11-18 19:01:18 +00007387 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007388 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007389 if (PR.take() != Op)
7390 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007391 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007392
Chris Lattner9156f1b2010-07-05 19:17:26 +00007393 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007394 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007395 << OpTy << Op->getSourceRange();
7396 return QualType();
7397 }
John McCall4bc41ae2010-11-18 19:01:18 +00007398
7399 // Dereferences are usually l-values...
7400 VK = VK_LValue;
7401
7402 // ...except that certain expressions are never l-values in C.
7403 if (!S.getLangOptions().CPlusPlus &&
7404 IsCForbiddenLValueType(S.Context, Result))
7405 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007406
7407 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007408}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007409
John McCalle3027922010-08-25 11:45:40 +00007410static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007411 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007412 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007413 switch (Kind) {
7414 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007415 case tok::periodstar: Opc = BO_PtrMemD; break;
7416 case tok::arrowstar: Opc = BO_PtrMemI; break;
7417 case tok::star: Opc = BO_Mul; break;
7418 case tok::slash: Opc = BO_Div; break;
7419 case tok::percent: Opc = BO_Rem; break;
7420 case tok::plus: Opc = BO_Add; break;
7421 case tok::minus: Opc = BO_Sub; break;
7422 case tok::lessless: Opc = BO_Shl; break;
7423 case tok::greatergreater: Opc = BO_Shr; break;
7424 case tok::lessequal: Opc = BO_LE; break;
7425 case tok::less: Opc = BO_LT; break;
7426 case tok::greaterequal: Opc = BO_GE; break;
7427 case tok::greater: Opc = BO_GT; break;
7428 case tok::exclaimequal: Opc = BO_NE; break;
7429 case tok::equalequal: Opc = BO_EQ; break;
7430 case tok::amp: Opc = BO_And; break;
7431 case tok::caret: Opc = BO_Xor; break;
7432 case tok::pipe: Opc = BO_Or; break;
7433 case tok::ampamp: Opc = BO_LAnd; break;
7434 case tok::pipepipe: Opc = BO_LOr; break;
7435 case tok::equal: Opc = BO_Assign; break;
7436 case tok::starequal: Opc = BO_MulAssign; break;
7437 case tok::slashequal: Opc = BO_DivAssign; break;
7438 case tok::percentequal: Opc = BO_RemAssign; break;
7439 case tok::plusequal: Opc = BO_AddAssign; break;
7440 case tok::minusequal: Opc = BO_SubAssign; break;
7441 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7442 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7443 case tok::ampequal: Opc = BO_AndAssign; break;
7444 case tok::caretequal: Opc = BO_XorAssign; break;
7445 case tok::pipeequal: Opc = BO_OrAssign; break;
7446 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007447 }
7448 return Opc;
7449}
7450
John McCalle3027922010-08-25 11:45:40 +00007451static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007452 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007453 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007454 switch (Kind) {
7455 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007456 case tok::plusplus: Opc = UO_PreInc; break;
7457 case tok::minusminus: Opc = UO_PreDec; break;
7458 case tok::amp: Opc = UO_AddrOf; break;
7459 case tok::star: Opc = UO_Deref; break;
7460 case tok::plus: Opc = UO_Plus; break;
7461 case tok::minus: Opc = UO_Minus; break;
7462 case tok::tilde: Opc = UO_Not; break;
7463 case tok::exclaim: Opc = UO_LNot; break;
7464 case tok::kw___real: Opc = UO_Real; break;
7465 case tok::kw___imag: Opc = UO_Imag; break;
7466 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007467 }
7468 return Opc;
7469}
7470
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007471/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7472/// This warning is only emitted for builtin assignment operations. It is also
7473/// suppressed in the event of macro expansions.
7474static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7475 SourceLocation OpLoc) {
7476 if (!S.ActiveTemplateInstantiations.empty())
7477 return;
7478 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7479 return;
7480 lhs = lhs->IgnoreParenImpCasts();
7481 rhs = rhs->IgnoreParenImpCasts();
7482 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7483 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7484 if (!LeftDeclRef || !RightDeclRef ||
7485 LeftDeclRef->getLocation().isMacroID() ||
7486 RightDeclRef->getLocation().isMacroID())
7487 return;
7488 const ValueDecl *LeftDecl =
7489 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7490 const ValueDecl *RightDecl =
7491 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7492 if (LeftDecl != RightDecl)
7493 return;
7494 if (LeftDecl->getType().isVolatileQualified())
7495 return;
7496 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7497 if (RefTy->getPointeeType().isVolatileQualified())
7498 return;
7499
7500 S.Diag(OpLoc, diag::warn_self_assignment)
7501 << LeftDeclRef->getType()
7502 << lhs->getSourceRange() << rhs->getSourceRange();
7503}
7504
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007505/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7506/// operator @p Opc at location @c TokLoc. This routine only supports
7507/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007508ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007509 BinaryOperatorKind Opc,
John McCalle3027922010-08-25 11:45:40 +00007510 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007511 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007512 // The following two variables are used for compound assignment operators
7513 QualType CompLHSTy; // Type of LHS after promotions for computation
7514 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007515 ExprValueKind VK = VK_RValue;
7516 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007517
7518 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007519 case BO_Assign:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007520 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007521 if (getLangOptions().CPlusPlus &&
7522 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall4bc41ae2010-11-18 19:01:18 +00007523 VK = lhs->getValueKind();
7524 OK = lhs->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007525 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007526 if (!ResultTy.isNull())
7527 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007528 break;
John McCalle3027922010-08-25 11:45:40 +00007529 case BO_PtrMemD:
7530 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007531 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007532 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007533 break;
John McCalle3027922010-08-25 11:45:40 +00007534 case BO_Mul:
7535 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007536 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007537 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007538 break;
John McCalle3027922010-08-25 11:45:40 +00007539 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007540 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7541 break;
John McCalle3027922010-08-25 11:45:40 +00007542 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007543 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7544 break;
John McCalle3027922010-08-25 11:45:40 +00007545 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007546 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7547 break;
John McCalle3027922010-08-25 11:45:40 +00007548 case BO_Shl:
7549 case BO_Shr:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007550 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
7551 break;
John McCalle3027922010-08-25 11:45:40 +00007552 case BO_LE:
7553 case BO_LT:
7554 case BO_GE:
7555 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007556 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007557 break;
John McCalle3027922010-08-25 11:45:40 +00007558 case BO_EQ:
7559 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007560 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007561 break;
John McCalle3027922010-08-25 11:45:40 +00007562 case BO_And:
7563 case BO_Xor:
7564 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007565 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7566 break;
John McCalle3027922010-08-25 11:45:40 +00007567 case BO_LAnd:
7568 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007569 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007570 break;
John McCalle3027922010-08-25 11:45:40 +00007571 case BO_MulAssign:
7572 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007573 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007574 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007575 CompLHSTy = CompResultTy;
7576 if (!CompResultTy.isNull())
7577 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007578 break;
John McCalle3027922010-08-25 11:45:40 +00007579 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007580 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7581 CompLHSTy = CompResultTy;
7582 if (!CompResultTy.isNull())
7583 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007584 break;
John McCalle3027922010-08-25 11:45:40 +00007585 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007586 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7587 if (!CompResultTy.isNull())
7588 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007589 break;
John McCalle3027922010-08-25 11:45:40 +00007590 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007591 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7592 if (!CompResultTy.isNull())
7593 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007594 break;
John McCalle3027922010-08-25 11:45:40 +00007595 case BO_ShlAssign:
7596 case BO_ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007597 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
7598 CompLHSTy = CompResultTy;
7599 if (!CompResultTy.isNull())
7600 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007601 break;
John McCalle3027922010-08-25 11:45:40 +00007602 case BO_AndAssign:
7603 case BO_XorAssign:
7604 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007605 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7606 CompLHSTy = CompResultTy;
7607 if (!CompResultTy.isNull())
7608 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007609 break;
John McCalle3027922010-08-25 11:45:40 +00007610 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007611 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCall7decc9e2010-11-18 06:31:45 +00007612 if (getLangOptions().CPlusPlus) {
7613 VK = rhs->getValueKind();
7614 OK = rhs->getObjectKind();
7615 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007616 break;
7617 }
7618 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007619 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007620 if (CompResultTy.isNull())
John McCall7decc9e2010-11-18 06:31:45 +00007621 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
7622 VK, OK, OpLoc));
7623
John McCall34376a62010-12-04 03:47:34 +00007624 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007625 VK = VK_LValue;
7626 OK = lhs->getObjectKind();
7627 }
7628 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
7629 VK, OK, CompLHSTy,
7630 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007631}
7632
Sebastian Redl44615072009-10-27 12:10:02 +00007633/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
7634/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007635static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7636 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007637 const PartialDiagnostic &FirstNote,
7638 SourceRange FirstParenRange,
7639 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00007640 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007641 Self.Diag(Loc, PD);
7642
7643 if (!FirstNote.getDiagID())
7644 return;
7645
7646 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
7647 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7648 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007649 return;
7650 }
7651
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007652 Self.Diag(Loc, FirstNote)
7653 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00007654 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007655
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007656 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007657 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007658
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007659 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
7660 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7661 // We can't display the parentheses, so just dig the
7662 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007663 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007664 return;
7665 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007666
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007667 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00007668 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
7669 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007670}
7671
Sebastian Redl44615072009-10-27 12:10:02 +00007672/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7673/// operators are mixed in a way that suggests that the programmer forgot that
7674/// comparison operators have higher precedence. The most typical example of
7675/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007676static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007677 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007678 typedef BinaryOperator BinOp;
7679 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7680 rhsopc = static_cast<BinOp::Opcode>(-1);
7681 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007682 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007683 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007684 rhsopc = BO->getOpcode();
7685
7686 // Subs are not binary operators.
7687 if (lhsopc == -1 && rhsopc == -1)
7688 return;
7689
7690 // Bitwise operations are sometimes used as eager logical ops.
7691 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007692 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7693 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007694 return;
7695
Sebastian Redl44615072009-10-27 12:10:02 +00007696 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007697 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007698 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00007699 << SourceRange(lhs->getLocStart(), OpLoc)
7700 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00007701 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007702 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007703 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
7704 Self.PDiag(diag::note_precedence_bitwise_silence)
7705 << BinOp::getOpcodeStr(lhsopc),
7706 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00007707 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007708 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007709 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00007710 << SourceRange(OpLoc, rhs->getLocEnd())
7711 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00007712 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007713 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007714 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
7715 Self.PDiag(diag::note_precedence_bitwise_silence)
7716 << BinOp::getOpcodeStr(rhsopc),
7717 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00007718}
7719
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007720/// \brief It accepts a '&&' expr that is inside a '||' one.
7721/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7722/// in parentheses.
7723static void
7724EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
7725 Expr *E) {
7726 assert(isa<BinaryOperator>(E) &&
7727 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
7728 SuggestParentheses(Self, OpLoc,
7729 Self.PDiag(diag::warn_logical_and_in_logical_or)
7730 << E->getSourceRange(),
7731 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
7732 E->getSourceRange(),
7733 Self.PDiag(0), SourceRange());
7734}
7735
7736/// \brief Returns true if the given expression can be evaluated as a constant
7737/// 'true'.
7738static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7739 bool Res;
7740 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7741}
7742
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007743/// \brief Returns true if the given expression can be evaluated as a constant
7744/// 'false'.
7745static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7746 bool Res;
7747 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7748}
7749
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007750/// \brief Look for '&&' in the left hand of a '||' expr.
7751static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007752 Expr *OrLHS, Expr *OrRHS) {
7753 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007754 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007755 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7756 if (EvaluatesAsFalse(S, OrRHS))
7757 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007758 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7759 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7760 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7761 } else if (Bop->getOpcode() == BO_LOr) {
7762 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7763 // If it's "a || b && 1 || c" we didn't warn earlier for
7764 // "a || b && 1", but warn now.
7765 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7766 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7767 }
7768 }
7769 }
7770}
7771
7772/// \brief Look for '&&' in the right hand of a '||' expr.
7773static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007774 Expr *OrLHS, Expr *OrRHS) {
7775 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007776 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007777 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7778 if (EvaluatesAsFalse(S, OrLHS))
7779 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007780 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7781 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7782 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007783 }
7784 }
7785}
7786
Sebastian Redl43028242009-10-26 15:24:15 +00007787/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007788/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007789static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007790 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007791 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007792 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007793 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7794
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007795 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7796 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007797 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007798 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7799 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007800 }
Sebastian Redl43028242009-10-26 15:24:15 +00007801}
7802
Steve Naroff218bc2b2007-05-04 21:54:46 +00007803// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007804ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00007805 tok::TokenKind Kind,
7806 Expr *lhs, Expr *rhs) {
7807 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00007808 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7809 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00007810
Sebastian Redl43028242009-10-26 15:24:15 +00007811 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7812 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7813
Douglas Gregor5287f092009-11-05 00:51:44 +00007814 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7815}
7816
John McCalldadc5752010-08-24 06:29:42 +00007817ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007818 BinaryOperatorKind Opc,
7819 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00007820 if (getLangOptions().CPlusPlus) {
7821 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007822
John McCall622114c2010-12-06 05:26:58 +00007823 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7824 UseBuiltinOperator = false;
7825 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7826 UseBuiltinOperator = true;
7827 } else {
7828 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7829 !rhs->getType()->isOverloadableType();
7830 }
7831
7832 if (!UseBuiltinOperator) {
7833 // Find all of the overloaded operators visible from this
7834 // point. We perform both an operator-name lookup from the local
7835 // scope and an argument-dependent lookup based on the types of
7836 // the arguments.
7837 UnresolvedSet<16> Functions;
7838 OverloadedOperatorKind OverOp
7839 = BinaryOperator::getOverloadedOperator(Opc);
7840 if (S && OverOp != OO_None)
7841 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7842 Functions);
7843
7844 // Build the (potentially-overloaded, potentially-dependent)
7845 // binary operation.
7846 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7847 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00007848 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007849
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007850 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00007851 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007852}
7853
John McCalldadc5752010-08-24 06:29:42 +00007854ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007855 UnaryOperatorKind Opc,
John McCall36226622010-10-12 02:09:17 +00007856 Expr *Input) {
John McCall7decc9e2010-11-18 06:31:45 +00007857 ExprValueKind VK = VK_RValue;
7858 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00007859 QualType resultType;
7860 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007861 case UO_PreInc:
7862 case UO_PreDec:
7863 case UO_PostInc:
7864 case UO_PostDec:
John McCall4bc41ae2010-11-18 19:01:18 +00007865 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007866 Opc == UO_PreInc ||
7867 Opc == UO_PostInc,
7868 Opc == UO_PreInc ||
7869 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00007870 break;
John McCalle3027922010-08-25 11:45:40 +00007871 case UO_AddrOf:
John McCall4bc41ae2010-11-18 19:01:18 +00007872 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007873 break;
John McCalle3027922010-08-25 11:45:40 +00007874 case UO_Deref:
Douglas Gregorb92a1562010-02-03 00:27:59 +00007875 DefaultFunctionArrayLvalueConversion(Input);
John McCall4bc41ae2010-11-18 19:01:18 +00007876 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007877 break;
John McCalle3027922010-08-25 11:45:40 +00007878 case UO_Plus:
7879 case UO_Minus:
Steve Naroff31090012007-07-16 21:54:35 +00007880 UsualUnaryConversions(Input);
7881 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007882 if (resultType->isDependentType())
7883 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00007884 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7885 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00007886 break;
7887 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7888 resultType->isEnumeralType())
7889 break;
7890 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00007891 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00007892 resultType->isPointerType())
7893 break;
John McCall36226622010-10-12 02:09:17 +00007894 else if (resultType->isPlaceholderType()) {
7895 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7896 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007897 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00007898 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007899
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007900 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7901 << resultType << Input->getSourceRange());
John McCalle3027922010-08-25 11:45:40 +00007902 case UO_Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00007903 UsualUnaryConversions(Input);
7904 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007905 if (resultType->isDependentType())
7906 break;
Chris Lattner0d707612008-07-25 23:52:49 +00007907 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
7908 if (resultType->isComplexType() || resultType->isComplexIntegerType())
7909 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00007910 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007911 << resultType << Input->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007912 else if (resultType->hasIntegerRepresentation())
7913 break;
7914 else if (resultType->isPlaceholderType()) {
7915 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7916 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007917 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00007918 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007919 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7920 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007921 }
Steve Naroff35d85152007-05-07 00:24:15 +00007922 break;
John McCalle3027922010-08-25 11:45:40 +00007923 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00007924 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00007925 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00007926 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007927 if (resultType->isDependentType())
7928 break;
John McCall36226622010-10-12 02:09:17 +00007929 if (resultType->isScalarType()) { // C99 6.5.3.3p1
7930 // ok, fallthrough
7931 } else if (resultType->isPlaceholderType()) {
7932 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7933 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007934 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00007935 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007936 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7937 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007938 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00007939
Chris Lattnerbe31ed82007-06-02 19:11:33 +00007940 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007941 // In C++, it's bool. C++ 5.3.1p8
7942 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00007943 break;
John McCalle3027922010-08-25 11:45:40 +00007944 case UO_Real:
7945 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00007946 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00007947 // _Real and _Imag map ordinary l-values into ordinary l-values.
7948 if (Input->getValueKind() != VK_RValue &&
7949 Input->getObjectKind() == OK_Ordinary)
7950 VK = Input->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00007951 break;
John McCalle3027922010-08-25 11:45:40 +00007952 case UO_Extension:
Chris Lattner86554282007-06-08 22:32:33 +00007953 resultType = Input->getType();
John McCall7decc9e2010-11-18 06:31:45 +00007954 VK = Input->getValueKind();
7955 OK = Input->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00007956 break;
Steve Naroff35d85152007-05-07 00:24:15 +00007957 }
7958 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007959 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00007960
John McCall7decc9e2010-11-18 06:31:45 +00007961 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
7962 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00007963}
Chris Lattnereefa10e2007-05-28 06:56:27 +00007964
John McCalldadc5752010-08-24 06:29:42 +00007965ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007966 UnaryOperatorKind Opc,
7967 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00007968 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00007969 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007970 // Find all of the overloaded operators visible from this
7971 // point. We perform both an operator-name lookup from the local
7972 // scope and an argument-dependent lookup based on the types of
7973 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00007974 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00007975 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00007976 if (S && OverOp != OO_None)
7977 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
7978 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007979
John McCallb268a282010-08-23 23:25:46 +00007980 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007981 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007982
John McCallb268a282010-08-23 23:25:46 +00007983 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007984}
7985
Douglas Gregor5287f092009-11-05 00:51:44 +00007986// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007987ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00007988 tok::TokenKind Op, Expr *Input) {
7989 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00007990}
7991
Steve Naroff66356bd2007-09-16 14:56:35 +00007992/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
John McCalldadc5752010-08-24 06:29:42 +00007993ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007994 SourceLocation LabLoc,
7995 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00007996 // Look up the record for this label identifier.
John McCallaab3e412010-08-25 08:40:02 +00007997 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00007998
Daniel Dunbar88402ce2008-08-04 16:51:22 +00007999 // If we haven't seen this label yet, create a forward reference. It
8000 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00008001 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00008002 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008003
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00008004 LabelDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008005 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008006 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
8007 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008008}
8009
John McCalldadc5752010-08-24 06:29:42 +00008010ExprResult
John McCallb268a282010-08-23 23:25:46 +00008011Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008012 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008013 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8014 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8015
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008016 bool isFileScope
8017 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008018 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008019 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008020
Chris Lattner366727f2007-07-24 16:58:17 +00008021 // FIXME: there are a variety of strange constraints to enforce here, for
8022 // example, it is not possible to goto into a stmt expression apparently.
8023 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008024
Chris Lattner366727f2007-07-24 16:58:17 +00008025 // If there are sub stmts in the compound stmt, take the type of the last one
8026 // as the type of the stmtexpr.
8027 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008028 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008029 if (!Compound->body_empty()) {
8030 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008031 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008032 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008033 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8034 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008035 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008036 }
8037 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008038 // Do function/array conversion on the last expression, but not
8039 // lvalue-to-rvalue. However, initialize an unqualified type.
8040 DefaultFunctionArrayConversion(LastExpr);
8041 Ty = LastExpr->getType().getUnqualifiedType();
8042
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008043 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8044 ExprResult Res = PerformCopyInitialization(
8045 InitializedEntity::InitializeResult(LPLoc,
8046 Ty,
8047 false),
8048 SourceLocation(),
8049 Owned(LastExpr));
8050 if (Res.isInvalid())
8051 return ExprError();
8052 if ((LastExpr = Res.takeAs<Expr>())) {
8053 if (!LastLabelStmt)
8054 Compound->setLastStmt(LastExpr);
8055 else
8056 LastLabelStmt->setSubStmt(LastExpr);
8057 StmtExprMayBindToTemp = true;
8058 }
8059 }
8060 }
Chris Lattner944d3062008-07-26 19:51:01 +00008061 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008062
Eli Friedmanba961a92009-03-23 00:24:07 +00008063 // FIXME: Check that expression type is complete/non-abstract; statement
8064 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008065 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8066 if (StmtExprMayBindToTemp)
8067 return MaybeBindToTemporary(ResStmtExpr);
8068 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008069}
Steve Naroff78864672007-08-01 22:05:33 +00008070
John McCalldadc5752010-08-24 06:29:42 +00008071ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008072 TypeSourceInfo *TInfo,
8073 OffsetOfComponent *CompPtr,
8074 unsigned NumComponents,
8075 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008076 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008077 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008078 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008079
Chris Lattnerf17bd422007-08-30 17:45:32 +00008080 // We must have at least one component that refers to the type, and the first
8081 // one is known to be a field designator. Verify that the ArgTy represents
8082 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008083 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008084 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8085 << ArgTy << TypeRange);
8086
8087 // Type must be complete per C99 7.17p3 because a declaring a variable
8088 // with an incomplete type would be ill-formed.
8089 if (!Dependent
8090 && RequireCompleteType(BuiltinLoc, ArgTy,
8091 PDiag(diag::err_offsetof_incomplete_type)
8092 << TypeRange))
8093 return ExprError();
8094
Chris Lattner78502cf2007-08-31 21:49:13 +00008095 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8096 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008097 // FIXME: This diagnostic isn't actually visible because the location is in
8098 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008099 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008100 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8101 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008102
8103 bool DidWarnAboutNonPOD = false;
8104 QualType CurrentType = ArgTy;
8105 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8106 llvm::SmallVector<OffsetOfNode, 4> Comps;
8107 llvm::SmallVector<Expr*, 4> Exprs;
8108 for (unsigned i = 0; i != NumComponents; ++i) {
8109 const OffsetOfComponent &OC = CompPtr[i];
8110 if (OC.isBrackets) {
8111 // Offset of an array sub-field. TODO: Should we allow vector elements?
8112 if (!CurrentType->isDependentType()) {
8113 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8114 if(!AT)
8115 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8116 << CurrentType);
8117 CurrentType = AT->getElementType();
8118 } else
8119 CurrentType = Context.DependentTy;
8120
8121 // The expression must be an integral expression.
8122 // FIXME: An integral constant expression?
8123 Expr *Idx = static_cast<Expr*>(OC.U.E);
8124 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8125 !Idx->getType()->isIntegerType())
8126 return ExprError(Diag(Idx->getLocStart(),
8127 diag::err_typecheck_subscript_not_integer)
8128 << Idx->getSourceRange());
8129
8130 // Record this array index.
8131 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8132 Exprs.push_back(Idx);
8133 continue;
8134 }
8135
8136 // Offset of a field.
8137 if (CurrentType->isDependentType()) {
8138 // We have the offset of a field, but we can't look into the dependent
8139 // type. Just record the identifier of the field.
8140 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8141 CurrentType = Context.DependentTy;
8142 continue;
8143 }
8144
8145 // We need to have a complete type to look into.
8146 if (RequireCompleteType(OC.LocStart, CurrentType,
8147 diag::err_offsetof_incomplete_type))
8148 return ExprError();
8149
8150 // Look for the designated field.
8151 const RecordType *RC = CurrentType->getAs<RecordType>();
8152 if (!RC)
8153 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8154 << CurrentType);
8155 RecordDecl *RD = RC->getDecl();
8156
8157 // C++ [lib.support.types]p5:
8158 // The macro offsetof accepts a restricted set of type arguments in this
8159 // International Standard. type shall be a POD structure or a POD union
8160 // (clause 9).
8161 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8162 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8163 DiagRuntimeBehavior(BuiltinLoc,
8164 PDiag(diag::warn_offsetof_non_pod_type)
8165 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8166 << CurrentType))
8167 DidWarnAboutNonPOD = true;
8168 }
8169
8170 // Look for the field.
8171 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8172 LookupQualifiedName(R, RD);
8173 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008174 IndirectFieldDecl *IndirectMemberDecl = 0;
8175 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008176 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008177 MemberDecl = IndirectMemberDecl->getAnonField();
8178 }
8179
Douglas Gregor882211c2010-04-28 22:16:22 +00008180 if (!MemberDecl)
8181 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8182 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8183 OC.LocEnd));
8184
Douglas Gregor10982ea2010-04-28 22:36:06 +00008185 // C99 7.17p3:
8186 // (If the specified member is a bit-field, the behavior is undefined.)
8187 //
8188 // We diagnose this as an error.
8189 if (MemberDecl->getBitWidth()) {
8190 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8191 << MemberDecl->getDeclName()
8192 << SourceRange(BuiltinLoc, RParenLoc);
8193 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8194 return ExprError();
8195 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008196
8197 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008198 if (IndirectMemberDecl)
8199 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008200
Douglas Gregord1702062010-04-29 00:18:15 +00008201 // If the member was found in a base class, introduce OffsetOfNodes for
8202 // the base class indirections.
8203 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8204 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008205 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008206 CXXBasePath &Path = Paths.front();
8207 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8208 B != BEnd; ++B)
8209 Comps.push_back(OffsetOfNode(B->Base));
8210 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008211
Francois Pichet783dd6e2010-11-21 06:08:52 +00008212 if (IndirectMemberDecl) {
8213 for (IndirectFieldDecl::chain_iterator FI =
8214 IndirectMemberDecl->chain_begin(),
8215 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8216 assert(isa<FieldDecl>(*FI));
8217 Comps.push_back(OffsetOfNode(OC.LocStart,
8218 cast<FieldDecl>(*FI), OC.LocEnd));
8219 }
8220 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008221 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008222
Douglas Gregor882211c2010-04-28 22:16:22 +00008223 CurrentType = MemberDecl->getType().getNonReferenceType();
8224 }
8225
8226 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8227 TInfo, Comps.data(), Comps.size(),
8228 Exprs.data(), Exprs.size(), RParenLoc));
8229}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008230
John McCalldadc5752010-08-24 06:29:42 +00008231ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008232 SourceLocation BuiltinLoc,
8233 SourceLocation TypeLoc,
8234 ParsedType argty,
8235 OffsetOfComponent *CompPtr,
8236 unsigned NumComponents,
8237 SourceLocation RPLoc) {
8238
Douglas Gregor882211c2010-04-28 22:16:22 +00008239 TypeSourceInfo *ArgTInfo;
8240 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8241 if (ArgTy.isNull())
8242 return ExprError();
8243
Eli Friedman06dcfd92010-08-05 10:15:45 +00008244 if (!ArgTInfo)
8245 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8246
8247 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8248 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008249}
8250
8251
John McCalldadc5752010-08-24 06:29:42 +00008252ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008253 Expr *CondExpr,
8254 Expr *LHSExpr, Expr *RHSExpr,
8255 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008256 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8257
John McCall7decc9e2010-11-18 06:31:45 +00008258 ExprValueKind VK = VK_RValue;
8259 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008260 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008261 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008262 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008263 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008264 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008265 } else {
8266 // The conditional expression is required to be a constant expression.
8267 llvm::APSInt condEval(32);
8268 SourceLocation ExpLoc;
8269 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008270 return ExprError(Diag(ExpLoc,
8271 diag::err_typecheck_choose_expr_requires_constant)
8272 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008273
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008274 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008275 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8276
8277 resType = ActiveExpr->getType();
8278 ValueDependent = ActiveExpr->isValueDependent();
8279 VK = ActiveExpr->getValueKind();
8280 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008281 }
8282
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008283 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008284 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008285 resType->isDependentType(),
8286 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008287}
8288
Steve Naroffc540d662008-09-03 18:15:37 +00008289//===----------------------------------------------------------------------===//
8290// Clang Extensions.
8291//===----------------------------------------------------------------------===//
8292
8293/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008294void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008295 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8296 PushBlockScope(BlockScope, Block);
8297 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008298 if (BlockScope)
8299 PushDeclContext(BlockScope, Block);
8300 else
8301 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008302}
8303
Mike Stump82f071f2009-02-04 22:31:32 +00008304void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008305 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008306 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008307 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008308
John McCall8cb7bdf2010-06-04 23:28:52 +00008309 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008310 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008311
John McCall3882ace2011-01-05 12:14:39 +00008312 // GetTypeForDeclarator always produces a function type for a block
8313 // literal signature. Furthermore, it is always a FunctionProtoType
8314 // unless the function was written with a typedef.
8315 assert(T->isFunctionType() &&
8316 "GetTypeForDeclarator made a non-function block signature");
8317
8318 // Look for an explicit signature in that function type.
8319 FunctionProtoTypeLoc ExplicitSignature;
8320
8321 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8322 if (isa<FunctionProtoTypeLoc>(tmp)) {
8323 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8324
8325 // Check whether that explicit signature was synthesized by
8326 // GetTypeForDeclarator. If so, don't save that as part of the
8327 // written signature.
8328 if (ExplicitSignature.getLParenLoc() ==
8329 ExplicitSignature.getRParenLoc()) {
8330 // This would be much cheaper if we stored TypeLocs instead of
8331 // TypeSourceInfos.
8332 TypeLoc Result = ExplicitSignature.getResultLoc();
8333 unsigned Size = Result.getFullDataSize();
8334 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8335 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8336
8337 ExplicitSignature = FunctionProtoTypeLoc();
8338 }
John McCalla3ccba02010-06-04 11:21:44 +00008339 }
Mike Stump11289f42009-09-09 15:08:12 +00008340
John McCall3882ace2011-01-05 12:14:39 +00008341 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8342 CurBlock->FunctionType = T;
8343
8344 const FunctionType *Fn = T->getAs<FunctionType>();
8345 QualType RetTy = Fn->getResultType();
8346 bool isVariadic =
8347 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8348
John McCall8e346702010-06-04 19:02:56 +00008349 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008350
John McCalla3ccba02010-06-04 11:21:44 +00008351 // Don't allow returning a objc interface by value.
8352 if (RetTy->isObjCObjectType()) {
8353 Diag(ParamInfo.getSourceRange().getBegin(),
8354 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8355 return;
8356 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008357
John McCalla3ccba02010-06-04 11:21:44 +00008358 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008359 // return type. TODO: what should we do with declarators like:
8360 // ^ * { ... }
8361 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008362 if (RetTy != Context.DependentTy)
8363 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008364
John McCalla3ccba02010-06-04 11:21:44 +00008365 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00008366 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008367 if (ExplicitSignature) {
8368 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8369 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008370 if (Param->getIdentifier() == 0 &&
8371 !Param->isImplicit() &&
8372 !Param->isInvalidDecl() &&
8373 !getLangOptions().CPlusPlus)
8374 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008375 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008376 }
John McCalla3ccba02010-06-04 11:21:44 +00008377
8378 // Fake up parameter variables if we have a typedef, like
8379 // ^ fntype { ... }
8380 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8381 for (FunctionProtoType::arg_type_iterator
8382 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8383 ParmVarDecl *Param =
8384 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8385 ParamInfo.getSourceRange().getBegin(),
8386 *I);
John McCall8e346702010-06-04 19:02:56 +00008387 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008388 }
Steve Naroffc540d662008-09-03 18:15:37 +00008389 }
John McCalla3ccba02010-06-04 11:21:44 +00008390
John McCall8e346702010-06-04 19:02:56 +00008391 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008392 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008393 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008394 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8395 CurBlock->TheDecl->param_end(),
8396 /*CheckParameterNames=*/false);
8397 }
8398
John McCalla3ccba02010-06-04 11:21:44 +00008399 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008400 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008401
John McCall8e346702010-06-04 19:02:56 +00008402 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008403 Diag(ParamInfo.getAttributes()->getLoc(),
8404 diag::warn_attribute_sentinel_not_variadic) << 1;
8405 // FIXME: remove the attribute.
8406 }
8407
8408 // Put the parameter variables in scope. We can bail out immediately
8409 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008410 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008411 return;
8412
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008413 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008414 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8415 (*AI)->setOwningFunction(CurBlock->TheDecl);
8416
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008417 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008418 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008419 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008420
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008421 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008422 }
John McCallf7b2fb52010-01-22 00:28:27 +00008423 }
Steve Naroffc540d662008-09-03 18:15:37 +00008424}
8425
8426/// ActOnBlockError - If there is an error parsing a block, this callback
8427/// is invoked to pop the information about the block from the action impl.
8428void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008429 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008430 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008431 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008432}
8433
8434/// ActOnBlockStmtExpr - This is called when the body of a block statement
8435/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008436ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
John McCallb268a282010-08-23 23:25:46 +00008437 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008438 // If blocks are disabled, emit an error.
8439 if (!LangOpts.Blocks)
8440 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008441
Douglas Gregor9a28e842010-03-01 23:15:13 +00008442 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008443
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008444 PopDeclContext();
8445
Steve Naroffc540d662008-09-03 18:15:37 +00008446 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008447 if (!BSI->ReturnType.isNull())
8448 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008449
Mike Stump3bf1ab42009-07-28 22:04:01 +00008450 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008451 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008452
8453 // If the user wrote a function type in some form, try to use that.
8454 if (!BSI->FunctionType.isNull()) {
8455 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8456
8457 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8458 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8459
8460 // Turn protoless block types into nullary block types.
8461 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008462 FunctionProtoType::ExtProtoInfo EPI;
8463 EPI.ExtInfo = Ext;
8464 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008465
8466 // Otherwise, if we don't need to change anything about the function type,
8467 // preserve its sugar structure.
8468 } else if (FTy->getResultType() == RetTy &&
8469 (!NoReturn || FTy->getNoReturnAttr())) {
8470 BlockTy = BSI->FunctionType;
8471
8472 // Otherwise, make the minimal modifications to the function type.
8473 } else {
8474 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008475 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8476 EPI.TypeQuals = 0; // FIXME: silently?
8477 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008478 BlockTy = Context.getFunctionType(RetTy,
8479 FPT->arg_type_begin(),
8480 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008481 EPI);
John McCall8e346702010-06-04 19:02:56 +00008482 }
8483
8484 // If we don't have a function type, just build one from nothing.
8485 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008486 FunctionProtoType::ExtProtoInfo EPI;
8487 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
8488 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008489 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008490
John McCall8e346702010-06-04 19:02:56 +00008491 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8492 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008493 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008494
Chris Lattner45542ea2009-04-19 05:28:12 +00008495 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00008496 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008497 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008498
John McCallb268a282010-08-23 23:25:46 +00008499 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Mike Stump314825b2010-01-19 23:08:01 +00008500
8501 bool Good = true;
8502 // Check goto/label use.
8503 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
8504 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
8505 LabelStmt *L = I->second;
8506
8507 // Verify that we have no forward references left. If so, there was a goto
8508 // or address of a label taken, but no definition of it.
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00008509 if (L->getSubStmt() != 0) {
8510 if (!L->isUsed())
8511 Diag(L->getIdentLoc(), diag::warn_unused_label) << L->getName();
Mike Stump314825b2010-01-19 23:08:01 +00008512 continue;
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00008513 }
Mike Stump314825b2010-01-19 23:08:01 +00008514
8515 // Emit error.
8516 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
8517 Good = false;
8518 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00008519 if (!Good) {
8520 PopFunctionOrBlockScope();
Mike Stump314825b2010-01-19 23:08:01 +00008521 return ExprError();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008522 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008523
John McCall1d570a72010-08-25 05:56:39 +00008524 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
8525 BSI->hasBlockDeclRefExprs);
8526
Ted Kremenek918fe842010-03-20 21:06:02 +00008527 // Issue any analysis-based warnings.
Ted Kremenek0b405322010-03-23 00:13:23 +00008528 const sema::AnalysisBasedWarnings::Policy &WP =
8529 AnalysisWarnings.getDefaultPolicy();
John McCall1d570a72010-08-25 05:56:39 +00008530 AnalysisWarnings.IssueWarnings(WP, Result);
Ted Kremenek918fe842010-03-20 21:06:02 +00008531
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008532 PopFunctionOrBlockScope();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008533 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008534}
8535
John McCalldadc5752010-08-24 06:29:42 +00008536ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008537 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008538 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008539 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008540 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008541 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008542}
8543
John McCalldadc5752010-08-24 06:29:42 +00008544ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008545 Expr *E, TypeSourceInfo *TInfo,
8546 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008547 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008548
Eli Friedman121ba0c2008-08-09 23:32:40 +00008549 // Get the va_list type
8550 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008551 if (VaListType->isArrayType()) {
8552 // Deal with implicit array decay; for example, on x86-64,
8553 // va_list is an array, but it's supposed to decay to
8554 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008555 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008556 // Make sure the input expression also decays appropriately.
8557 UsualUnaryConversions(E);
8558 } else {
8559 // Otherwise, the va_list argument must be an l-value because
8560 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008561 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008562 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008563 return ExprError();
8564 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008565
Douglas Gregorad3150c2009-05-19 23:10:31 +00008566 if (!E->isTypeDependent() &&
8567 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008568 return ExprError(Diag(E->getLocStart(),
8569 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008570 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008571 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008572
Eli Friedmanba961a92009-03-23 00:24:07 +00008573 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008574 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008575
Abramo Bagnara27db2392010-08-10 10:06:15 +00008576 QualType T = TInfo->getType().getNonLValueExprType(Context);
8577 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008578}
8579
John McCalldadc5752010-08-24 06:29:42 +00008580ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008581 // The type of __null will be int or long, depending on the size of
8582 // pointers on the target.
8583 QualType Ty;
8584 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
8585 Ty = Context.IntTy;
8586 else
8587 Ty = Context.LongTy;
8588
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008589 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008590}
8591
Alexis Huntc46382e2010-04-28 23:02:27 +00008592static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008593 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008594 if (!SemaRef.getLangOptions().ObjC1)
8595 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008596
Anders Carlssonace5d072009-11-10 04:46:30 +00008597 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8598 if (!PT)
8599 return;
8600
8601 // Check if the destination is of type 'id'.
8602 if (!PT->isObjCIdType()) {
8603 // Check if the destination is the 'NSString' interface.
8604 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8605 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8606 return;
8607 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008608
Anders Carlssonace5d072009-11-10 04:46:30 +00008609 // Strip off any parens and casts.
8610 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8611 if (!SL || SL->isWide())
8612 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008613
Douglas Gregora771f462010-03-31 17:46:05 +00008614 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008615}
8616
Chris Lattner9bad62c2008-01-04 18:04:52 +00008617bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8618 SourceLocation Loc,
8619 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008620 Expr *SrcExpr, AssignmentAction Action,
8621 bool *Complained) {
8622 if (Complained)
8623 *Complained = false;
8624
Chris Lattner9bad62c2008-01-04 18:04:52 +00008625 // Decode the result (notice that AST's are still created for extensions).
8626 bool isInvalid = false;
8627 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008628 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008629
Chris Lattner9bad62c2008-01-04 18:04:52 +00008630 switch (ConvTy) {
8631 default: assert(0 && "Unknown conversion type");
8632 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008633 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008634 DiagKind = diag::ext_typecheck_convert_pointer_int;
8635 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008636 case IntToPointer:
8637 DiagKind = diag::ext_typecheck_convert_int_pointer;
8638 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008639 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008640 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008641 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
8642 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008643 case IncompatiblePointerSign:
8644 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8645 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008646 case FunctionVoidPointer:
8647 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8648 break;
8649 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008650 // If the qualifiers lost were because we were applying the
8651 // (deprecated) C++ conversion from a string literal to a char*
8652 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8653 // Ideally, this check would be performed in
8654 // CheckPointerTypesForAssignment. However, that would require a
8655 // bit of refactoring (so that the second argument is an
8656 // expression, rather than a type), which should be done as part
8657 // of a larger effort to fix CheckPointerTypesForAssignment for
8658 // C++ semantics.
8659 if (getLangOptions().CPlusPlus &&
8660 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8661 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008662 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8663 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008664 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008665 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008666 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008667 case IntToBlockPointer:
8668 DiagKind = diag::err_int_to_block_pointer;
8669 break;
8670 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008671 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008672 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008673 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008674 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008675 // it can give a more specific diagnostic.
8676 DiagKind = diag::warn_incompatible_qualified_id;
8677 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008678 case IncompatibleVectors:
8679 DiagKind = diag::warn_incompatible_vectors;
8680 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008681 case Incompatible:
8682 DiagKind = diag::err_typecheck_convert_incompatible;
8683 isInvalid = true;
8684 break;
8685 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008686
Douglas Gregorc68e1402010-04-09 00:35:39 +00008687 QualType FirstType, SecondType;
8688 switch (Action) {
8689 case AA_Assigning:
8690 case AA_Initializing:
8691 // The destination type comes first.
8692 FirstType = DstType;
8693 SecondType = SrcType;
8694 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00008695
Douglas Gregorc68e1402010-04-09 00:35:39 +00008696 case AA_Returning:
8697 case AA_Passing:
8698 case AA_Converting:
8699 case AA_Sending:
8700 case AA_Casting:
8701 // The source type comes first.
8702 FirstType = SrcType;
8703 SecondType = DstType;
8704 break;
8705 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008706
Douglas Gregorc68e1402010-04-09 00:35:39 +00008707 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00008708 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008709 if (Complained)
8710 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008711 return isInvalid;
8712}
Anders Carlssone54e8a12008-11-30 19:50:32 +00008713
Chris Lattnerc71d08b2009-04-25 21:59:05 +00008714bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008715 llvm::APSInt ICEResult;
8716 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8717 if (Result)
8718 *Result = ICEResult;
8719 return false;
8720 }
8721
Anders Carlssone54e8a12008-11-30 19:50:32 +00008722 Expr::EvalResult EvalResult;
8723
Mike Stump4e1f26a2009-02-19 03:04:26 +00008724 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00008725 EvalResult.HasSideEffects) {
8726 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8727
8728 if (EvalResult.Diag) {
8729 // We only show the note if it's not the usual "invalid subexpression"
8730 // or if it's actually in a subexpression.
8731 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8732 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8733 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8734 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008735
Anders Carlssone54e8a12008-11-30 19:50:32 +00008736 return true;
8737 }
8738
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008739 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8740 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00008741
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008742 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008743 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
8744 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008745 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008746
Anders Carlssone54e8a12008-11-30 19:50:32 +00008747 if (Result)
8748 *Result = EvalResult.Val.getInt();
8749 return false;
8750}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008751
Douglas Gregorff790f12009-11-26 00:44:06 +00008752void
Mike Stump11289f42009-09-09 15:08:12 +00008753Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008754 ExprEvalContexts.push_back(
8755 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008756}
8757
Mike Stump11289f42009-09-09 15:08:12 +00008758void
Douglas Gregorff790f12009-11-26 00:44:06 +00008759Sema::PopExpressionEvaluationContext() {
8760 // Pop the current expression evaluation context off the stack.
8761 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8762 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008763
Douglas Gregorfab31f42009-12-12 07:57:52 +00008764 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8765 if (Rec.PotentiallyReferenced) {
8766 // Mark any remaining declarations in the current position of the stack
8767 // as "referenced". If they were not meant to be referenced, semantic
8768 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008769 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00008770 I = Rec.PotentiallyReferenced->begin(),
8771 IEnd = Rec.PotentiallyReferenced->end();
8772 I != IEnd; ++I)
8773 MarkDeclarationReferenced(I->first, I->second);
8774 }
8775
8776 if (Rec.PotentiallyDiagnosed) {
8777 // Emit any pending diagnostics.
8778 for (PotentiallyEmittedDiagnostics::iterator
8779 I = Rec.PotentiallyDiagnosed->begin(),
8780 IEnd = Rec.PotentiallyDiagnosed->end();
8781 I != IEnd; ++I)
8782 Diag(I->first, I->second);
8783 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008784 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008785
8786 // When are coming out of an unevaluated context, clear out any
8787 // temporaries that we may have created as part of the evaluation of
8788 // the expression in that context: they aren't relevant because they
8789 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008790 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00008791 ExprTemporaries.size() > Rec.NumTemporaries)
8792 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
8793 ExprTemporaries.end());
8794
8795 // Destroy the popped expression evaluation record.
8796 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008797}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008798
8799/// \brief Note that the given declaration was referenced in the source code.
8800///
8801/// This routine should be invoke whenever a given declaration is referenced
8802/// in the source code, and where that reference occurred. If this declaration
8803/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
8804/// C99 6.9p3), then the declaration will be marked as used.
8805///
8806/// \param Loc the location where the declaration was referenced.
8807///
8808/// \param D the declaration that has been referenced by the source code.
8809void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
8810 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00008811
Douglas Gregorebada0772010-06-17 23:14:26 +00008812 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00008813 return;
Mike Stump11289f42009-09-09 15:08:12 +00008814
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00008815 // Mark a parameter or variable declaration "used", regardless of whether we're in a
8816 // template or not. The reason for this is that unevaluated expressions
8817 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
8818 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008819 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008820 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00008821 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008822 return;
8823 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008824
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008825 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
8826 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00008827
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008828 // Do not mark anything as "used" within a dependent context; wait for
8829 // an instantiation.
8830 if (CurContext->isDependentContext())
8831 return;
Mike Stump11289f42009-09-09 15:08:12 +00008832
Douglas Gregorff790f12009-11-26 00:44:06 +00008833 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008834 case Unevaluated:
8835 // We are in an expression that is not potentially evaluated; do nothing.
8836 return;
Mike Stump11289f42009-09-09 15:08:12 +00008837
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008838 case PotentiallyEvaluated:
8839 // We are in a potentially-evaluated expression, so this declaration is
8840 // "used"; handle this below.
8841 break;
Mike Stump11289f42009-09-09 15:08:12 +00008842
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008843 case PotentiallyPotentiallyEvaluated:
8844 // We are in an expression that may be potentially evaluated; queue this
8845 // declaration reference until we know whether the expression is
8846 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00008847 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008848 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008849
8850 case PotentiallyEvaluatedIfUsed:
8851 // Referenced declarations will only be used if the construct in the
8852 // containing expression is used.
8853 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008854 }
Mike Stump11289f42009-09-09 15:08:12 +00008855
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008856 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00008857 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008858 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008859 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00008860 if (Constructor->getParent()->hasTrivialConstructor())
8861 return;
8862 if (!Constructor->isUsed(false))
8863 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00008864 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00008865 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008866 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008867 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
8868 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008869
Douglas Gregor88d292c2010-05-13 16:44:06 +00008870 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008871 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008872 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008873 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008874 if (Destructor->isVirtual())
8875 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008876 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
8877 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
8878 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008879 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00008880 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008881 } else if (MethodDecl->isVirtual())
8882 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008883 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00008884 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00008885 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00008886 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00008887 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00008888 bool AlreadyInstantiated = false;
8889 if (FunctionTemplateSpecializationInfo *SpecInfo
8890 = Function->getTemplateSpecializationInfo()) {
8891 if (SpecInfo->getPointOfInstantiation().isInvalid())
8892 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008893 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008894 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008895 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008896 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00008897 = Function->getMemberSpecializationInfo()) {
8898 if (MSInfo->getPointOfInstantiation().isInvalid())
8899 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008900 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008901 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008902 AlreadyInstantiated = true;
8903 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008904
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008905 if (!AlreadyInstantiated) {
8906 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
8907 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
8908 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
8909 Loc));
8910 else
Chandler Carruth54080172010-08-25 08:44:16 +00008911 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008912 }
Gabor Greifb6aba3e2010-08-28 00:16:06 +00008913 } else // Walk redefinitions, as some of them may be instantiable.
8914 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
8915 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00008916 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00008917 MarkDeclarationReferenced(Loc, *i);
8918 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008919
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008920 // FIXME: keep track of references to static functions
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00008921
8922 // Recursive functions should be marked when used from another function.
8923 if (CurContext != Function)
8924 Function->setUsed(true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008925
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008926 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00008927 }
Mike Stump11289f42009-09-09 15:08:12 +00008928
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008929 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008930 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00008931 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00008932 Var->getInstantiatedFromStaticDataMember()) {
8933 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
8934 assert(MSInfo && "Missing member specialization information?");
8935 if (MSInfo->getPointOfInstantiation().isInvalid() &&
8936 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
8937 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +00008938 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00008939 }
8940 }
Mike Stump11289f42009-09-09 15:08:12 +00008941
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008942 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008943
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008944 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008945 return;
Sam Weinigbae69142009-09-11 03:29:30 +00008946 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008947}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008948
Douglas Gregor5597ab42010-05-07 23:12:07 +00008949namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00008950 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00008951 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00008952 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00008953 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
8954 Sema &S;
8955 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00008956
Douglas Gregor5597ab42010-05-07 23:12:07 +00008957 public:
8958 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00008959
Douglas Gregor5597ab42010-05-07 23:12:07 +00008960 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00008961
8962 bool TraverseTemplateArgument(const TemplateArgument &Arg);
8963 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00008964 };
8965}
8966
Chandler Carruthaf80f662010-06-09 08:17:30 +00008967bool MarkReferencedDecls::TraverseTemplateArgument(
8968 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00008969 if (Arg.getKind() == TemplateArgument::Declaration) {
8970 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
8971 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00008972
8973 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00008974}
8975
Chandler Carruthaf80f662010-06-09 08:17:30 +00008976bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00008977 if (ClassTemplateSpecializationDecl *Spec
8978 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
8979 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008980 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00008981 }
8982
Chandler Carruthc65667c2010-06-10 10:31:57 +00008983 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00008984}
8985
8986void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
8987 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00008988 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00008989}
8990
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008991namespace {
8992 /// \brief Helper class that marks all of the declarations referenced by
8993 /// potentially-evaluated subexpressions as "referenced".
8994 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
8995 Sema &S;
8996
8997 public:
8998 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
8999
9000 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9001
9002 void VisitDeclRefExpr(DeclRefExpr *E) {
9003 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9004 }
9005
9006 void VisitMemberExpr(MemberExpr *E) {
9007 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009008 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009009 }
9010
9011 void VisitCXXNewExpr(CXXNewExpr *E) {
9012 if (E->getConstructor())
9013 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9014 if (E->getOperatorNew())
9015 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9016 if (E->getOperatorDelete())
9017 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009018 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009019 }
9020
9021 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9022 if (E->getOperatorDelete())
9023 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009024 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9025 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9026 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9027 S.MarkDeclarationReferenced(E->getLocStart(),
9028 S.LookupDestructor(Record));
9029 }
9030
Douglas Gregor32b3de52010-09-11 23:32:50 +00009031 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009032 }
9033
9034 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9035 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009036 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009037 }
9038
9039 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9040 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9041 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009042
9043 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9044 Visit(E->getExpr());
9045 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009046 };
9047}
9048
9049/// \brief Mark any declarations that appear within this expression or any
9050/// potentially-evaluated subexpressions as "referenced".
9051void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9052 EvaluatedExprMarker(*this).Visit(E);
9053}
9054
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009055/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9056/// of the program being compiled.
9057///
9058/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009059/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009060/// possibility that the code will actually be executable. Code in sizeof()
9061/// expressions, code used only during overload resolution, etc., are not
9062/// potentially evaluated. This routine will suppress such diagnostics or,
9063/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009064/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009065/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009066///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009067/// This routine should be used for all diagnostics that describe the run-time
9068/// behavior of a program, such as passing a non-POD value through an ellipsis.
9069/// Failure to do so will likely result in spurious diagnostics or failures
9070/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009071bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009072 const PartialDiagnostic &PD) {
9073 switch (ExprEvalContexts.back().Context ) {
9074 case Unevaluated:
9075 // The argument will never be evaluated, so don't complain.
9076 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009077
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009078 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009079 case PotentiallyEvaluatedIfUsed:
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009080 Diag(Loc, PD);
9081 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009082
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009083 case PotentiallyPotentiallyEvaluated:
9084 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9085 break;
9086 }
9087
9088 return false;
9089}
9090
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009091bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9092 CallExpr *CE, FunctionDecl *FD) {
9093 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9094 return false;
9095
9096 PartialDiagnostic Note =
9097 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9098 << FD->getDeclName() : PDiag();
9099 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009100
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009101 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009102 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009103 PDiag(diag::err_call_function_incomplete_return)
9104 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009105 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009106 << CE->getSourceRange(),
9107 std::make_pair(NoteLoc, Note)))
9108 return true;
9109
9110 return false;
9111}
9112
John McCalld5707ab2009-10-12 21:59:07 +00009113// Diagnose the common s/=/==/ typo. Note that adding parentheses
9114// will prevent this condition from triggering, which is what we want.
9115void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9116 SourceLocation Loc;
9117
John McCall0506e4a2009-11-11 02:41:58 +00009118 unsigned diagnostic = diag::warn_condition_is_assignment;
9119
John McCalld5707ab2009-10-12 21:59:07 +00009120 if (isa<BinaryOperator>(E)) {
9121 BinaryOperator *Op = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00009122 if (Op->getOpcode() != BO_Assign)
John McCalld5707ab2009-10-12 21:59:07 +00009123 return;
9124
John McCallb0e419e2009-11-12 00:06:05 +00009125 // Greylist some idioms by putting them into a warning subcategory.
9126 if (ObjCMessageExpr *ME
9127 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9128 Selector Sel = ME->getSelector();
9129
John McCallb0e419e2009-11-12 00:06:05 +00009130 // self = [<foo> init...]
9131 if (isSelfExpr(Op->getLHS())
9132 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
9133 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9134
9135 // <foo> = [<bar> nextObject]
9136 else if (Sel.isUnarySelector() &&
9137 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
9138 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9139 }
John McCall0506e4a2009-11-11 02:41:58 +00009140
John McCalld5707ab2009-10-12 21:59:07 +00009141 Loc = Op->getOperatorLoc();
9142 } else if (isa<CXXOperatorCallExpr>(E)) {
9143 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
9144 if (Op->getOperator() != OO_Equal)
9145 return;
9146
9147 Loc = Op->getOperatorLoc();
9148 } else {
9149 // Not an assignment.
9150 return;
9151 }
9152
John McCalld5707ab2009-10-12 21:59:07 +00009153 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00009154 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009155
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009156 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00009157 Diag(Loc, diag::note_condition_assign_to_comparison)
Douglas Gregora771f462010-03-31 17:46:05 +00009158 << FixItHint::CreateReplacement(Loc, "==");
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009159 Diag(Loc, diag::note_condition_assign_silence)
9160 << FixItHint::CreateInsertion(Open, "(")
9161 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +00009162}
9163
9164bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9165 DiagnoseAssignmentAsCondition(E);
9166
9167 if (!E->isTypeDependent()) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009168 if (E->isBoundMemberFunction(Context))
9169 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9170 << E->getSourceRange();
9171
John McCall34376a62010-12-04 03:47:34 +00009172 if (getLangOptions().CPlusPlus)
9173 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9174
9175 DefaultFunctionArrayLvalueConversion(E);
John McCall29cb2fd2010-12-04 06:09:13 +00009176
9177 QualType T = E->getType();
John McCall34376a62010-12-04 03:47:34 +00009178 if (!T->isScalarType()) // C99 6.8.4.1p1
9179 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9180 << T << E->getSourceRange();
John McCalld5707ab2009-10-12 21:59:07 +00009181 }
9182
9183 return false;
9184}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009185
John McCalldadc5752010-08-24 06:29:42 +00009186ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9187 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009188 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009189 return ExprError();
9190
Douglas Gregorb412e172010-07-25 18:17:45 +00009191 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00009192 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00009193
9194 return Owned(Sub);
9195}
John McCall36e7fe32010-10-12 00:20:44 +00009196
9197/// Check for operands with placeholder types and complain if found.
9198/// Returns true if there was an error and no recovery was possible.
9199ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9200 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9201 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9202
9203 // If this is overload, check for a single overload.
9204 if (BT->getKind() == BuiltinType::Overload) {
9205 if (FunctionDecl *Specialization
9206 = ResolveSingleFunctionTemplateSpecialization(E)) {
9207 // The access doesn't really matter in this case.
9208 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9209 Specialization->getAccess());
9210 E = FixOverloadedFunctionReference(E, Found, Specialization);
9211 if (!E) return ExprError();
9212 return Owned(E);
9213 }
9214
John McCall36226622010-10-12 02:09:17 +00009215 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
John McCall36e7fe32010-10-12 00:20:44 +00009216 return ExprError();
9217 }
9218
9219 // Otherwise it's a use of undeduced auto.
9220 assert(BT->getKind() == BuiltinType::UndeducedAuto);
9221
9222 DeclRefExpr *DRE = cast<DeclRefExpr>(E->IgnoreParens());
9223 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
9224 << DRE->getDecl() << E->getSourceRange();
9225 return ExprError();
9226}