blob: ea4f6bc85592f5e8cb9c2569a133abd7e063b46c [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///
Chris Lattnerb7df3c62009-10-25 22:31:57 +000052/// If IgnoreDeprecated is set to true, this should not want about deprecated
53/// 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///
John McCall28a6aea2009-11-04 02:18:39 +000058bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000059 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
60 // If there were any diagnostics suppressed by template argument deduction,
61 // emit them now.
62 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
63 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
64 if (Pos != SuppressedDiagnostics.end()) {
65 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
66 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
67 Diag(Suppressed[I].first, Suppressed[I].second);
68
69 // Clear out the list of suppressed diagnostics, so that we don't emit
70 // them again for this specialization. However, we don't remove this
71 // entry from the table, because we want to avoid ever emitting these
72 // diagnostics again.
73 Suppressed.clear();
74 }
75 }
76
Chris Lattner4bf74fd2009-02-15 22:43:40 +000077 // See if the decl is deprecated.
Benjamin Kramerbfac7dc2010-10-09 15:49:00 +000078 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>())
79 EmitDeprecationWarning(D, DA->getMessage(), Loc);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000080
Chris Lattnera27dd592009-10-25 17:21:40 +000081 // See if the decl is unavailable
Fariborz Jahanianc74073c2010-10-06 23:12:32 +000082 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) {
83 if (UA->getMessage().empty())
84 Diag(Loc, diag::err_unavailable) << D->getDeclName();
85 else
86 Diag(Loc, diag::err_unavailable_message)
Benjamin Kramerbfac7dc2010-10-09 15:49:00 +000087 << D->getDeclName() << UA->getMessage();
Chris Lattnera27dd592009-10-25 17:21:40 +000088 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
89 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000090
Douglas Gregor171c45a2009-02-18 21:56:37 +000091 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000092 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000093 if (FD->isDeleted()) {
94 Diag(Loc, diag::err_deleted_function_use);
95 Diag(D->getLocation(), diag::note_unavailable_here) << true;
96 return true;
97 }
Douglas Gregorde681d42009-02-24 04:26:15 +000098 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000099
Anders Carlsson73067a02010-10-22 23:37:08 +0000100 // Warn if this is used but marked unused.
101 if (D->hasAttr<UnusedAttr>())
102 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
103
Douglas Gregor171c45a2009-02-18 21:56:37 +0000104 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000105}
106
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000107/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000108/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000109/// attribute. It warns if call does not have the sentinel argument.
110///
111void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000112 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000113 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000114 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000115 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000116
117 // FIXME: In C++0x, if any of the arguments are parameter pack
118 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000119 int sentinelPos = attr->getSentinel();
120 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000121
Mike Stump87c57ac2009-05-16 07:39:55 +0000122 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
123 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000124 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000125 bool warnNotEnoughArgs = false;
126 int isMethod = 0;
127 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
128 // skip over named parameters.
129 ObjCMethodDecl::param_iterator P, E = MD->param_end();
130 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
131 if (nullPos)
132 --nullPos;
133 else
134 ++i;
135 }
136 warnNotEnoughArgs = (P != E || i >= NumArgs);
137 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000138 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000139 // skip over named parameters.
140 ObjCMethodDecl::param_iterator P, E = FD->param_end();
141 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
142 if (nullPos)
143 --nullPos;
144 else
145 ++i;
146 }
147 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000148 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000149 // block or function pointer call.
150 QualType Ty = V->getType();
151 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000152 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000153 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
154 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000155 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
156 unsigned NumArgsInProto = Proto->getNumArgs();
157 unsigned k;
158 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
159 if (nullPos)
160 --nullPos;
161 else
162 ++i;
163 }
164 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
165 }
166 if (Ty->isBlockPointerType())
167 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000168 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000169 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000170 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000171 return;
172
173 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000174 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000175 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000176 return;
177 }
178 int sentinel = i;
179 while (sentinelPos > 0 && i < NumArgs-1) {
180 --sentinelPos;
181 ++i;
182 }
183 if (sentinelPos > 0) {
184 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000185 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000186 return;
187 }
188 while (i < NumArgs-1) {
189 ++i;
190 ++sentinel;
191 }
192 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000193 if (!sentinelExpr) return;
194 if (sentinelExpr->isTypeDependent()) return;
195 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000196
197 // nullptr_t is always treated as null.
198 if (sentinelExpr->getType()->isNullPtrType()) return;
199
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000200 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000201 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
202 Expr::NPC_ValueDependentIsNull))
203 return;
204
205 // Unfortunately, __null has type 'int'.
206 if (isa<GNUNullExpr>(sentinelExpr)) return;
207
208 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
209 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000210}
211
Douglas Gregor87f95b02009-02-26 21:00:50 +0000212SourceRange Sema::getExprRange(ExprTy *E) const {
213 Expr *Ex = (Expr *)E;
214 return Ex? Ex->getSourceRange() : SourceRange();
215}
216
Chris Lattner513165e2008-07-25 21:10:04 +0000217//===----------------------------------------------------------------------===//
218// Standard Promotions and Conversions
219//===----------------------------------------------------------------------===//
220
Chris Lattner513165e2008-07-25 21:10:04 +0000221/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
222void Sema::DefaultFunctionArrayConversion(Expr *&E) {
223 QualType Ty = E->getType();
224 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
225
Chris Lattner513165e2008-07-25 21:10:04 +0000226 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000227 ImpCastExprToType(E, Context.getPointerType(Ty),
John McCalle3027922010-08-25 11:45:40 +0000228 CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000229 else if (Ty->isArrayType()) {
230 // In C90 mode, arrays only promote to pointers if the array expression is
231 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
232 // type 'array of type' is converted to an expression that has type 'pointer
233 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
234 // that has type 'array of type' ...". The relevant change is "an lvalue"
235 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000236 //
237 // C++ 4.2p1:
238 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
239 // T" can be converted to an rvalue of type "pointer to T".
240 //
John McCall086a4642010-11-24 05:12:34 +0000241 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000242 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
John McCalle3027922010-08-25 11:45:40 +0000243 CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000244 }
Chris Lattner513165e2008-07-25 21:10:04 +0000245}
246
John McCall27584242010-12-06 20:48:59 +0000247void Sema::DefaultLvalueConversion(Expr *&E) {
John McCallf3735e02010-12-01 04:43:34 +0000248 // C++ [conv.lval]p1:
249 // A glvalue of a non-function, non-array type T can be
250 // converted to a prvalue.
John McCall27584242010-12-06 20:48:59 +0000251 if (!E->isGLValue()) return;
John McCall34376a62010-12-04 03:47:34 +0000252
John McCall27584242010-12-06 20:48:59 +0000253 QualType T = E->getType();
254 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000255
John McCall27584242010-12-06 20:48:59 +0000256 // Create a load out of an ObjCProperty l-value, if necessary.
257 if (E->getObjectKind() == OK_ObjCProperty) {
258 ConvertPropertyForRValue(E);
259 if (!E->isGLValue())
John McCall34376a62010-12-04 03:47:34 +0000260 return;
Douglas Gregorb92a1562010-02-03 00:27:59 +0000261 }
John McCall27584242010-12-06 20:48:59 +0000262
263 // We don't want to throw lvalue-to-rvalue casts on top of
264 // expressions of certain types in C++.
265 if (getLangOptions().CPlusPlus &&
266 (E->getType() == Context.OverloadTy ||
267 T->isDependentType() ||
268 T->isRecordType()))
269 return;
270
271 // The C standard is actually really unclear on this point, and
272 // DR106 tells us what the result should be but not why. It's
273 // generally best to say that void types just doesn't undergo
274 // lvalue-to-rvalue at all. Note that expressions of unqualified
275 // 'void' type are never l-values, but qualified void can be.
276 if (T->isVoidType())
277 return;
278
279 // C++ [conv.lval]p1:
280 // [...] If T is a non-class type, the type of the prvalue is the
281 // cv-unqualified version of T. Otherwise, the type of the
282 // rvalue is T.
283 //
284 // C99 6.3.2.1p2:
285 // If the lvalue has qualified type, the value has the unqualified
286 // version of the type of the lvalue; otherwise, the value has the
287 // type of the lvalue.
288 if (T.hasQualifiers())
289 T = T.getUnqualifiedType();
290
291 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
292 E, 0, VK_RValue);
293}
294
295void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
296 DefaultFunctionArrayConversion(E);
297 DefaultLvalueConversion(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000298}
299
300
Chris Lattner513165e2008-07-25 21:10:04 +0000301/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000302/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000303/// sometimes surpressed. For example, the array->pointer conversion doesn't
304/// apply if the array is an argument to the sizeof or address (&) operators.
305/// In these instances, this routine should *not* be called.
John McCallf3735e02010-12-01 04:43:34 +0000306Expr *Sema::UsualUnaryConversions(Expr *&E) {
307 // First, convert to an r-value.
308 DefaultFunctionArrayLvalueConversion(E);
309
310 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000311 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000312
313 // Try to perform integral promotions if the object has a theoretically
314 // promotable type.
315 if (Ty->isIntegralOrUnscopedEnumerationType()) {
316 // C99 6.3.1.1p2:
317 //
318 // The following may be used in an expression wherever an int or
319 // unsigned int may be used:
320 // - an object or expression with an integer type whose integer
321 // conversion rank is less than or equal to the rank of int
322 // and unsigned int.
323 // - A bit-field of type _Bool, int, signed int, or unsigned int.
324 //
325 // If an int can represent all values of the original type, the
326 // value is converted to an int; otherwise, it is converted to an
327 // unsigned int. These are called the integer promotions. All
328 // other types are unchanged by the integer promotions.
329
330 QualType PTy = Context.isPromotableBitField(E);
331 if (!PTy.isNull()) {
332 ImpCastExprToType(E, PTy, CK_IntegralCast);
333 return E;
334 }
335 if (Ty->isPromotableIntegerType()) {
336 QualType PT = Context.getPromotedIntegerType(Ty);
337 ImpCastExprToType(E, PT, CK_IntegralCast);
338 return E;
339 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000340 }
341
John McCallf3735e02010-12-01 04:43:34 +0000342 return E;
Chris Lattner513165e2008-07-25 21:10:04 +0000343}
344
Chris Lattner2ce500f2008-07-25 22:25:12 +0000345/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000346/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000347/// double. All other argument types are converted by UsualUnaryConversions().
348void Sema::DefaultArgumentPromotion(Expr *&Expr) {
349 QualType Ty = Expr->getType();
350 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000351
John McCall9bc26772010-12-06 18:36:11 +0000352 UsualUnaryConversions(Expr);
353
Chris Lattner2ce500f2008-07-25 22:25:12 +0000354 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000355 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John McCall9bc26772010-12-06 18:36:11 +0000356 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000357}
358
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000359/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
360/// will warn if the resulting type is not a POD type, and rejects ObjC
361/// interfaces passed by value. This returns true if the argument type is
362/// completely illegal.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000363bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
364 FunctionDecl *FDecl) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000365 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000366
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000367 // __builtin_va_start takes the second argument as a "varargs" argument, but
368 // it doesn't actually do anything with it. It doesn't need to be non-pod
369 // etc.
370 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
371 return false;
372
John McCall8b07ec22010-05-15 11:32:37 +0000373 if (Expr->getType()->isObjCObjectType() &&
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000374 DiagRuntimeBehavior(Expr->getLocStart(),
375 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
376 << Expr->getType() << CT))
377 return true;
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000378
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000379 if (!Expr->getType()->isPODType() &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000380 DiagRuntimeBehavior(Expr->getLocStart(),
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000381 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
382 << Expr->getType() << CT))
383 return true;
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000384
385 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000386}
387
Chris Lattner513165e2008-07-25 21:10:04 +0000388/// UsualArithmeticConversions - Performs various conversions that are common to
389/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000390/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000391/// responsible for emitting appropriate error diagnostics.
392/// FIXME: verify the conversion rules for "complex int" are consistent with
393/// GCC.
394QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
395 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000396 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000397 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000398
399 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000400
Mike Stump11289f42009-09-09 15:08:12 +0000401 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000402 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000403 QualType lhs =
404 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000405 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000406 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000407
408 // If both types are identical, no conversion is needed.
409 if (lhs == rhs)
410 return lhs;
411
412 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
413 // The caller can deal with this (e.g. pointer + int).
414 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
415 return lhs;
416
John McCalld005ac92010-11-13 08:17:45 +0000417 // Apply unary and bitfield promotions to the LHS's type.
418 QualType lhs_unpromoted = lhs;
419 if (lhs->isPromotableIntegerType())
420 lhs = Context.getPromotedIntegerType(lhs);
Eli Friedman629ffb92009-08-20 04:21:42 +0000421 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000422 if (!LHSBitfieldPromoteTy.isNull())
423 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000424 if (lhs != lhs_unpromoted && !isCompAssign)
425 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000426
John McCalld005ac92010-11-13 08:17:45 +0000427 // If both types are identical, no conversion is needed.
428 if (lhs == rhs)
429 return lhs;
430
431 // At this point, we have two different arithmetic types.
432
433 // Handle complex types first (C99 6.3.1.8p1).
434 bool LHSComplexFloat = lhs->isComplexType();
435 bool RHSComplexFloat = rhs->isComplexType();
436 if (LHSComplexFloat || RHSComplexFloat) {
437 // if we have an integer operand, the result is the complex type.
438
John McCallc5e62b42010-11-13 09:02:35 +0000439 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
440 if (rhs->isIntegerType()) {
441 QualType fp = cast<ComplexType>(lhs)->getElementType();
442 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
443 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
444 } else {
445 assert(rhs->isComplexIntegerType());
John McCalld7646252010-11-14 08:17:51 +0000446 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000447 }
John McCalld005ac92010-11-13 08:17:45 +0000448 return lhs;
449 }
450
John McCallc5e62b42010-11-13 09:02:35 +0000451 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
452 if (!isCompAssign) {
453 // int -> float -> _Complex float
454 if (lhs->isIntegerType()) {
455 QualType fp = cast<ComplexType>(rhs)->getElementType();
456 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
457 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
458 } else {
459 assert(lhs->isComplexIntegerType());
John McCalld7646252010-11-14 08:17:51 +0000460 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000461 }
462 }
John McCalld005ac92010-11-13 08:17:45 +0000463 return rhs;
464 }
465
466 // This handles complex/complex, complex/float, or float/complex.
467 // When both operands are complex, the shorter operand is converted to the
468 // type of the longer, and that is the type of the result. This corresponds
469 // to what is done when combining two real floating-point operands.
470 // The fun begins when size promotion occur across type domains.
471 // From H&S 6.3.4: When one operand is complex and the other is a real
472 // floating-point type, the less precise type is converted, within it's
473 // real or complex domain, to the precision of the other type. For example,
474 // when combining a "long double" with a "double _Complex", the
475 // "double _Complex" is promoted to "long double _Complex".
476 int order = Context.getFloatingTypeOrder(lhs, rhs);
477
478 // If both are complex, just cast to the more precise type.
479 if (LHSComplexFloat && RHSComplexFloat) {
480 if (order > 0) {
481 // _Complex float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000482 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000483 return lhs;
484
485 } else if (order < 0) {
486 // _Complex float -> _Complex double
487 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000488 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000489 return rhs;
490 }
491 return lhs;
492 }
493
494 // If just the LHS is complex, the RHS needs to be converted,
495 // and the LHS might need to be promoted.
496 if (LHSComplexFloat) {
497 if (order > 0) { // LHS is wider
498 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000499 QualType fp = cast<ComplexType>(lhs)->getElementType();
500 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
501 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000502 return lhs;
503 }
504
505 // RHS is at least as wide. Find its corresponding complex type.
506 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
507
508 // double -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000509 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000510
511 // _Complex float -> _Complex double
512 if (!isCompAssign && order < 0)
John McCallc5e62b42010-11-13 09:02:35 +0000513 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000514
515 return result;
516 }
517
518 // Just the RHS is complex, so the LHS needs to be converted
519 // and the RHS might need to be promoted.
520 assert(RHSComplexFloat);
521
522 if (order < 0) { // RHS is wider
523 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000524 if (!isCompAssign) {
525 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
526 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
527 }
John McCalld005ac92010-11-13 08:17:45 +0000528 return rhs;
529 }
530
531 // LHS is at least as wide. Find its corresponding complex type.
532 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
533
534 // double -> _Complex double
535 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000536 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000537
538 // _Complex float -> _Complex double
539 if (order > 0)
John McCallc5e62b42010-11-13 09:02:35 +0000540 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000541
542 return result;
543 }
544
545 // Now handle "real" floating types (i.e. float, double, long double).
546 bool LHSFloat = lhs->isRealFloatingType();
547 bool RHSFloat = rhs->isRealFloatingType();
548 if (LHSFloat || RHSFloat) {
549 // If we have two real floating types, convert the smaller operand
550 // to the bigger result.
551 if (LHSFloat && RHSFloat) {
552 int order = Context.getFloatingTypeOrder(lhs, rhs);
553 if (order > 0) {
554 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
555 return lhs;
556 }
557
558 assert(order < 0 && "illegal float comparison");
559 if (!isCompAssign)
560 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
561 return rhs;
562 }
563
564 // If we have an integer operand, the result is the real floating type.
565 if (LHSFloat) {
566 if (rhs->isIntegerType()) {
567 // Convert rhs to the lhs floating point type.
568 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
569 return lhs;
570 }
571
572 // Convert both sides to the appropriate complex float.
573 assert(rhs->isComplexIntegerType());
574 QualType result = Context.getComplexType(lhs);
575
576 // _Complex int -> _Complex float
John McCalld7646252010-11-14 08:17:51 +0000577 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000578
579 // float -> _Complex float
580 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000581 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000582
583 return result;
584 }
585
586 assert(RHSFloat);
587 if (lhs->isIntegerType()) {
588 // Convert lhs to the rhs floating point type.
589 if (!isCompAssign)
590 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
591 return rhs;
592 }
593
594 // Convert both sides to the appropriate complex float.
595 assert(lhs->isComplexIntegerType());
596 QualType result = Context.getComplexType(rhs);
597
598 // _Complex int -> _Complex float
599 if (!isCompAssign)
John McCalld7646252010-11-14 08:17:51 +0000600 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000601
602 // float -> _Complex float
John McCallc5e62b42010-11-13 09:02:35 +0000603 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000604
605 return result;
606 }
607
608 // Handle GCC complex int extension.
609 // FIXME: if the operands are (int, _Complex long), we currently
610 // don't promote the complex. Also, signedness?
611 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
612 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
613 if (lhsComplexInt && rhsComplexInt) {
614 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
615 rhsComplexInt->getElementType());
616 assert(order && "inequal types with equal element ordering");
617 if (order > 0) {
618 // _Complex int -> _Complex long
John McCallc5e62b42010-11-13 09:02:35 +0000619 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000620 return lhs;
621 }
622
623 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000624 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000625 return rhs;
626 } else if (lhsComplexInt) {
627 // int -> _Complex int
John McCallc5e62b42010-11-13 09:02:35 +0000628 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000629 return lhs;
630 } else if (rhsComplexInt) {
631 // int -> _Complex int
632 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000633 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000634 return rhs;
635 }
636
637 // Finally, we have two differing integer types.
638 // The rules for this case are in C99 6.3.1.8
639 int compare = Context.getIntegerTypeOrder(lhs, rhs);
640 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
641 rhsSigned = rhs->hasSignedIntegerRepresentation();
642 if (lhsSigned == rhsSigned) {
643 // Same signedness; use the higher-ranked type
644 if (compare >= 0) {
645 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
646 return lhs;
647 } else if (!isCompAssign)
648 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
649 return rhs;
650 } else if (compare != (lhsSigned ? 1 : -1)) {
651 // The unsigned type has greater than or equal rank to the
652 // signed type, so use the unsigned type
653 if (rhsSigned) {
654 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
655 return lhs;
656 } else if (!isCompAssign)
657 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
658 return rhs;
659 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
660 // The two types are different widths; if we are here, that
661 // means the signed type is larger than the unsigned type, so
662 // use the signed type.
663 if (lhsSigned) {
664 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
665 return lhs;
666 } else if (!isCompAssign)
667 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
668 return rhs;
669 } else {
670 // The signed type is higher-ranked than the unsigned type,
671 // but isn't actually any bigger (like unsigned int and long
672 // on most 32-bit systems). Use the unsigned type corresponding
673 // to the signed type.
674 QualType result =
675 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
676 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
677 if (!isCompAssign)
678 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
679 return result;
680 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000681}
682
Chris Lattner513165e2008-07-25 21:10:04 +0000683//===----------------------------------------------------------------------===//
684// Semantic Analysis for various Expression Types
685//===----------------------------------------------------------------------===//
686
687
Steve Naroff83895f72007-09-16 03:34:24 +0000688/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000689/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
690/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
691/// multiple tokens. However, the common case is that StringToks points to one
692/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000693///
John McCalldadc5752010-08-24 06:29:42 +0000694ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000695Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000696 assert(NumStringToks && "Must have at least one string!");
697
Chris Lattner8a24e582009-01-16 18:51:42 +0000698 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000699 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000700 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000701
Chris Lattner23b7eb62007-06-15 23:05:46 +0000702 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000703 for (unsigned i = 0; i != NumStringToks; ++i)
704 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000705
Chris Lattner36fc8792008-02-11 00:02:17 +0000706 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000707 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000708 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000709
710 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000711 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000712 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000713
Chris Lattner36fc8792008-02-11 00:02:17 +0000714 // Get an array type for the string, according to C99 6.4.5. This includes
715 // the nul terminator character as well as the string length for pascal
716 // strings.
717 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000718 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000719 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000720
Chris Lattner5b183d82006-11-10 05:03:26 +0000721 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000722 return Owned(StringLiteral::Create(Context, Literal.GetString(),
723 Literal.GetStringLength(),
724 Literal.AnyWide, StrTy,
725 &StringTokLocs[0],
726 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000727}
728
Chris Lattner2a9d9892008-10-20 05:16:36 +0000729/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
730/// CurBlock to VD should cause it to be snapshotted (as we do for auto
731/// variables defined outside the block) or false if this is not needed (e.g.
732/// for values inside the block or for globals).
733///
Douglas Gregor4f13beb2010-03-01 20:44:28 +0000734/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
Chris Lattner497d7b02009-04-21 22:26:47 +0000735/// up-to-date.
736///
Douglas Gregor9a28e842010-03-01 23:15:13 +0000737static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
Chris Lattner2a9d9892008-10-20 05:16:36 +0000738 ValueDecl *VD) {
739 // If the value is defined inside the block, we couldn't snapshot it even if
740 // we wanted to.
741 if (CurBlock->TheDecl == VD->getDeclContext())
742 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000743
Chris Lattner2a9d9892008-10-20 05:16:36 +0000744 // If this is an enum constant or function, it is constant, don't snapshot.
745 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
746 return false;
747
748 // If this is a reference to an extern, static, or global variable, no need to
749 // snapshot it.
750 // FIXME: What about 'const' variables in C++?
751 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000752 if (!Var->hasLocalStorage())
753 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000754
Chris Lattner497d7b02009-04-21 22:26:47 +0000755 // Blocks that have these can't be constant.
756 CurBlock->hasBlockDeclRefExprs = true;
757
758 // If we have nested blocks, the decl may be declared in an outer block (in
759 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
760 // be defined outside all of the current blocks (in which case the blocks do
761 // all get the bit). Walk the nesting chain.
Douglas Gregor9a28e842010-03-01 23:15:13 +0000762 for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
763 BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000764
Douglas Gregor9a28e842010-03-01 23:15:13 +0000765 if (!NextBlock)
766 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000767
Chris Lattner497d7b02009-04-21 22:26:47 +0000768 // If we found the defining block for the variable, don't mark the block as
769 // having a reference outside it.
770 if (NextBlock->TheDecl == VD->getDeclContext())
771 break;
Mike Stump11289f42009-09-09 15:08:12 +0000772
Chris Lattner497d7b02009-04-21 22:26:47 +0000773 // Otherwise, the DeclRef from the inner block causes the outer one to need
774 // a snapshot as well.
775 NextBlock->hasBlockDeclRefExprs = true;
776 }
Mike Stump11289f42009-09-09 15:08:12 +0000777
Chris Lattner2a9d9892008-10-20 05:16:36 +0000778 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000779}
780
Chris Lattner2a9d9892008-10-20 05:16:36 +0000781
John McCalldadc5752010-08-24 06:29:42 +0000782ExprResult
John McCall7decc9e2010-11-18 06:31:45 +0000783Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
784 SourceLocation Loc, const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000785 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +0000786 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000787}
788
789/// BuildDeclRefExpr - Build a DeclRefExpr.
John McCalldadc5752010-08-24 06:29:42 +0000790ExprResult
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000791Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +0000792 ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000793 const DeclarationNameInfo &NameInfo,
794 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000795 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000796 Diag(NameInfo.getLoc(),
Mike Stump11289f42009-09-09 15:08:12 +0000797 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000798 << D->getDeclName();
799 return ExprError();
800 }
Mike Stump11289f42009-09-09 15:08:12 +0000801
Anders Carlsson946b86d2009-06-24 00:10:43 +0000802 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Douglas Gregor15243332010-04-27 21:10:04 +0000803 if (isa<NonTypeTemplateParmDecl>(VD)) {
804 // Non-type template parameters can be referenced anywhere they are
805 // visible.
Douglas Gregora8a089b2010-07-13 18:40:04 +0000806 Ty = Ty.getNonLValueExprType(Context);
Douglas Gregor15243332010-04-27 21:10:04 +0000807 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
Anders Carlsson946b86d2009-06-24 00:10:43 +0000808 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
809 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000810 Diag(NameInfo.getLoc(),
811 diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000812 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000813 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000814 << D->getIdentifier();
815 return ExprError();
816 }
817 }
John McCall4bc41ae2010-11-18 19:01:18 +0000818
819 // This ridiculousness brought to you by 'extern void x;' and the
820 // GNU compiler collection.
821 } else if (!getLangOptions().CPlusPlus && !Ty.hasQualifiers() &&
822 Ty->isVoidType()) {
823 VK = VK_RValue;
Anders Carlsson946b86d2009-06-24 00:10:43 +0000824 }
825 }
Mike Stump11289f42009-09-09 15:08:12 +0000826
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000827 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +0000828
John McCall086a4642010-11-24 05:12:34 +0000829 Expr *E = DeclRefExpr::Create(Context,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000830 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
John McCall086a4642010-11-24 05:12:34 +0000831 SS? SS->getRange() : SourceRange(),
832 D, NameInfo, Ty, VK);
833
834 // Just in case we're building an illegal pointer-to-member.
835 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
836 E->setObjectKind(OK_BitField);
837
838 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000839}
840
John McCallfeb624a2010-11-23 20:48:44 +0000841static ExprResult
842BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
843 const CXXScopeSpec &SS, FieldDecl *Field,
844 DeclAccessPair FoundDecl,
845 const DeclarationNameInfo &MemberNameInfo);
846
John McCalldadc5752010-08-24 06:29:42 +0000847ExprResult
Douglas Gregord5846a12009-04-15 06:41:24 +0000848Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
Francois Pichet783dd6e2010-11-21 06:08:52 +0000849 IndirectFieldDecl *IndirectField,
Douglas Gregord5846a12009-04-15 06:41:24 +0000850 Expr *BaseObjectExpr,
851 SourceLocation OpLoc) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000852 // Build the expression that refers to the base object, from
853 // which we will build a sequence of member references to each
854 // of the anonymous union objects and, eventually, the field we
855 // found via name lookup.
856 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000857 Qualifiers BaseQuals;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000858 VarDecl *BaseObject = IndirectField->getVarDecl();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000859 if (BaseObject) {
860 // BaseObject is an anonymous struct/union variable (and is,
861 // therefore, not part of another non-anonymous record).
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000862 MarkDeclarationReferenced(Loc, BaseObject);
John McCall7decc9e2010-11-18 06:31:45 +0000863 BaseObjectExpr =
864 new (Context) DeclRefExpr(BaseObject, BaseObject->getType(),
865 VK_LValue, Loc);
John McCall8ccfcb52009-09-24 19:53:00 +0000866 BaseQuals
867 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000868 } else if (BaseObjectExpr) {
869 // The caller provided the base object expression. Determine
870 // whether its a pointer and whether it adds any qualifiers to the
871 // anonymous struct/union fields we're looking into.
872 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000873 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000874 BaseObjectIsPointer = true;
875 ObjectType = ObjectPtr->getPointeeType();
876 }
John McCall8ccfcb52009-09-24 19:53:00 +0000877 BaseQuals
878 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000879 } else {
880 // We've found a member of an anonymous struct/union that is
881 // inside a non-anonymous struct/union, so in a well-formed
882 // program our base object expression is "this".
John McCall87fe5d52010-05-20 01:18:31 +0000883 DeclContext *DC = getFunctionLevelDeclContext();
884 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000885 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000886 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000887 = Context.getTagDeclType(
Francois Pichet783dd6e2010-11-21 06:08:52 +0000888 cast<RecordDecl>(
889 (*IndirectField->chain_begin())->getDeclContext()));
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000890 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000891 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000892 == Context.getCanonicalType(ThisType)) ||
893 IsDerivedFrom(ThisType, AnonFieldType)) {
894 // Our base object expression is "this".
Douglas Gregor4b654412009-12-24 20:23:34 +0000895 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000896 MD->getThisType(Context),
897 /*isImplicit=*/true);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000898 BaseObjectIsPointer = true;
899 }
900 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000901 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
Francois Pichet783dd6e2010-11-21 06:08:52 +0000902 << IndirectField->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000903 }
John McCall8ccfcb52009-09-24 19:53:00 +0000904 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000905 }
906
Mike Stump11289f42009-09-09 15:08:12 +0000907 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000908 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
Francois Pichet783dd6e2010-11-21 06:08:52 +0000909 << IndirectField->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000910 }
911
912 // Build the implicit member references to the field of the
913 // anonymous struct/union.
914 Expr *Result = BaseObjectExpr;
John McCallfeb624a2010-11-23 20:48:44 +0000915
Francois Pichet783dd6e2010-11-21 06:08:52 +0000916 IndirectFieldDecl::chain_iterator FI = IndirectField->chain_begin(),
917 FEnd = IndirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +0000918
Francois Pichet783dd6e2010-11-21 06:08:52 +0000919 // Skip the first VarDecl if present.
920 if (BaseObject)
921 FI++;
922 for (; FI != FEnd; FI++) {
923 FieldDecl *Field = cast<FieldDecl>(*FI);
John McCall8ccfcb52009-09-24 19:53:00 +0000924
John McCallfeb624a2010-11-23 20:48:44 +0000925 // FIXME: the first access can be qualified
926 CXXScopeSpec SS;
John McCall8ccfcb52009-09-24 19:53:00 +0000927
John McCallfeb624a2010-11-23 20:48:44 +0000928 // FIXME: these are somewhat meaningless
929 DeclarationNameInfo MemberNameInfo(Field->getDeclName(), Loc);
930 DeclAccessPair FoundDecl = DeclAccessPair::make(Field, Field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +0000931
John McCallfeb624a2010-11-23 20:48:44 +0000932 Result = BuildFieldReferenceExpr(*this, Result, BaseObjectIsPointer,
933 SS, Field, FoundDecl, MemberNameInfo)
934 .take();
John McCall8ccfcb52009-09-24 19:53:00 +0000935
John McCallfeb624a2010-11-23 20:48:44 +0000936 // All the implicit accesses are dot-accesses.
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000937 BaseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000938 }
939
Sebastian Redlffbcf962009-01-18 18:53:16 +0000940 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000941}
942
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000943/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +0000944/// possibly a list of template arguments.
945///
946/// If this produces template arguments, it is permitted to call
947/// DecomposeTemplateName.
948///
949/// This actually loses a lot of source location information for
950/// non-standard name kinds; we should consider preserving that in
951/// some way.
952static void DecomposeUnqualifiedId(Sema &SemaRef,
953 const UnqualifiedId &Id,
954 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000955 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +0000956 const TemplateArgumentListInfo *&TemplateArgs) {
957 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
958 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
959 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
960
961 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
962 Id.TemplateId->getTemplateArgs(),
963 Id.TemplateId->NumArgs);
964 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
965 TemplateArgsPtr.release();
966
John McCall3e56fd42010-08-23 07:28:44 +0000967 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000968 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
969 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +0000970 TemplateArgs = &Buffer;
971 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000972 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +0000973 TemplateArgs = 0;
974 }
975}
976
John McCall69f9dbc2010-02-08 19:26:07 +0000977/// Determines whether the given record is "fully-formed" at the given
978/// location, i.e. whether a qualified lookup into it is assured of
979/// getting consistent results already.
John McCall10eae182009-11-30 22:42:35 +0000980static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
John McCall69f9dbc2010-02-08 19:26:07 +0000981 if (!Record->hasDefinition())
982 return false;
983
John McCall10eae182009-11-30 22:42:35 +0000984 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
985 E = Record->bases_end(); I != E; ++I) {
986 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
987 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
988 if (!BaseRT) return false;
989
990 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall69f9dbc2010-02-08 19:26:07 +0000991 if (!BaseRecord->hasDefinition() ||
John McCall10eae182009-11-30 22:42:35 +0000992 !IsFullyFormedScope(SemaRef, BaseRecord))
993 return false;
994 }
995
996 return true;
997}
998
John McCall2d74de92009-12-01 22:10:20 +0000999/// Determines if the given class is provably not derived from all of
1000/// the prospective base classes.
1001static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1002 CXXRecordDecl *Record,
1003 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001004 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001005 return false;
1006
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001007 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001008 if (!RD) return false;
1009 Record = cast<CXXRecordDecl>(RD);
1010
John McCall2d74de92009-12-01 22:10:20 +00001011 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1012 E = Record->bases_end(); I != E; ++I) {
1013 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1014 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1015 if (!BaseRT) return false;
1016
1017 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001018 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1019 return false;
1020 }
1021
1022 return true;
1023}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001024
John McCall2d74de92009-12-01 22:10:20 +00001025enum IMAKind {
1026 /// The reference is definitely not an instance member access.
1027 IMA_Static,
1028
1029 /// The reference may be an implicit instance member access.
1030 IMA_Mixed,
1031
1032 /// The reference may be to an instance member, but it is invalid if
1033 /// so, because the context is not an instance method.
1034 IMA_Mixed_StaticContext,
1035
1036 /// The reference may be to an instance member, but it is invalid if
1037 /// so, because the context is from an unrelated class.
1038 IMA_Mixed_Unrelated,
1039
1040 /// The reference is definitely an implicit instance member access.
1041 IMA_Instance,
1042
1043 /// The reference may be to an unresolved using declaration.
1044 IMA_Unresolved,
1045
1046 /// The reference may be to an unresolved using declaration and the
1047 /// context is not an instance method.
1048 IMA_Unresolved_StaticContext,
1049
John McCall2d74de92009-12-01 22:10:20 +00001050 /// All possible referrents are instance members and the current
1051 /// context is not an instance method.
1052 IMA_Error_StaticContext,
1053
1054 /// All possible referrents are instance members of an unrelated
1055 /// class.
1056 IMA_Error_Unrelated
1057};
1058
1059/// The given lookup names class member(s) and is not being used for
1060/// an address-of-member expression. Classify the type of access
1061/// according to whether it's possible that this reference names an
1062/// instance member. This is best-effort; it is okay to
1063/// conservatively answer "yes", in which case some errors will simply
1064/// not be caught until template-instantiation.
1065static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1066 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001067 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001068
John McCall87fe5d52010-05-20 01:18:31 +00001069 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001070 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001071 (!isa<CXXMethodDecl>(DC) ||
1072 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001073
1074 if (R.isUnresolvableResult())
1075 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1076
1077 // Collect all the declaring classes of instance members we find.
1078 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001079 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001080 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1081 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001082 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001083
John McCalla8ae2222010-04-06 21:38:20 +00001084 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001085 if (dyn_cast<FieldDecl>(D))
1086 hasField = true;
1087
John McCall2d74de92009-12-01 22:10:20 +00001088 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001089 Classes.insert(R->getCanonicalDecl());
1090 }
1091 else
1092 hasNonInstance = true;
1093 }
1094
1095 // If we didn't find any instance members, it can't be an implicit
1096 // member reference.
1097 if (Classes.empty())
1098 return IMA_Static;
1099
1100 // If the current context is not an instance method, it can't be
1101 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001102 if (isStaticContext) {
1103 if (hasNonInstance)
1104 return IMA_Mixed_StaticContext;
1105
1106 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1107 // C++0x [expr.prim.general]p10:
1108 // An id-expression that denotes a non-static data member or non-static
1109 // member function of a class can only be used:
1110 // (...)
1111 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1112 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1113 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1114 if (isUnevaluatedExpression)
1115 return IMA_Mixed_StaticContext;
1116 }
1117
1118 return IMA_Error_StaticContext;
1119 }
John McCall2d74de92009-12-01 22:10:20 +00001120
1121 // If we can prove that the current context is unrelated to all the
1122 // declaring classes, it can't be an implicit member reference (in
1123 // which case it's an error if any of those members are selected).
1124 if (IsProvablyNotDerivedFrom(SemaRef,
John McCall87fe5d52010-05-20 01:18:31 +00001125 cast<CXXMethodDecl>(DC)->getParent(),
John McCall2d74de92009-12-01 22:10:20 +00001126 Classes))
1127 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1128
1129 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1130}
1131
1132/// Diagnose a reference to a field with no object available.
1133static void DiagnoseInstanceReference(Sema &SemaRef,
1134 const CXXScopeSpec &SS,
1135 const LookupResult &R) {
1136 SourceLocation Loc = R.getNameLoc();
1137 SourceRange Range(Loc);
1138 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1139
1140 if (R.getAsSingle<FieldDecl>()) {
1141 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1142 if (MD->isStatic()) {
1143 // "invalid use of member 'x' in static member function"
1144 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
1145 << Range << R.getLookupName();
1146 return;
1147 }
1148 }
1149
1150 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
1151 << R.getLookupName() << Range;
1152 return;
1153 }
1154
1155 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001156}
1157
John McCalld681c392009-12-16 08:11:27 +00001158/// Diagnose an empty lookup.
1159///
1160/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001161bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1162 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001163 DeclarationName Name = R.getLookupName();
1164
John McCalld681c392009-12-16 08:11:27 +00001165 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001166 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001167 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1168 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001169 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001170 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001171 diagnostic_suggest = diag::err_undeclared_use_suggest;
1172 }
John McCalld681c392009-12-16 08:11:27 +00001173
Douglas Gregor598b08f2009-12-31 05:20:13 +00001174 // If the original lookup was an unqualified lookup, fake an
1175 // unqualified lookup. This is useful when (for example) the
1176 // original lookup would not have found something because it was a
1177 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001178 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001179 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001180 if (isa<CXXRecordDecl>(DC)) {
1181 LookupQualifiedName(R, DC);
1182
1183 if (!R.empty()) {
1184 // Don't give errors about ambiguities in this lookup.
1185 R.suppressDiagnostics();
1186
1187 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1188 bool isInstance = CurMethod &&
1189 CurMethod->isInstance() &&
1190 DC == CurMethod->getParent();
1191
1192 // Give a code modification hint to insert 'this->'.
1193 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1194 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001195 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001196 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1197 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001198 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001199 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001200 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001201 Diag(R.getNameLoc(), diagnostic) << Name
1202 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1203 QualType DepThisType = DepMethod->getThisType(Context);
1204 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1205 R.getNameLoc(), DepThisType, false);
1206 TemplateArgumentListInfo TList;
1207 if (ULE->hasExplicitTemplateArgs())
1208 ULE->copyTemplateArgumentsInto(TList);
1209 CXXDependentScopeMemberExpr *DepExpr =
1210 CXXDependentScopeMemberExpr::Create(
1211 Context, DepThis, DepThisType, true, SourceLocation(),
1212 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
1213 R.getLookupNameInfo(), &TList);
1214 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001215 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001216 // FIXME: we should be able to handle this case too. It is correct
1217 // to add this-> here. This is a workaround for PR7947.
1218 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001219 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001220 } else {
John McCalld681c392009-12-16 08:11:27 +00001221 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001222 }
John McCalld681c392009-12-16 08:11:27 +00001223
1224 // Do we really want to note all of these?
1225 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1226 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1227
1228 // Tell the callee to try to recover.
1229 return false;
1230 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001231
1232 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001233 }
1234 }
1235
Douglas Gregor598b08f2009-12-31 05:20:13 +00001236 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001237 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001238 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001239 if (!R.empty()) {
1240 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1241 if (SS.isEmpty())
1242 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1243 << FixItHint::CreateReplacement(R.getNameLoc(),
1244 R.getLookupName().getAsString());
1245 else
1246 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1247 << Name << computeDeclContext(SS, false) << R.getLookupName()
1248 << SS.getRange()
1249 << FixItHint::CreateReplacement(R.getNameLoc(),
1250 R.getLookupName().getAsString());
1251 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1252 Diag(ND->getLocation(), diag::note_previous_decl)
1253 << ND->getDeclName();
1254
1255 // Tell the callee to try to recover.
1256 return false;
1257 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001258
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001259 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1260 // FIXME: If we ended up with a typo for a type name or
1261 // Objective-C class name, we're in trouble because the parser
1262 // is in the wrong place to recover. Suggest the typo
1263 // correction, but don't make it a fix-it since we're not going
1264 // to recover well anyway.
1265 if (SS.isEmpty())
1266 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1267 else
1268 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1269 << Name << computeDeclContext(SS, false) << R.getLookupName()
1270 << SS.getRange();
1271
1272 // Don't try to recover; it won't work.
1273 return true;
1274 }
1275 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001276 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001277 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001278 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001279 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001280 else
Douglas Gregor25363982010-01-01 00:15:04 +00001281 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001282 << Name << computeDeclContext(SS, false) << Corrected
1283 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001284 return true;
1285 }
Douglas Gregor25363982010-01-01 00:15:04 +00001286 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001287 }
1288
1289 // Emit a special diagnostic for failed member lookups.
1290 // FIXME: computing the declaration context might fail here (?)
1291 if (!SS.isEmpty()) {
1292 Diag(R.getNameLoc(), diag::err_no_member)
1293 << Name << computeDeclContext(SS, false)
1294 << SS.getRange();
1295 return true;
1296 }
1297
John McCalld681c392009-12-16 08:11:27 +00001298 // Give up, we can't recover.
1299 Diag(R.getNameLoc(), diagnostic) << Name;
1300 return true;
1301}
1302
Douglas Gregor05fcf842010-11-02 20:36:02 +00001303ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1304 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001305 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1306 if (!IDecl)
1307 return 0;
1308 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1309 if (!ClassImpDecl)
1310 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001311 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001312 if (!property)
1313 return 0;
1314 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001315 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1316 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001317 return 0;
1318 return property;
1319}
1320
Douglas Gregor05fcf842010-11-02 20:36:02 +00001321bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1322 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1323 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1324 if (!IDecl)
1325 return false;
1326 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1327 if (!ClassImpDecl)
1328 return false;
1329 if (ObjCPropertyImplDecl *PIDecl
1330 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1331 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1332 PIDecl->getPropertyIvarDecl())
1333 return false;
1334
1335 return true;
1336}
1337
Fariborz Jahanian18722982010-07-17 00:59:30 +00001338static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001339 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001340 IdentifierInfo *II,
1341 SourceLocation NameLoc) {
1342 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001343 bool LookForIvars;
1344 if (Lookup.empty())
1345 LookForIvars = true;
1346 else if (CurMeth->isClassMethod())
1347 LookForIvars = false;
1348 else
1349 LookForIvars = (Lookup.isSingleResult() &&
1350 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1351 if (!LookForIvars)
1352 return 0;
1353
Fariborz Jahanian18722982010-07-17 00:59:30 +00001354 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1355 if (!IDecl)
1356 return 0;
1357 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001358 if (!ClassImpDecl)
1359 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001360 bool DynamicImplSeen = false;
1361 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1362 if (!property)
1363 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001364 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001365 DynamicImplSeen =
1366 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001367 // property implementation has a designated ivar. No need to assume a new
1368 // one.
1369 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1370 return 0;
1371 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001372 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001373 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1374 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001375 NameLoc,
1376 II, PropType, /*Dinfo=*/0,
1377 ObjCIvarDecl::Protected,
1378 (Expr *)0, true);
1379 ClassImpDecl->addDecl(Ivar);
1380 IDecl->makeDeclVisibleInContext(Ivar, false);
1381 property->setPropertyIvarDecl(Ivar);
1382 return Ivar;
1383 }
1384 return 0;
1385}
1386
John McCalldadc5752010-08-24 06:29:42 +00001387ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001388 CXXScopeSpec &SS,
1389 UnqualifiedId &Id,
1390 bool HasTrailingLParen,
1391 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001392 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1393 "cannot be direct & operand and have a trailing lparen");
1394
1395 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001396 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001397
John McCall10eae182009-11-30 22:42:35 +00001398 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001399
1400 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001401 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001402 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001403 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001404
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001405 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001406 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001407 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001408
John McCalle66edc12009-11-24 19:00:30 +00001409 // C++ [temp.dep.expr]p3:
1410 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001411 // -- an identifier that was declared with a dependent type,
1412 // (note: handled after lookup)
1413 // -- a template-id that is dependent,
1414 // (note: handled in BuildTemplateIdExpr)
1415 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001416 // -- a nested-name-specifier that contains a class-name that
1417 // names a dependent type.
1418 // Determine whether this is a member of an unknown specialization;
1419 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001420 bool DependentID = false;
1421 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1422 Name.getCXXNameType()->isDependentType()) {
1423 DependentID = true;
1424 } else if (SS.isSet()) {
1425 DeclContext *DC = computeDeclContext(SS, false);
1426 if (DC) {
1427 if (RequireCompleteDeclContext(SS, DC))
1428 return ExprError();
1429 // FIXME: We should be checking whether DC is the current instantiation.
1430 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
1431 DependentID = !IsFullyFormedScope(*this, RD);
1432 } else {
1433 DependentID = true;
1434 }
1435 }
1436
1437 if (DependentID) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001438 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001439 TemplateArgs);
1440 }
Fariborz Jahanian86151342010-07-22 23:33:21 +00001441 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001442 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001443 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001444 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001445 // Lookup the template name again to correctly establish the context in
1446 // which it was found. This is really unfortunate as we already did the
1447 // lookup to determine that it was a template name in the first place. If
1448 // this becomes a performance hit, we can work harder to preserve those
1449 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001450 bool MemberOfUnknownSpecialization;
1451 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1452 MemberOfUnknownSpecialization);
John McCalle66edc12009-11-24 19:00:30 +00001453 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001454 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001455 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001456
John McCalle66edc12009-11-24 19:00:30 +00001457 // If this reference is in an Objective-C method, then we need to do
1458 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001459 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001460 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001461 if (E.isInvalid())
1462 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001463
John McCalle66edc12009-11-24 19:00:30 +00001464 Expr *Ex = E.takeAs<Expr>();
1465 if (Ex) return Owned(Ex);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001466 // Synthesize ivars lazily
1467 if (getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001468 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1469 if (const ObjCPropertyDecl *Property =
1470 canSynthesizeProvisionalIvar(II)) {
1471 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1472 Diag(Property->getLocation(), diag::note_property_declare);
1473 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001474 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1475 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001476 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001477 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001478 // for further use, this must be set to false if in class method.
1479 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001480 }
Chris Lattner59a25942008-03-31 00:36:02 +00001481 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001482
John McCalle66edc12009-11-24 19:00:30 +00001483 if (R.isAmbiguous())
1484 return ExprError();
1485
Douglas Gregor171c45a2009-02-18 21:56:37 +00001486 // Determine whether this name might be a candidate for
1487 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001488 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001489
John McCalle66edc12009-11-24 19:00:30 +00001490 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001491 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001492 // in C90, extension in C99, forbidden in C++).
1493 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1494 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1495 if (D) R.addDecl(D);
1496 }
1497
1498 // If this name wasn't predeclared and if this is not a function
1499 // call, diagnose the problem.
1500 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001501 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001502 return ExprError();
1503
1504 assert(!R.empty() &&
1505 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001506
1507 // If we found an Objective-C instance variable, let
1508 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001509 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001510 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1511 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001512 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001513 assert(E.isInvalid() || E.get());
1514 return move(E);
1515 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001516 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001517 }
Mike Stump11289f42009-09-09 15:08:12 +00001518
John McCalle66edc12009-11-24 19:00:30 +00001519 // This is guaranteed from this point on.
1520 assert(!R.empty() || ADL);
1521
1522 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001523 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
Fariborz Jahanianc15dfd82010-07-29 16:53:53 +00001524 !getLangOptions().ObjCNonFragileABI2 &&
1525 Var->isFileVarDecl()) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001526 ObjCPropertyDecl *Property = canSynthesizeProvisionalIvar(II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001527 if (Property) {
1528 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1529 Diag(Property->getLocation(), diag::note_property_declare);
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001530 Diag(Var->getLocation(), diag::note_global_declared_at);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001531 }
1532 }
John McCalle66edc12009-11-24 19:00:30 +00001533 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001534 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1535 // C99 DR 316 says that, if a function type comes from a
1536 // function definition (without a prototype), that type is only
1537 // used for checking compatibility. Therefore, when referencing
1538 // the function, we pretend that we don't have the full function
1539 // type.
John McCalle66edc12009-11-24 19:00:30 +00001540 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001541 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001542
Douglas Gregor3256d042009-06-30 15:47:41 +00001543 QualType T = Func->getType();
1544 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001545 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Eli Friedmanb41ad0f2010-05-17 02:50:18 +00001546 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(),
1547 Proto->getExtInfo());
John McCall7decc9e2010-11-18 06:31:45 +00001548 // Note that functions are r-values in C.
1549 return BuildDeclRefExpr(Func, NoProtoType, VK_RValue, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001550 }
1551 }
Mike Stump11289f42009-09-09 15:08:12 +00001552
John McCall2d74de92009-12-01 22:10:20 +00001553 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001554 // C++ [class.mfct.non-static]p3:
1555 // When an id-expression that is not part of a class member access
1556 // syntax and not used to form a pointer to member is used in the
1557 // body of a non-static member function of class X, if name lookup
1558 // resolves the name in the id-expression to a non-static non-type
1559 // member of some class C, the id-expression is transformed into a
1560 // class member access expression using (*this) as the
1561 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001562 //
1563 // But we don't actually need to do this for '&' operands if R
1564 // resolved to a function or overloaded function set, because the
1565 // expression is ill-formed if it actually works out to be a
1566 // non-static member function:
1567 //
1568 // C++ [expr.ref]p4:
1569 // Otherwise, if E1.E2 refers to a non-static member function. . .
1570 // [t]he expression can be used only as the left-hand operand of a
1571 // member function call.
1572 //
1573 // There are other safeguards against such uses, but it's important
1574 // to get this right here so that we don't end up making a
1575 // spuriously dependent expression if we're inside a dependent
1576 // instance method.
John McCall57500772009-12-16 12:17:52 +00001577 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001578 bool MightBeImplicitMember;
1579 if (!isAddressOfOperand)
1580 MightBeImplicitMember = true;
1581 else if (!SS.isEmpty())
1582 MightBeImplicitMember = false;
1583 else if (R.isOverloadedResult())
1584 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001585 else if (R.isUnresolvableResult())
1586 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001587 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001588 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1589 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001590
1591 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001592 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001593 }
1594
John McCalle66edc12009-11-24 19:00:30 +00001595 if (TemplateArgs)
1596 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001597
John McCalle66edc12009-11-24 19:00:30 +00001598 return BuildDeclarationNameExpr(SS, R, ADL);
1599}
1600
John McCall57500772009-12-16 12:17:52 +00001601/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001602ExprResult
John McCall57500772009-12-16 12:17:52 +00001603Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1604 LookupResult &R,
1605 const TemplateArgumentListInfo *TemplateArgs) {
1606 switch (ClassifyImplicitMemberAccess(*this, R)) {
1607 case IMA_Instance:
1608 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1609
John McCall57500772009-12-16 12:17:52 +00001610 case IMA_Mixed:
1611 case IMA_Mixed_Unrelated:
1612 case IMA_Unresolved:
1613 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1614
1615 case IMA_Static:
1616 case IMA_Mixed_StaticContext:
1617 case IMA_Unresolved_StaticContext:
1618 if (TemplateArgs)
1619 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1620 return BuildDeclarationNameExpr(SS, R, false);
1621
1622 case IMA_Error_StaticContext:
1623 case IMA_Error_Unrelated:
1624 DiagnoseInstanceReference(*this, SS, R);
1625 return ExprError();
1626 }
1627
1628 llvm_unreachable("unexpected instance member access kind");
1629 return ExprError();
1630}
1631
John McCall10eae182009-11-30 22:42:35 +00001632/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1633/// declaration name, generally during template instantiation.
1634/// There's a large number of things which don't need to be done along
1635/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001636ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001637Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001638 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001639 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001640 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001641 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001642
John McCall0b66eb32010-05-01 00:40:08 +00001643 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001644 return ExprError();
1645
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001646 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001647 LookupQualifiedName(R, DC);
1648
1649 if (R.isAmbiguous())
1650 return ExprError();
1651
1652 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001653 Diag(NameInfo.getLoc(), diag::err_no_member)
1654 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001655 return ExprError();
1656 }
1657
1658 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1659}
1660
1661/// LookupInObjCMethod - The parser has read a name in, and Sema has
1662/// detected that we're currently inside an ObjC method. Perform some
1663/// additional lookup.
1664///
1665/// Ideally, most of this would be done by lookup, but there's
1666/// actually quite a lot of extra work involved.
1667///
1668/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001669ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001670Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001671 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001672 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001673 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001674
John McCalle66edc12009-11-24 19:00:30 +00001675 // There are two cases to handle here. 1) scoped lookup could have failed,
1676 // in which case we should look for an ivar. 2) scoped lookup could have
1677 // found a decl, but that decl is outside the current instance method (i.e.
1678 // a global variable). In these two cases, we do a lookup for an ivar with
1679 // this name, if the lookup sucedes, we replace it our current decl.
1680
1681 // If we're in a class method, we don't normally want to look for
1682 // ivars. But if we don't find anything else, and there's an
1683 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001684 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001685
1686 bool LookForIvars;
1687 if (Lookup.empty())
1688 LookForIvars = true;
1689 else if (IsClassMethod)
1690 LookForIvars = false;
1691 else
1692 LookForIvars = (Lookup.isSingleResult() &&
1693 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001694 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001695 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001696 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001697 ObjCInterfaceDecl *ClassDeclared;
1698 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1699 // Diagnose using an ivar in a class method.
1700 if (IsClassMethod)
1701 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1702 << IV->getDeclName());
1703
1704 // If we're referencing an invalid decl, just return this as a silent
1705 // error node. The error diagnostic was already emitted on the decl.
1706 if (IV->isInvalidDecl())
1707 return ExprError();
1708
1709 // Check if referencing a field with __attribute__((deprecated)).
1710 if (DiagnoseUseOfDecl(IV, Loc))
1711 return ExprError();
1712
1713 // Diagnose the use of an ivar outside of the declaring class.
1714 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1715 ClassDeclared != IFace)
1716 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1717
1718 // FIXME: This should use a new expr for a direct reference, don't
1719 // turn this into Self->ivar, just return a BareIVarExpr or something.
1720 IdentifierInfo &II = Context.Idents.get("self");
1721 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001722 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001723 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001724 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001725 SelfName, false, false);
1726 if (SelfExpr.isInvalid())
1727 return ExprError();
1728
John McCall27584242010-12-06 20:48:59 +00001729 Expr *SelfE = SelfExpr.take();
1730 DefaultLvalueConversion(SelfE);
1731
John McCalle66edc12009-11-24 19:00:30 +00001732 MarkDeclarationReferenced(Loc, IV);
1733 return Owned(new (Context)
1734 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall27584242010-12-06 20:48:59 +00001735 SelfE, true, true));
John McCalle66edc12009-11-24 19:00:30 +00001736 }
Chris Lattner87313662010-04-12 05:10:17 +00001737 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001738 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001739 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001740 ObjCInterfaceDecl *ClassDeclared;
1741 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1742 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1743 IFace == ClassDeclared)
1744 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1745 }
1746 }
1747
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001748 if (Lookup.empty() && II && AllowBuiltinCreation) {
1749 // FIXME. Consolidate this with similar code in LookupName.
1750 if (unsigned BuiltinID = II->getBuiltinID()) {
1751 if (!(getLangOptions().CPlusPlus &&
1752 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1753 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1754 S, Lookup.isForRedeclaration(),
1755 Lookup.getNameLoc());
1756 if (D) Lookup.addDecl(D);
1757 }
1758 }
1759 }
John McCalle66edc12009-11-24 19:00:30 +00001760 // Sentinel value saying that we didn't do anything special.
1761 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001762}
John McCalld14a8642009-11-21 08:51:07 +00001763
John McCall16df1e52010-03-30 21:47:33 +00001764/// \brief Cast a base object to a member's actual type.
1765///
1766/// Logically this happens in three phases:
1767///
1768/// * First we cast from the base type to the naming class.
1769/// The naming class is the class into which we were looking
1770/// when we found the member; it's the qualifier type if a
1771/// qualifier was provided, and otherwise it's the base type.
1772///
1773/// * Next we cast from the naming class to the declaring class.
1774/// If the member we found was brought into a class's scope by
1775/// a using declaration, this is that class; otherwise it's
1776/// the class declaring the member.
1777///
1778/// * Finally we cast from the declaring class to the "true"
1779/// declaring class of the member. This conversion does not
1780/// obey access control.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001781bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001782Sema::PerformObjectMemberConversion(Expr *&From,
1783 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001784 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001785 NamedDecl *Member) {
1786 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1787 if (!RD)
1788 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001789
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001790 QualType DestRecordType;
1791 QualType DestType;
1792 QualType FromRecordType;
1793 QualType FromType = From->getType();
1794 bool PointerConversions = false;
1795 if (isa<FieldDecl>(Member)) {
1796 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001797
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001798 if (FromType->getAs<PointerType>()) {
1799 DestType = Context.getPointerType(DestRecordType);
1800 FromRecordType = FromType->getPointeeType();
1801 PointerConversions = true;
1802 } else {
1803 DestType = DestRecordType;
1804 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001805 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001806 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1807 if (Method->isStatic())
1808 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001809
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001810 DestType = Method->getThisType(Context);
1811 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001812
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001813 if (FromType->getAs<PointerType>()) {
1814 FromRecordType = FromType->getPointeeType();
1815 PointerConversions = true;
1816 } else {
1817 FromRecordType = FromType;
1818 DestType = DestRecordType;
1819 }
1820 } else {
1821 // No conversion necessary.
1822 return false;
1823 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001824
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001825 if (DestType->isDependentType() || FromType->isDependentType())
1826 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001827
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001828 // If the unqualified types are the same, no conversion is necessary.
1829 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1830 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001831
John McCall16df1e52010-03-30 21:47:33 +00001832 SourceRange FromRange = From->getSourceRange();
1833 SourceLocation FromLoc = FromRange.getBegin();
1834
John McCall2536c6d2010-08-25 10:28:54 +00001835 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001836
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001837 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001838 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001839 // class name.
1840 //
1841 // If the member was a qualified name and the qualified referred to a
1842 // specific base subobject type, we'll cast to that intermediate type
1843 // first and then to the object in which the member is declared. That allows
1844 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1845 //
1846 // class Base { public: int x; };
1847 // class Derived1 : public Base { };
1848 // class Derived2 : public Base { };
1849 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1850 //
1851 // void VeryDerived::f() {
1852 // x = 17; // error: ambiguous base subobjects
1853 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1854 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001855 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001856 QualType QType = QualType(Qualifier->getAsType(), 0);
1857 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1858 assert(QType->isRecordType() && "lookup done with non-record type");
1859
1860 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1861
1862 // In C++98, the qualifier type doesn't actually have to be a base
1863 // type of the object type, in which case we just ignore it.
1864 // Otherwise build the appropriate casts.
1865 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00001866 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001867 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001868 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001869 return true;
1870
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001871 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00001872 QType = Context.getPointerType(QType);
John McCall2536c6d2010-08-25 10:28:54 +00001873 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
1874 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00001875
1876 FromType = QType;
1877 FromRecordType = QRecordType;
1878
1879 // If the qualifier type was the same as the destination type,
1880 // we're done.
1881 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1882 return false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001883 }
1884 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001885
John McCall16df1e52010-03-30 21:47:33 +00001886 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001887
John McCall16df1e52010-03-30 21:47:33 +00001888 // If we actually found the member through a using declaration, cast
1889 // down to the using declaration's type.
1890 //
1891 // Pointer equality is fine here because only one declaration of a
1892 // class ever has member declarations.
1893 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1894 assert(isa<UsingShadowDecl>(FoundDecl));
1895 QualType URecordType = Context.getTypeDeclType(
1896 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1897
1898 // We only need to do this if the naming-class to declaring-class
1899 // conversion is non-trivial.
1900 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1901 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00001902 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001903 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001904 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001905 return true;
Alexis Huntc46382e2010-04-28 23:02:27 +00001906
John McCall16df1e52010-03-30 21:47:33 +00001907 QualType UType = URecordType;
1908 if (PointerConversions)
1909 UType = Context.getPointerType(UType);
John McCalle3027922010-08-25 11:45:40 +00001910 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001911 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00001912 FromType = UType;
1913 FromRecordType = URecordType;
1914 }
1915
1916 // We don't do access control for the conversion from the
1917 // declaring class to the true declaring class.
1918 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001919 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001920
John McCallcf142162010-08-07 06:22:56 +00001921 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00001922 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1923 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00001924 IgnoreAccess))
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001925 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001926
John McCalle3027922010-08-25 11:45:40 +00001927 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001928 VK, &BasePath);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001929 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001930}
Douglas Gregor3256d042009-06-30 15:47:41 +00001931
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001932/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001933static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001934 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00001935 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001936 const DeclarationNameInfo &MemberNameInfo,
1937 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00001938 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00001939 const TemplateArgumentListInfo *TemplateArgs = 0) {
1940 NestedNameSpecifier *Qualifier = 0;
1941 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001942 if (SS.isSet()) {
1943 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1944 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001945 }
Mike Stump11289f42009-09-09 15:08:12 +00001946
John McCalle66edc12009-11-24 19:00:30 +00001947 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001948 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00001949 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00001950}
1951
John McCallfeb624a2010-11-23 20:48:44 +00001952static ExprResult
1953BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1954 const CXXScopeSpec &SS, FieldDecl *Field,
1955 DeclAccessPair FoundDecl,
1956 const DeclarationNameInfo &MemberNameInfo) {
1957 // x.a is an l-value if 'a' has a reference type. Otherwise:
1958 // x.a is an l-value/x-value/pr-value if the base is (and note
1959 // that *x is always an l-value), except that if the base isn't
1960 // an ordinary object then we must have an rvalue.
1961 ExprValueKind VK = VK_LValue;
1962 ExprObjectKind OK = OK_Ordinary;
1963 if (!IsArrow) {
1964 if (BaseExpr->getObjectKind() == OK_Ordinary)
1965 VK = BaseExpr->getValueKind();
1966 else
1967 VK = VK_RValue;
1968 }
1969 if (VK != VK_RValue && Field->isBitField())
1970 OK = OK_BitField;
1971
1972 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1973 QualType MemberType = Field->getType();
1974 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1975 MemberType = Ref->getPointeeType();
1976 VK = VK_LValue;
1977 } else {
1978 QualType BaseType = BaseExpr->getType();
1979 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1980
1981 Qualifiers BaseQuals = BaseType.getQualifiers();
1982
1983 // GC attributes are never picked up by members.
1984 BaseQuals.removeObjCGCAttr();
1985
1986 // CVR attributes from the base are picked up by members,
1987 // except that 'mutable' members don't pick up 'const'.
1988 if (Field->isMutable()) BaseQuals.removeConst();
1989
1990 Qualifiers MemberQuals
1991 = S.Context.getCanonicalType(MemberType).getQualifiers();
1992
1993 // TR 18037 does not allow fields to be declared with address spaces.
1994 assert(!MemberQuals.hasAddressSpace());
1995
1996 Qualifiers Combined = BaseQuals + MemberQuals;
1997 if (Combined != MemberQuals)
1998 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1999 }
2000
2001 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2002 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2003 FoundDecl, Field))
2004 return ExprError();
2005 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2006 Field, FoundDecl, MemberNameInfo,
2007 MemberType, VK, OK));
2008}
2009
John McCall2d74de92009-12-01 22:10:20 +00002010/// Builds an implicit member access expression. The current context
2011/// is known to be an instance method, and the given unqualified lookup
2012/// set is known to contain only instance members, at least one of which
2013/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002014ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002015Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2016 LookupResult &R,
2017 const TemplateArgumentListInfo *TemplateArgs,
2018 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002019 assert(!R.empty() && !R.isAmbiguous());
2020
John McCalld14a8642009-11-21 08:51:07 +00002021 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002022
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002023 // We may have found a field within an anonymous union or struct
2024 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00002025 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00002026 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002027 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
2028 return BuildAnonymousStructUnionMemberReference(Loc, FD);
2029
Sebastian Redlffbcf962009-01-18 18:53:16 +00002030
John McCall2d74de92009-12-01 22:10:20 +00002031 // If this is known to be an instance access, go ahead and build a
2032 // 'this' expression now.
John McCall87fe5d52010-05-20 01:18:31 +00002033 DeclContext *DC = getFunctionLevelDeclContext();
2034 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2d74de92009-12-01 22:10:20 +00002035 Expr *This = 0; // null signifies implicit access
2036 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002037 SourceLocation Loc = R.getNameLoc();
2038 if (SS.getRange().isValid())
2039 Loc = SS.getRange().getBegin();
2040 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002041 }
2042
John McCallb268a282010-08-23 23:25:46 +00002043 return BuildMemberReferenceExpr(This, ThisType,
John McCall2d74de92009-12-01 22:10:20 +00002044 /*OpLoc*/ SourceLocation(),
2045 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002046 SS,
2047 /*FirstQualifierInScope*/ 0,
2048 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002049}
2050
John McCalle66edc12009-11-24 19:00:30 +00002051bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002052 const LookupResult &R,
2053 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002054 // Only when used directly as the postfix-expression of a call.
2055 if (!HasTrailingLParen)
2056 return false;
2057
2058 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002059 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002060 return false;
2061
2062 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002063 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002064 return false;
2065
2066 // Turn off ADL when we find certain kinds of declarations during
2067 // normal lookup:
2068 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2069 NamedDecl *D = *I;
2070
2071 // C++0x [basic.lookup.argdep]p3:
2072 // -- a declaration of a class member
2073 // Since using decls preserve this property, we check this on the
2074 // original decl.
John McCall57500772009-12-16 12:17:52 +00002075 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002076 return false;
2077
2078 // C++0x [basic.lookup.argdep]p3:
2079 // -- a block-scope function declaration that is not a
2080 // using-declaration
2081 // NOTE: we also trigger this for function templates (in fact, we
2082 // don't check the decl type at all, since all other decl types
2083 // turn off ADL anyway).
2084 if (isa<UsingShadowDecl>(D))
2085 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2086 else if (D->getDeclContext()->isFunctionOrMethod())
2087 return false;
2088
2089 // C++0x [basic.lookup.argdep]p3:
2090 // -- a declaration that is neither a function or a function
2091 // template
2092 // And also for builtin functions.
2093 if (isa<FunctionDecl>(D)) {
2094 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2095
2096 // But also builtin functions.
2097 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2098 return false;
2099 } else if (!isa<FunctionTemplateDecl>(D))
2100 return false;
2101 }
2102
2103 return true;
2104}
2105
2106
John McCalld14a8642009-11-21 08:51:07 +00002107/// Diagnoses obvious problems with the use of the given declaration
2108/// as an expression. This is only actually called for lookups that
2109/// were not overloaded, and it doesn't promise that the declaration
2110/// will in fact be used.
2111static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2112 if (isa<TypedefDecl>(D)) {
2113 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2114 return true;
2115 }
2116
2117 if (isa<ObjCInterfaceDecl>(D)) {
2118 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2119 return true;
2120 }
2121
2122 if (isa<NamespaceDecl>(D)) {
2123 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2124 return true;
2125 }
2126
2127 return false;
2128}
2129
John McCalldadc5752010-08-24 06:29:42 +00002130ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002131Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002132 LookupResult &R,
2133 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002134 // If this is a single, fully-resolved result and we don't need ADL,
2135 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002136 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002137 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2138 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002139
2140 // We only need to check the declaration if there's exactly one
2141 // result, because in the overloaded case the results can only be
2142 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002143 if (R.isSingleResult() &&
2144 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002145 return ExprError();
2146
John McCall58cc69d2010-01-27 01:50:18 +00002147 // Otherwise, just build an unresolved lookup expression. Suppress
2148 // any lookup-related diagnostics; we'll hash these out later, when
2149 // we've picked a target.
2150 R.suppressDiagnostics();
2151
John McCalld14a8642009-11-21 08:51:07 +00002152 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002153 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00002154 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002155 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002156 NeedsADL, R.isOverloadedResult(),
2157 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002158
2159 return Owned(ULE);
2160}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002161
John McCall7decc9e2010-11-18 06:31:45 +00002162static ExprValueKind getValueKindForDecl(ASTContext &Context,
2163 const ValueDecl *D) {
John McCall4bc41ae2010-11-18 19:01:18 +00002164 // FIXME: It's not clear to me why NonTypeTemplateParmDecl is a VarDecl.
2165 if (isa<VarDecl>(D) && !isa<NonTypeTemplateParmDecl>(D)) return VK_LValue;
2166 if (isa<FieldDecl>(D)) return VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00002167 if (!Context.getLangOptions().CPlusPlus) return VK_RValue;
2168 if (isa<FunctionDecl>(D)) {
2169 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
2170 return VK_RValue;
2171 return VK_LValue;
2172 }
2173 return Expr::getValueKindForType(D->getType());
2174}
2175
John McCalld14a8642009-11-21 08:51:07 +00002176
2177/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002178ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002179Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002180 const DeclarationNameInfo &NameInfo,
2181 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002182 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002183 assert(!isa<FunctionTemplateDecl>(D) &&
2184 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002185
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002186 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002187 if (CheckDeclInExpr(*this, Loc, D))
2188 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002189
Douglas Gregore7488b92009-12-01 16:58:18 +00002190 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2191 // Specifically diagnose references to class templates that are missing
2192 // a template argument list.
2193 Diag(Loc, diag::err_template_decl_ref)
2194 << Template << SS.getRange();
2195 Diag(Template->getLocation(), diag::note_template_decl_here);
2196 return ExprError();
2197 }
2198
2199 // Make sure that we're referring to a value.
2200 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2201 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002202 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002203 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002204 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002205 return ExprError();
2206 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002207
Douglas Gregor171c45a2009-02-18 21:56:37 +00002208 // Check whether this declaration can be used. Note that we suppress
2209 // this check when we're going to perform argument-dependent lookup
2210 // on this function name, because this might not be the function
2211 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002212 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002213 return ExprError();
2214
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002215 // Only create DeclRefExpr's for valid Decl's.
2216 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002217 return ExprError();
2218
Francois Pichet783dd6e2010-11-21 06:08:52 +00002219 // Handle anonymous.
2220 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(VD))
2221 return BuildAnonymousStructUnionMemberReference(Loc, FD);
2222
John McCall7decc9e2010-11-18 06:31:45 +00002223 ExprValueKind VK = getValueKindForDecl(Context, VD);
2224
Chris Lattner2a9d9892008-10-20 05:16:36 +00002225 // If the identifier reference is inside a block, and it refers to a value
2226 // that is outside the block, create a BlockDeclRefExpr instead of a
2227 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2228 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002229 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002230 // We do not do this for things like enum constants, global variables, etc,
2231 // as they do not get snapshotted.
2232 //
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002233 if (getCurBlock() &&
Douglas Gregor9a28e842010-03-01 23:15:13 +00002234 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
Mike Stump7dafa0d2010-01-05 02:56:35 +00002235 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
2236 Diag(Loc, diag::err_ref_vm_type);
2237 Diag(D->getLocation(), diag::note_declared_at);
2238 return ExprError();
2239 }
2240
Fariborz Jahanianfa24e102010-03-16 23:39:51 +00002241 if (VD->getType()->isArrayType()) {
Mike Stump8971a862010-01-05 03:10:36 +00002242 Diag(Loc, diag::err_ref_array_type);
2243 Diag(D->getLocation(), diag::note_declared_at);
2244 return ExprError();
2245 }
2246
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00002247 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00002248 QualType ExprTy = VD->getType().getNonReferenceType();
John McCall7decc9e2010-11-18 06:31:45 +00002249
Steve Naroff1d95e5a2008-10-10 01:28:17 +00002250 // The BlocksAttr indicates the variable is bound by-reference.
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002251 bool byrefVar = (VD->getAttr<BlocksAttr>() != 0);
Fariborz Jahanian70c0b082010-07-12 17:26:57 +00002252 QualType T = VD->getType();
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002253 BlockDeclRefExpr *BDRE;
2254
2255 if (!byrefVar) {
2256 // This is to record that a 'const' was actually synthesize and added.
2257 bool constAdded = !ExprTy.isConstQualified();
2258 // Variable will be bound by-copy, make it const within the closure.
2259 ExprTy.addConst();
John McCall7decc9e2010-11-18 06:31:45 +00002260 BDRE = new (Context) BlockDeclRefExpr(VD, ExprTy, VK,
2261 Loc, false, constAdded);
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002262 }
2263 else
John McCall7decc9e2010-11-18 06:31:45 +00002264 BDRE = new (Context) BlockDeclRefExpr(VD, ExprTy, VK, Loc, true);
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002265
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002266 if (getLangOptions().CPlusPlus) {
2267 if (!T->isDependentType() && !T->isReferenceType()) {
2268 Expr *E = new (Context)
2269 DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T,
John McCall7decc9e2010-11-18 06:31:45 +00002270 VK, SourceLocation());
Fariborz Jahanian2a5deb52010-11-11 00:11:38 +00002271 if (T->getAs<RecordType>())
2272 if (!T->isUnionType()) {
2273 ExprResult Res = PerformCopyInitialization(
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002274 InitializedEntity::InitializeBlock(VD->getLocation(),
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002275 T, false),
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002276 SourceLocation(),
2277 Owned(E));
Fariborz Jahanian2a5deb52010-11-11 00:11:38 +00002278 if (!Res.isInvalid()) {
Douglas Gregora40433a2010-12-07 00:41:46 +00002279 Res = MaybeCreateExprWithCleanups(Res);
Fariborz Jahanian2a5deb52010-11-11 00:11:38 +00002280 Expr *Init = Res.takeAs<Expr>();
2281 BDRE->setCopyConstructorExpr(Init);
2282 }
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002283 }
Fariborz Jahanianea882cd2010-06-04 21:35:44 +00002284 }
2285 }
2286 return Owned(BDRE);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00002287 }
2288 // If this reference is not in a block or if the referenced variable is
2289 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00002290
John McCall7decc9e2010-11-18 06:31:45 +00002291 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002292 NameInfo, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00002293}
Chris Lattnere168f762006-11-10 05:29:30 +00002294
John McCalldadc5752010-08-24 06:29:42 +00002295ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlffbcf962009-01-18 18:53:16 +00002296 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002297 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002298
Chris Lattnere168f762006-11-10 05:29:30 +00002299 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002300 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002301 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2302 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2303 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002304 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002305
Chris Lattnera81a0272008-01-12 08:14:25 +00002306 // Pre-defined identifiers are of type char[x], where x is the length of the
2307 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002308
Anders Carlsson2fb08242009-09-08 18:24:21 +00002309 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002310 if (!currentDecl && getCurBlock())
2311 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002312 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002313 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002314 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002315 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002316
Anders Carlsson0b209a82009-09-11 01:22:35 +00002317 QualType ResTy;
2318 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2319 ResTy = Context.DependentTy;
2320 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002321 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002322
Anders Carlsson0b209a82009-09-11 01:22:35 +00002323 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002324 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002325 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2326 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002327 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002328}
2329
John McCalldadc5752010-08-24 06:29:42 +00002330ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002331 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002332 bool Invalid = false;
2333 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2334 if (Invalid)
2335 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002336
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002337 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2338 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002339 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002340 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002341
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002342 QualType Ty;
2343 if (!getLangOptions().CPlusPlus)
2344 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2345 else if (Literal.isWide())
2346 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002347 else if (Literal.isMultiChar())
2348 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002349 else
2350 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002351
Sebastian Redl20614a72009-01-20 22:23:13 +00002352 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2353 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002354 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002355}
2356
John McCalldadc5752010-08-24 06:29:42 +00002357ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002358 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002359 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2360 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002361 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002362 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002363 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002364 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002365 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002366
Chris Lattner23b7eb62007-06-15 23:05:46 +00002367 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002368 // Add padding so that NumericLiteralParser can overread by one character.
2369 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002370 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002371
Chris Lattner67ca9252007-05-21 01:08:44 +00002372 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002373 bool Invalid = false;
2374 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2375 if (Invalid)
2376 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002377
Mike Stump11289f42009-09-09 15:08:12 +00002378 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002379 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002380 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002381 return ExprError();
2382
Chris Lattner1c20a172007-08-26 03:42:43 +00002383 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002384
Chris Lattner1c20a172007-08-26 03:42:43 +00002385 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002386 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002387 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002388 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002389 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002390 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002391 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002392 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002393
2394 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2395
John McCall53b93a02009-12-24 09:08:04 +00002396 using llvm::APFloat;
2397 APFloat Val(Format);
2398
2399 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002400
2401 // Overflow is always an error, but underflow is only an error if
2402 // we underflowed to zero (APFloat reports denormals as underflow).
2403 if ((result & APFloat::opOverflow) ||
2404 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002405 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002406 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002407 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002408 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002409 APFloat::getLargest(Format).toString(buffer);
2410 } else {
John McCall62abc942010-02-26 23:35:57 +00002411 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002412 APFloat::getSmallest(Format).toString(buffer);
2413 }
2414
2415 Diag(Tok.getLocation(), diagnostic)
2416 << Ty
2417 << llvm::StringRef(buffer.data(), buffer.size());
2418 }
2419
2420 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002421 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002422
Peter Collingbourne0b69e1a2010-12-04 01:50:56 +00002423 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2424 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2425
Chris Lattner1c20a172007-08-26 03:42:43 +00002426 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002427 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002428 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002429 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002430
Neil Boothac582c52007-08-29 22:00:19 +00002431 // long long is a C99 feature.
2432 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002433 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002434 Diag(Tok.getLocation(), diag::ext_longlong);
2435
Chris Lattner67ca9252007-05-21 01:08:44 +00002436 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002437 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002438
Chris Lattner67ca9252007-05-21 01:08:44 +00002439 if (Literal.GetIntegerValue(ResultVal)) {
2440 // If this value didn't fit into uintmax_t, warn and force to ull.
2441 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002442 Ty = Context.UnsignedLongLongTy;
2443 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002444 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002445 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002446 // If this value fits into a ULL, try to figure out what else it fits into
2447 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002448
Chris Lattner67ca9252007-05-21 01:08:44 +00002449 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2450 // be an unsigned int.
2451 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2452
2453 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002454 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002455 if (!Literal.isLong && !Literal.isLongLong) {
2456 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002457 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002458
Chris Lattner67ca9252007-05-21 01:08:44 +00002459 // Does it fit in a unsigned int?
2460 if (ResultVal.isIntN(IntSize)) {
2461 // Does it fit in a signed int?
2462 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002463 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002464 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002465 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002466 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002467 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002468 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002469
Chris Lattner67ca9252007-05-21 01:08:44 +00002470 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002471 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002472 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002473
Chris Lattner67ca9252007-05-21 01:08:44 +00002474 // Does it fit in a unsigned long?
2475 if (ResultVal.isIntN(LongSize)) {
2476 // Does it fit in a signed long?
2477 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002478 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002479 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002480 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002481 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002482 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002483 }
2484
Chris Lattner67ca9252007-05-21 01:08:44 +00002485 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002486 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002487 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002488
Chris Lattner67ca9252007-05-21 01:08:44 +00002489 // Does it fit in a unsigned long long?
2490 if (ResultVal.isIntN(LongLongSize)) {
2491 // Does it fit in a signed long long?
2492 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002493 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002494 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002495 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002496 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002497 }
2498 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002499
Chris Lattner67ca9252007-05-21 01:08:44 +00002500 // If we still couldn't decide a type, we probably have something that
2501 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002502 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002503 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002504 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002505 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002506 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002507
Chris Lattner55258cf2008-05-09 05:59:00 +00002508 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002509 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002510 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002511 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002512 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002513
Chris Lattner1c20a172007-08-26 03:42:43 +00002514 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2515 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002516 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002517 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002518
2519 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002520}
2521
John McCalldadc5752010-08-24 06:29:42 +00002522ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002523 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002524 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002525 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002526}
2527
Steve Naroff71b59a92007-06-04 22:22:31 +00002528/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002529/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002530bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00002531 SourceLocation OpLoc,
John McCall36e7fe32010-10-12 00:20:44 +00002532 SourceRange ExprRange,
Sebastian Redl6f282892008-11-11 17:56:53 +00002533 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002534 if (exprType->isDependentType())
2535 return false;
2536
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002537 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2538 // the result is the size of the referenced type."
2539 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2540 // result shall be the alignment of the referenced type."
2541 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2542 exprType = Ref->getPointeeType();
2543
Steve Naroff043d45d2007-05-15 02:32:35 +00002544 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002545 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002546 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002547 if (isSizeof)
2548 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2549 return false;
2550 }
Mike Stump11289f42009-09-09 15:08:12 +00002551
Chris Lattner62975a72009-04-24 00:30:45 +00002552 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002553 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002554 Diag(OpLoc, diag::ext_sizeof_void_type)
2555 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002556 return false;
2557 }
Mike Stump11289f42009-09-09 15:08:12 +00002558
Chris Lattner62975a72009-04-24 00:30:45 +00002559 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002560 PDiag(diag::err_sizeof_alignof_incomplete_type)
2561 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002562 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002563
Chris Lattner62975a72009-04-24 00:30:45 +00002564 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002565 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002566 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002567 << exprType << isSizeof << ExprRange;
2568 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002569 }
Mike Stump11289f42009-09-09 15:08:12 +00002570
Chris Lattner62975a72009-04-24 00:30:45 +00002571 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002572}
2573
John McCall36e7fe32010-10-12 00:20:44 +00002574static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2575 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002576 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002577
Mike Stump11289f42009-09-09 15:08:12 +00002578 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002579 if (isa<DeclRefExpr>(E))
2580 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002581
2582 // Cannot know anything else if the expression is dependent.
2583 if (E->isTypeDependent())
2584 return false;
2585
Douglas Gregor71235ec2009-05-02 02:18:30 +00002586 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00002587 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00002588 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002589 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002590
2591 // Alignment of a field access is always okay, so long as it isn't a
2592 // bit-field.
2593 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002594 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002595 return false;
2596
John McCall36e7fe32010-10-12 00:20:44 +00002597 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
Chris Lattner8dff0172009-01-24 20:17:12 +00002598}
2599
Douglas Gregor0950e412009-03-13 21:01:28 +00002600/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002601ExprResult
John McCallbcd03502009-12-07 02:54:59 +00002602Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00002603 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002604 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002605 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002606 return ExprError();
2607
John McCallbcd03502009-12-07 02:54:59 +00002608 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002609
Douglas Gregor0950e412009-03-13 21:01:28 +00002610 if (!T->isDependentType() &&
2611 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2612 return ExprError();
2613
2614 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00002615 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00002616 Context.getSizeType(), OpLoc,
2617 R.getEnd()));
2618}
2619
2620/// \brief Build a sizeof or alignof expression given an expression
2621/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002622ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00002623Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002624 bool isSizeOf, SourceRange R) {
2625 // Verify that the operand is valid.
2626 bool isInvalid = false;
2627 if (E->isTypeDependent()) {
2628 // Delay type-checking for type-dependent expressions.
2629 } else if (!isSizeOf) {
John McCall36e7fe32010-10-12 00:20:44 +00002630 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002631 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002632 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2633 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00002634 } else if (E->getType()->isPlaceholderType()) {
2635 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2636 if (PE.isInvalid()) return ExprError();
2637 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00002638 } else {
2639 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2640 }
2641
2642 if (isInvalid)
2643 return ExprError();
2644
2645 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2646 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2647 Context.getSizeType(), OpLoc,
2648 R.getEnd()));
2649}
2650
Sebastian Redl6f282892008-11-11 17:56:53 +00002651/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2652/// the same for @c alignof and @c __alignof
2653/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002654ExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00002655Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2656 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002657 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002658 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002659
Sebastian Redl6f282892008-11-11 17:56:53 +00002660 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002661 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002662 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
John McCallbcd03502009-12-07 02:54:59 +00002663 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002664 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002665
Douglas Gregor0950e412009-03-13 21:01:28 +00002666 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00002667 ExprResult Result
Douglas Gregor0950e412009-03-13 21:01:28 +00002668 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2669
Douglas Gregor0950e412009-03-13 21:01:28 +00002670 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002671}
2672
John McCall4bc41ae2010-11-18 19:01:18 +00002673static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2674 bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002675 if (V->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002676 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002677
John McCall34376a62010-12-04 03:47:34 +00002678 // _Real and _Imag are only l-values for normal l-values.
2679 if (V->getObjectKind() != OK_Ordinary)
John McCall27584242010-12-06 20:48:59 +00002680 S.DefaultLvalueConversion(V);
John McCall34376a62010-12-04 03:47:34 +00002681
Chris Lattnere267f5d2007-08-26 05:39:26 +00002682 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00002683 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002684 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002685
Chris Lattnere267f5d2007-08-26 05:39:26 +00002686 // Otherwise they pass through real integer and floating point types here.
2687 if (V->getType()->isArithmeticType())
2688 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002689
John McCall36226622010-10-12 02:09:17 +00002690 // Test for placeholders.
John McCall4bc41ae2010-11-18 19:01:18 +00002691 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall36226622010-10-12 02:09:17 +00002692 if (PR.isInvalid()) return QualType();
2693 if (PR.take() != V) {
2694 V = PR.take();
John McCall4bc41ae2010-11-18 19:01:18 +00002695 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002696 }
2697
Chris Lattnere267f5d2007-08-26 05:39:26 +00002698 // Reject anything else.
John McCall4bc41ae2010-11-18 19:01:18 +00002699 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002700 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002701 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002702}
2703
2704
Chris Lattnere168f762006-11-10 05:29:30 +00002705
John McCalldadc5752010-08-24 06:29:42 +00002706ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002707Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002708 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002709 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002710 switch (Kind) {
2711 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002712 case tok::plusplus: Opc = UO_PostInc; break;
2713 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002714 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002715
John McCallb268a282010-08-23 23:25:46 +00002716 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002717}
2718
John McCall4bc41ae2010-11-18 19:01:18 +00002719/// Expressions of certain arbitrary types are forbidden by C from
2720/// having l-value type. These are:
2721/// - 'void', but not qualified void
2722/// - function types
2723///
2724/// The exact rule here is C99 6.3.2.1:
2725/// An lvalue is an expression with an object type or an incomplete
2726/// type other than void.
2727static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2728 return ((T->isVoidType() && !T.hasQualifiers()) ||
2729 T->isFunctionType());
2730}
2731
John McCalldadc5752010-08-24 06:29:42 +00002732ExprResult
John McCallb268a282010-08-23 23:25:46 +00002733Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2734 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002735 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002736 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002737 if (Result.isInvalid()) return ExprError();
2738 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002739
John McCallb268a282010-08-23 23:25:46 +00002740 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002741
Douglas Gregor40412ac2008-11-19 17:17:41 +00002742 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002743 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002744 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002745 Context.DependentTy,
2746 VK_LValue, OK_Ordinary,
2747 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002748 }
2749
Mike Stump11289f42009-09-09 15:08:12 +00002750 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002751 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002752 LHSExp->getType()->isEnumeralType() ||
2753 RHSExp->getType()->isRecordType() ||
2754 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002755 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002756 }
2757
John McCallb268a282010-08-23 23:25:46 +00002758 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002759}
2760
2761
John McCalldadc5752010-08-24 06:29:42 +00002762ExprResult
John McCallb268a282010-08-23 23:25:46 +00002763Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2764 Expr *Idx, SourceLocation RLoc) {
2765 Expr *LHSExp = Base;
2766 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002767
Chris Lattner36d572b2007-07-16 00:14:47 +00002768 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002769 if (!LHSExp->getType()->getAs<VectorType>())
2770 DefaultFunctionArrayLvalueConversion(LHSExp);
2771 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002772
Chris Lattner36d572b2007-07-16 00:14:47 +00002773 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00002774 ExprValueKind VK = VK_LValue;
2775 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00002776
Steve Naroffc1aadb12007-03-28 21:49:40 +00002777 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002778 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002779 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002780 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002781 Expr *BaseExpr, *IndexExpr;
2782 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002783 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2784 BaseExpr = LHSExp;
2785 IndexExpr = RHSExp;
2786 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002787 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002788 BaseExpr = LHSExp;
2789 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002790 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002791 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002792 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002793 BaseExpr = RHSExp;
2794 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002795 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002796 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002797 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002798 BaseExpr = LHSExp;
2799 IndexExpr = RHSExp;
2800 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002801 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002802 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002803 // Handle the uncommon case of "123[Ptr]".
2804 BaseExpr = RHSExp;
2805 IndexExpr = LHSExp;
2806 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00002807 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00002808 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00002809 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00002810 VK = LHSExp->getValueKind();
2811 if (VK != VK_RValue)
2812 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00002813
Chris Lattner36d572b2007-07-16 00:14:47 +00002814 // FIXME: need to deal with const...
2815 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002816 } else if (LHSTy->isArrayType()) {
2817 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00002818 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00002819 // wasn't promoted because of the C90 rule that doesn't
2820 // allow promoting non-lvalue arrays. Warn, then
2821 // force the promotion here.
2822 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2823 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002824 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCalle3027922010-08-25 11:45:40 +00002825 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002826 LHSTy = LHSExp->getType();
2827
2828 BaseExpr = LHSExp;
2829 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002830 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002831 } else if (RHSTy->isArrayType()) {
2832 // Same as previous, except for 123[f().a] case
2833 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2834 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002835 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCalle3027922010-08-25 11:45:40 +00002836 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002837 RHSTy = RHSExp->getType();
2838
2839 BaseExpr = RHSExp;
2840 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002841 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00002842 } else {
Chris Lattner003af242009-04-25 22:50:55 +00002843 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2844 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002845 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00002846 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002847 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00002848 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2849 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00002850
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002851 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00002852 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2853 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00002854 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2855
Douglas Gregorac1fb652009-03-24 19:52:54 +00002856 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00002857 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2858 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00002859 // incomplete types are not object types.
2860 if (ResultType->isFunctionType()) {
2861 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2862 << ResultType << BaseExpr->getSourceRange();
2863 return ExprError();
2864 }
Mike Stump11289f42009-09-09 15:08:12 +00002865
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00002866 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
2867 // GNU extension: subscripting on pointer to void
2868 Diag(LLoc, diag::ext_gnu_void_ptr)
2869 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00002870
2871 // C forbids expressions of unqualified void type from being l-values.
2872 // See IsCForbiddenLValueType.
2873 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00002874 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00002875 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00002876 PDiag(diag::err_subscript_incomplete_type)
2877 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00002878 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002879
Chris Lattner62975a72009-04-24 00:30:45 +00002880 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00002881 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00002882 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2883 << ResultType << BaseExpr->getSourceRange();
2884 return ExprError();
2885 }
Mike Stump11289f42009-09-09 15:08:12 +00002886
John McCall4bc41ae2010-11-18 19:01:18 +00002887 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
2888 !IsCForbiddenLValueType(Context, ResultType));
2889
Mike Stump4e1f26a2009-02-19 03:04:26 +00002890 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002891 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00002892}
2893
John McCall4bc41ae2010-11-18 19:01:18 +00002894/// Check an ext-vector component access expression.
2895///
2896/// VK should be set in advance to the value kind of the base
2897/// expression.
2898static QualType
2899CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
2900 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00002901 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00002902 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2903 // see FIXME there.
2904 //
2905 // FIXME: This logic can be greatly simplified by splitting it along
2906 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00002907 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00002908
Steve Narofff8fd09e2007-07-27 22:15:19 +00002909 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002910 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002911
Mike Stump4e1f26a2009-02-19 03:04:26 +00002912 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00002913 // special names that indicate a subset of exactly half the elements are
2914 // to be selected.
2915 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002916
Nate Begemanbb70bf62009-01-18 01:47:54 +00002917 // This flag determines whether or not CompName has an 's' char prefix,
2918 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00002919 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00002920
John McCall4bc41ae2010-11-18 19:01:18 +00002921 bool HasRepeated = false;
2922 bool HasIndex[16] = {};
2923
2924 int Idx;
2925
Nate Begemanf322eab2008-05-09 06:41:27 +00002926 // Check that we've found one of the special components, or that the component
2927 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002928 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00002929 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2930 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00002931 } else if (!HexSwizzle &&
2932 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
2933 do {
2934 if (HasIndex[Idx]) HasRepeated = true;
2935 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00002936 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00002937 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
2938 } else {
2939 if (HexSwizzle) compStr++;
2940 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
2941 if (HasIndex[Idx]) HasRepeated = true;
2942 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00002943 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00002944 }
Chris Lattner7e152db2007-08-02 22:33:49 +00002945 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002946
Mike Stump4e1f26a2009-02-19 03:04:26 +00002947 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002948 // We didn't get to the end of the string. This means the component names
2949 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00002950 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00002951 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002952 return QualType();
2953 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002954
Nate Begemanbb70bf62009-01-18 01:47:54 +00002955 // Ensure no component accessor exceeds the width of the vector type it
2956 // operates on.
2957 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002958 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002959
2960 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002961 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002962
2963 while (*compStr) {
2964 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00002965 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00002966 << baseType << SourceRange(CompLoc);
2967 return QualType();
2968 }
2969 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002970 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002971
Steve Narofff8fd09e2007-07-27 22:15:19 +00002972 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002973 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002974 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002975 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002976 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00002977 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002978 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002979 if (HexSwizzle)
2980 CompSize--;
2981
Steve Narofff8fd09e2007-07-27 22:15:19 +00002982 if (CompSize == 1)
2983 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002984
John McCall4bc41ae2010-11-18 19:01:18 +00002985 if (HasRepeated) VK = VK_RValue;
2986
2987 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002988 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00002989 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00002990 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
2991 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
2992 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00002993 }
2994 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00002995}
2996
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002997static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00002998 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002999 const Selector &Sel,
3000 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003001 if (Member)
3002 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3003 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003004 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003005 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003006
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003007 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3008 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003009 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3010 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003011 return D;
3012 }
3013 return 0;
3014}
3015
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003016static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3017 IdentifierInfo *Member,
3018 const Selector &Sel,
3019 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003020 // Check protocols on qualified interfaces.
3021 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003022 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003023 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003024 if (Member)
3025 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3026 GDecl = PD;
3027 break;
3028 }
3029 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003030 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003031 GDecl = OMD;
3032 break;
3033 }
3034 }
3035 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003036 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003037 E = QIdTy->qual_end(); I != E; ++I) {
3038 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003039 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3040 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003041 if (GDecl)
3042 return GDecl;
3043 }
3044 }
3045 return GDecl;
3046}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003047
John McCalldadc5752010-08-24 06:29:42 +00003048ExprResult
John McCallb268a282010-08-23 23:25:46 +00003049Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003050 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003051 const CXXScopeSpec &SS,
3052 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003053 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003054 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003055 // Even in dependent contexts, try to diagnose base expressions with
3056 // obviously wrong types, e.g.:
3057 //
3058 // T* t;
3059 // t.f;
3060 //
3061 // In Obj-C++, however, the above expression is valid, since it could be
3062 // accessing the 'f' property if T is an Obj-C interface. The extra check
3063 // allows this, while still reporting an error if T is a struct pointer.
3064 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003065 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003066 if (PT && (!getLangOptions().ObjC1 ||
3067 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003068 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003069 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003070 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003071 return ExprError();
3072 }
3073 }
3074
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003075 assert(BaseType->isDependentType() ||
3076 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003077 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003078
3079 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3080 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003081 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003082 IsArrow, OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003083 SS.getScopeRep(),
John McCall10eae182009-11-30 22:42:35 +00003084 SS.getRange(),
3085 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003086 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003087}
3088
3089/// We know that the given qualified member reference points only to
3090/// declarations which do not belong to the static type of the base
3091/// expression. Diagnose the problem.
3092static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3093 Expr *BaseExpr,
3094 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003095 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003096 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00003097 // If this is an implicit member access, use a different set of
3098 // diagnostics.
3099 if (!BaseExpr)
3100 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00003101
John McCall1e67dd62010-04-27 01:43:38 +00003102 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
3103 << SS.getRange() << R.getRepresentativeDecl() << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003104}
3105
3106// Check whether the declarations we found through a nested-name
3107// specifier in a member expression are actually members of the base
3108// type. The restriction here is:
3109//
3110// C++ [expr.ref]p2:
3111// ... In these cases, the id-expression shall name a
3112// member of the class or of one of its base classes.
3113//
3114// So it's perfectly legitimate for the nested-name specifier to name
3115// an unrelated class, and for us to find an overload set including
3116// decls from classes which are not superclasses, as long as the decl
3117// we actually pick through overload resolution is from a superclass.
3118bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3119 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003120 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003121 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003122 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3123 if (!BaseRT) {
3124 // We can't check this yet because the base type is still
3125 // dependent.
3126 assert(BaseType->isDependentType());
3127 return false;
3128 }
3129 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003130
3131 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003132 // If this is an implicit member reference and we find a
3133 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003134 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003135 return false;
John McCall10eae182009-11-30 22:42:35 +00003136
John McCall2d74de92009-12-01 22:10:20 +00003137 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003138 DeclContext *DC = (*I)->getDeclContext();
3139 while (DC->isTransparentContext())
3140 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003141
Douglas Gregora9c3e822010-07-28 22:27:52 +00003142 if (!DC->isRecord())
3143 continue;
3144
John McCall2d74de92009-12-01 22:10:20 +00003145 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003146 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003147
3148 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3149 return false;
3150 }
3151
John McCallcd4b4772009-12-02 03:53:29 +00003152 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00003153 return true;
3154}
3155
3156static bool
3157LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3158 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003159 SourceLocation OpLoc, CXXScopeSpec &SS,
3160 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003161 RecordDecl *RDecl = RTy->getDecl();
3162 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003163 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003164 << BaseRange))
3165 return true;
3166
John McCalle9cccd82010-06-16 08:42:20 +00003167 if (HasTemplateArgs) {
3168 // LookupTemplateName doesn't expect these both to exist simultaneously.
3169 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3170
3171 bool MOUS;
3172 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3173 return false;
3174 }
3175
John McCall2d74de92009-12-01 22:10:20 +00003176 DeclContext *DC = RDecl;
3177 if (SS.isSet()) {
3178 // If the member name was a qualified-id, look into the
3179 // nested-name-specifier.
3180 DC = SemaRef.computeDeclContext(SS, false);
3181
John McCall0b66eb32010-05-01 00:40:08 +00003182 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003183 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3184 << SS.getRange() << DC;
3185 return true;
3186 }
3187
John McCall2d74de92009-12-01 22:10:20 +00003188 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003189
John McCall2d74de92009-12-01 22:10:20 +00003190 if (!isa<TypeDecl>(DC)) {
3191 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3192 << DC << SS.getRange();
3193 return true;
John McCall10eae182009-11-30 22:42:35 +00003194 }
3195 }
3196
John McCall2d74de92009-12-01 22:10:20 +00003197 // The record definition is complete, now look up the member.
3198 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003199
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003200 if (!R.empty())
3201 return false;
3202
3203 // We didn't find anything with the given name, so try to correct
3204 // for typos.
3205 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003206 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003207 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003208 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3209 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3210 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003211 << FixItHint::CreateReplacement(R.getNameLoc(),
3212 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003213 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3214 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3215 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003216 return false;
3217 } else {
3218 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003219 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003220 }
3221
John McCall10eae182009-11-30 22:42:35 +00003222 return false;
3223}
3224
John McCalldadc5752010-08-24 06:29:42 +00003225ExprResult
John McCallb268a282010-08-23 23:25:46 +00003226Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003227 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003228 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003229 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003230 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003231 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003232 if (BaseType->isDependentType() ||
3233 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003234 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003235 IsArrow, OpLoc,
3236 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003237 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003238
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003239 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003240
John McCall2d74de92009-12-01 22:10:20 +00003241 // Implicit member accesses.
3242 if (!Base) {
3243 QualType RecordTy = BaseType;
3244 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3245 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3246 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003247 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003248 return ExprError();
3249
3250 // Explicit member accesses.
3251 } else {
John McCalldadc5752010-08-24 06:29:42 +00003252 ExprResult Result =
John McCall2d74de92009-12-01 22:10:20 +00003253 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003254 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003255
3256 if (Result.isInvalid()) {
3257 Owned(Base);
3258 return ExprError();
3259 }
3260
3261 if (Result.get())
3262 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003263
3264 // LookupMemberExpr can modify Base, and thus change BaseType
3265 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003266 }
3267
John McCallb268a282010-08-23 23:25:46 +00003268 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003269 OpLoc, IsArrow, SS, FirstQualifierInScope,
3270 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003271}
3272
John McCalldadc5752010-08-24 06:29:42 +00003273ExprResult
John McCallb268a282010-08-23 23:25:46 +00003274Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003275 SourceLocation OpLoc, bool IsArrow,
3276 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003277 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003278 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003279 const TemplateArgumentListInfo *TemplateArgs,
3280 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003281 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003282 if (IsArrow) {
3283 assert(BaseType->isPointerType());
3284 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3285 }
John McCalla8ae2222010-04-06 21:38:20 +00003286 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003287
John McCallb268a282010-08-23 23:25:46 +00003288 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003289 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3290 DeclarationName MemberName = MemberNameInfo.getName();
3291 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003292
3293 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003294 return ExprError();
3295
John McCall10eae182009-11-30 22:42:35 +00003296 if (R.empty()) {
3297 // Rederive where we looked up.
3298 DeclContext *DC = (SS.isSet()
3299 ? computeDeclContext(SS, false)
3300 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003301
John McCall10eae182009-11-30 22:42:35 +00003302 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003303 << MemberName << DC
3304 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003305 return ExprError();
3306 }
3307
John McCall38836f02010-01-15 08:34:02 +00003308 // Diagnose lookups that find only declarations from a non-base
3309 // type. This is possible for either qualified lookups (which may
3310 // have been qualified with an unrelated type) or implicit member
3311 // expressions (which were found with unqualified lookup and thus
3312 // may have come from an enclosing scope). Note that it's okay for
3313 // lookup to find declarations from a non-base type as long as those
3314 // aren't the ones picked by overload resolution.
3315 if ((SS.isSet() || !BaseExpr ||
3316 (isa<CXXThisExpr>(BaseExpr) &&
3317 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003318 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003319 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003320 return ExprError();
3321
3322 // Construct an unresolved result if we in fact got an unresolved
3323 // result.
3324 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003325 // Suppress any lookup-related diagnostics; we'll do these when we
3326 // pick a member.
3327 R.suppressDiagnostics();
3328
John McCall10eae182009-11-30 22:42:35 +00003329 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003330 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003331 BaseExpr, BaseExprType,
3332 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003333 Qualifier, SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003334 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003335 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003336
3337 return Owned(MemExpr);
3338 }
3339
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003340 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003341 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003342 NamedDecl *MemberDecl = R.getFoundDecl();
3343
3344 // FIXME: diagnose the presence of template arguments now.
3345
3346 // If the decl being referenced had an error, return an error for this
3347 // sub-expr without emitting another error, in order to avoid cascading
3348 // error cases.
3349 if (MemberDecl->isInvalidDecl())
3350 return ExprError();
3351
John McCall2d74de92009-12-01 22:10:20 +00003352 // Handle the implicit-member-access case.
3353 if (!BaseExpr) {
3354 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003355 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003356 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003357
Douglas Gregorb15af892010-01-07 23:12:05 +00003358 SourceLocation Loc = R.getNameLoc();
3359 if (SS.getRange().isValid())
3360 Loc = SS.getRange().getBegin();
3361 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003362 }
3363
John McCall10eae182009-11-30 22:42:35 +00003364 bool ShouldCheckUse = true;
3365 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3366 // Don't diagnose the use of a virtual member function unless it's
3367 // explicitly qualified.
3368 if (MD->isVirtual() && !SS.isSet())
3369 ShouldCheckUse = false;
3370 }
3371
3372 // Check the use of this member.
3373 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3374 Owned(BaseExpr);
3375 return ExprError();
3376 }
3377
John McCall34376a62010-12-04 03:47:34 +00003378 // Perform a property load on the base regardless of whether we
3379 // actually need it for the declaration.
3380 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3381 ConvertPropertyForRValue(BaseExpr);
3382
John McCallfeb624a2010-11-23 20:48:44 +00003383 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3384 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3385 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003386
Francois Pichet783dd6e2010-11-21 06:08:52 +00003387 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3388 // We may have found a field within an anonymous union or struct
3389 // (C++ [class.union]).
3390 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00003391 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003392
John McCall10eae182009-11-30 22:42:35 +00003393 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3394 MarkDeclarationReferenced(MemberLoc, Var);
3395 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003396 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003397 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003398 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003399 }
3400
John McCall7decc9e2010-11-18 06:31:45 +00003401 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall10eae182009-11-30 22:42:35 +00003402 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3403 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003404 MemberFn, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003405 MemberFn->getType(),
3406 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3407 OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003408 }
John McCall7decc9e2010-11-18 06:31:45 +00003409 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003410
3411 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3412 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3413 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003414 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003415 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003416 }
3417
3418 Owned(BaseExpr);
3419
Douglas Gregor861eb802010-04-25 20:55:08 +00003420 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003421 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003422 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003423 << MemberName << BaseType << int(IsArrow);
3424 else
3425 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3426 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003427
Douglas Gregor861eb802010-04-25 20:55:08 +00003428 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3429 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003430 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003431 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003432}
3433
3434/// Look up the given member of the given non-type-dependent
3435/// expression. This can return in one of two ways:
3436/// * If it returns a sentinel null-but-valid result, the caller will
3437/// assume that lookup was performed and the results written into
3438/// the provided structure. It will take over from there.
3439/// * Otherwise, the returned expression will be produced in place of
3440/// an ordinary member expression.
3441///
3442/// The ObjCImpDecl bit is a gross hack that will need to be properly
3443/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00003444ExprResult
John McCall10eae182009-11-30 22:42:35 +00003445Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00003446 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003447 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00003448 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003449 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00003450
Steve Naroffeaaae462007-12-16 21:42:28 +00003451 // Perform default conversions.
3452 DefaultFunctionArrayConversion(BaseExpr);
John McCall15317a22010-12-15 04:42:30 +00003453 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003454
Steve Naroff185616f2007-07-26 03:11:44 +00003455 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00003456 assert(!BaseType->isDependentType());
3457
3458 DeclarationName MemberName = R.getLookupName();
3459 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00003460
3461 // If the user is trying to apply -> or . to a function pointer
John McCall10eae182009-11-30 22:42:35 +00003462 // type, it's probably because they forgot parentheses to call that
Douglas Gregord82ae382009-11-06 06:30:47 +00003463 // function. Suggest the addition of those parentheses, build the
3464 // call, and continue on.
3465 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
3466 if (const FunctionProtoType *Fun
3467 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
3468 QualType ResultTy = Fun->getResultType();
3469 if (Fun->getNumArgs() == 0 &&
John McCall10eae182009-11-30 22:42:35 +00003470 ((!IsArrow && ResultTy->isRecordType()) ||
3471 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregord82ae382009-11-06 06:30:47 +00003472 ResultTy->getAs<PointerType>()->getPointeeType()
3473 ->isRecordType()))) {
3474 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
Nick Lewyckyc60d6e72010-10-15 21:43:24 +00003475 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
Douglas Gregord82ae382009-11-06 06:30:47 +00003476 << QualType(Fun, 0)
Douglas Gregora771f462010-03-31 17:46:05 +00003477 << FixItHint::CreateInsertion(Loc, "()");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003478
John McCalldadc5752010-08-24 06:29:42 +00003479 ExprResult NewBase
Douglas Gregorce5aa332010-09-09 16:33:13 +00003480 = ActOnCallExpr(0, BaseExpr, Loc, MultiExprArg(*this, 0, 0), Loc);
Douglas Gregor143d3672010-06-21 22:46:46 +00003481 BaseExpr = 0;
Douglas Gregord82ae382009-11-06 06:30:47 +00003482 if (NewBase.isInvalid())
John McCall10eae182009-11-30 22:42:35 +00003483 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003484
Douglas Gregord82ae382009-11-06 06:30:47 +00003485 BaseExpr = NewBase.takeAs<Expr>();
3486 DefaultFunctionArrayConversion(BaseExpr);
3487 BaseType = BaseExpr->getType();
3488 }
3489 }
3490 }
3491
David Chisnall9f57c292009-08-17 16:35:33 +00003492 // If this is an Objective-C pseudo-builtin and a definition is provided then
3493 // use that.
3494 if (BaseType->isObjCIdType()) {
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00003495 if (IsArrow) {
3496 // Handle the following exceptional case PObj->isa.
3497 if (const ObjCObjectPointerType *OPT =
3498 BaseType->getAs<ObjCObjectPointerType>()) {
John McCall8b07ec22010-05-15 11:32:37 +00003499 if (OPT->getObjectType()->isObjCId() &&
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00003500 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00003501 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
3502 Context.getObjCClassType()));
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00003503 }
3504 }
David Chisnall9f57c292009-08-17 16:35:33 +00003505 // We have an 'id' type. Rather than fall through, we check if this
3506 // is a reference to 'isa'.
3507 if (BaseType != Context.ObjCIdRedefinitionType) {
3508 BaseType = Context.ObjCIdRedefinitionType;
John McCalle3027922010-08-25 11:45:40 +00003509 ImpCastExprToType(BaseExpr, BaseType, CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003510 }
David Chisnall9f57c292009-08-17 16:35:33 +00003511 }
John McCall10eae182009-11-30 22:42:35 +00003512
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00003513 // If this is an Objective-C pseudo-builtin and a definition is provided then
3514 // use that.
3515 if (Context.isObjCSelType(BaseType)) {
3516 // We have an 'SEL' type. Rather than fall through, we check if this
3517 // is a reference to 'sel_id'.
3518 if (BaseType != Context.ObjCSelRedefinitionType) {
3519 BaseType = Context.ObjCSelRedefinitionType;
John McCalle3027922010-08-25 11:45:40 +00003520 ImpCastExprToType(BaseExpr, BaseType, CK_BitCast);
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00003521 }
3522 }
John McCall10eae182009-11-30 22:42:35 +00003523
Steve Naroff185616f2007-07-26 03:11:44 +00003524 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003525
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003526 // Handle properties on ObjC 'Class' types.
John McCall10eae182009-11-30 22:42:35 +00003527 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003528 // Also must look for a getter name which uses property syntax.
3529 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3530 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3531 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3532 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3533 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003534 if ((Getter = IFace->lookupClassMethod(Sel))) {
3535 // Check the use of this method.
3536 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3537 return ExprError();
3538 }
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003539 else
3540 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003541 // If we found a getter then this may be a valid dot-reference, we
3542 // will look for the matching setter, in case it is needed.
3543 Selector SetterSel =
3544 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3545 PP.getSelectorTable(), Member);
3546 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3547 if (!Setter) {
3548 // If this reference is in an @implementation, also check for 'private'
3549 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003550 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003551 }
3552 // Look through local category implementations associated with the class.
3553 if (!Setter)
3554 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003555
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003556 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3557 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003558
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003559 if (Getter || Setter) {
3560 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003561
John McCall4bc41ae2010-11-18 19:01:18 +00003562 ExprValueKind VK = VK_LValue;
3563 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00003564 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00003565 if (!getLangOptions().CPlusPlus &&
3566 IsCForbiddenLValueType(Context, PType))
3567 VK = VK_RValue;
3568 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003569 // Get the expression type from Setter's incoming parameter.
3570 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00003571 }
3572 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3573
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003574 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00003575 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3576 PType, VK, OK,
3577 MemberLoc, BaseExpr));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003578 }
3579 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3580 << MemberName << BaseType);
3581 }
3582 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003583
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003584 if (BaseType->isObjCClassType() &&
3585 BaseType != Context.ObjCClassRedefinitionType) {
3586 BaseType = Context.ObjCClassRedefinitionType;
John McCalle3027922010-08-25 11:45:40 +00003587 ImpCastExprToType(BaseExpr, BaseType, CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003588 }
Mike Stump11289f42009-09-09 15:08:12 +00003589
John McCall10eae182009-11-30 22:42:35 +00003590 if (IsArrow) {
3591 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00003592 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00003593 else if (BaseType->isObjCObjectPointerType())
3594 ;
John McCalla928c652009-12-07 22:46:59 +00003595 else if (BaseType->isRecordType()) {
3596 // Recover from arrow accesses to records, e.g.:
3597 // struct MyRecord foo;
3598 // foo->bar
3599 // This is actually well-formed in C++ if MyRecord has an
3600 // overloaded operator->, but that should have been dealt with
3601 // by now.
3602 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3603 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003604 << FixItHint::CreateReplacement(OpLoc, ".");
John McCalla928c652009-12-07 22:46:59 +00003605 IsArrow = false;
3606 } else {
John McCall10eae182009-11-30 22:42:35 +00003607 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3608 << BaseType << BaseExpr->getSourceRange();
3609 return ExprError();
Anders Carlsson524d5a42009-05-16 20:31:20 +00003610 }
John McCalla928c652009-12-07 22:46:59 +00003611 } else {
3612 // Recover from dot accesses to pointers, e.g.:
3613 // type *foo;
3614 // foo.bar
3615 // This is actually well-formed in two cases:
3616 // - 'type' is an Objective C type
3617 // - 'bar' is a pseudo-destructor name which happens to refer to
3618 // the appropriate pointer type
3619 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3620 const PointerType *PT = BaseType->getAs<PointerType>();
3621 if (PT && PT->getPointeeType()->isRecordType()) {
3622 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3623 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003624 << FixItHint::CreateReplacement(OpLoc, "->");
John McCalla928c652009-12-07 22:46:59 +00003625 BaseType = PT->getPointeeType();
3626 IsArrow = true;
3627 }
3628 }
John McCall10eae182009-11-30 22:42:35 +00003629 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003630
John McCall8b07ec22010-05-15 11:32:37 +00003631 // Handle field access to simple records.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003632 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCall2d74de92009-12-01 22:10:20 +00003633 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
John McCalle9cccd82010-06-16 08:42:20 +00003634 RTy, OpLoc, SS, HasTemplateArgs))
Douglas Gregordd430f72009-01-19 19:26:10 +00003635 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003636 return Owned((Expr*) 0);
Chris Lattnerb63a7452008-07-21 04:28:12 +00003637 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003638
Chris Lattnerdc420f42008-07-21 04:59:05 +00003639 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
3640 // (*Obj).ivar.
John McCall10eae182009-11-30 22:42:35 +00003641 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00003642 (!IsArrow && BaseType->isObjCObjectType())) {
John McCall9dd450b2009-09-21 23:43:11 +00003643 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
John McCall8b07ec22010-05-15 11:32:37 +00003644 ObjCInterfaceDecl *IDecl =
3645 OPT ? OPT->getInterfaceDecl()
3646 : BaseType->getAs<ObjCObjectType>()->getInterface();
3647 if (IDecl) {
Anders Carlssonf571c112009-08-26 18:25:21 +00003648 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3649
Steve Naroffa057ba92009-07-16 00:25:06 +00003650 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00003651 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00003652
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003653 if (!IV) {
3654 // Attempt to correct for typos in ivar names.
3655 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3656 LookupMemberName);
Douglas Gregord507d772010-10-20 03:06:34 +00003657 if (CorrectTypo(Res, 0, 0, IDecl, false,
3658 IsArrow? CTC_ObjCIvarLookup
3659 : CTC_ObjCPropertyLookup) &&
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003660 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003661 Diag(R.getNameLoc(),
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003662 diag::err_typecheck_member_reference_ivar_suggest)
3663 << IDecl->getDeclName() << MemberName << IV->getDeclName()
Douglas Gregora771f462010-03-31 17:46:05 +00003664 << FixItHint::CreateReplacement(R.getNameLoc(),
3665 IV->getNameAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003666 Diag(IV->getLocation(), diag::note_previous_decl)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003667 << IV->getDeclName();
Douglas Gregorc048c522010-06-29 19:27:42 +00003668 } else {
3669 Res.clear();
3670 Res.setLookupName(Member);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003671 }
3672 }
3673
Steve Naroffa057ba92009-07-16 00:25:06 +00003674 if (IV) {
3675 // If the decl being referenced had an error, return an error for this
3676 // sub-expr without emitting another error, in order to avoid cascading
3677 // error cases.
3678 if (IV->isInvalidDecl())
3679 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003680
Steve Naroffa057ba92009-07-16 00:25:06 +00003681 // Check whether we can reference this field.
3682 if (DiagnoseUseOfDecl(IV, MemberLoc))
3683 return ExprError();
3684 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3685 IV->getAccessControl() != ObjCIvarDecl::Package) {
3686 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3687 if (ObjCMethodDecl *MD = getCurMethodDecl())
3688 ClassOfMethodDecl = MD->getClassInterface();
3689 else if (ObjCImpDecl && getCurFunctionDecl()) {
3690 // Case of a c-function declared inside an objc implementation.
3691 // FIXME: For a c-style function nested inside an objc implementation
3692 // class, there is no implementation context available, so we pass
3693 // down the context as argument to this routine. Ideally, this context
3694 // need be passed down in the AST node and somehow calculated from the
3695 // AST for a function decl.
Mike Stump11289f42009-09-09 15:08:12 +00003696 if (ObjCImplementationDecl *IMPD =
John McCall48871652010-08-21 09:40:31 +00003697 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
Steve Naroffa057ba92009-07-16 00:25:06 +00003698 ClassOfMethodDecl = IMPD->getClassInterface();
3699 else if (ObjCCategoryImplDecl* CatImplClass =
John McCall48871652010-08-21 09:40:31 +00003700 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
Steve Naroffa057ba92009-07-16 00:25:06 +00003701 ClassOfMethodDecl = CatImplClass->getClassInterface();
3702 }
Mike Stump11289f42009-09-09 15:08:12 +00003703
3704 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3705 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00003706 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00003707 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00003708 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00003709 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3710 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00003711 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00003712 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00003713 }
Steve Naroffa057ba92009-07-16 00:25:06 +00003714
John McCall27584242010-12-06 20:48:59 +00003715 if (IsArrow) DefaultLvalueConversion(BaseExpr);
3716
Steve Naroffa057ba92009-07-16 00:25:06 +00003717 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3718 MemberLoc, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00003719 IsArrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00003720 }
Steve Naroffa057ba92009-07-16 00:25:06 +00003721 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00003722 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00003723 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00003724 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00003725 }
Steve Naroff1329fa02009-07-15 18:40:39 +00003726 // Handle properties on 'id' and qualified "id".
John McCall10eae182009-11-30 22:42:35 +00003727 if (!IsArrow && (BaseType->isObjCIdType() ||
3728 BaseType->isObjCQualifiedIdType())) {
John McCall34376a62010-12-04 03:47:34 +00003729 // This actually uses the base as an r-value.
John McCall27584242010-12-06 20:48:59 +00003730 DefaultLvalueConversion(BaseExpr);
John McCall34376a62010-12-04 03:47:34 +00003731 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3732
John McCall9dd450b2009-09-21 23:43:11 +00003733 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00003734 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003735
Steve Naroff7cae42b2009-07-10 23:34:53 +00003736 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00003737 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003738 if (Decl *PMDecl = FindGetterSetterNameDecl(QIdTy, Member, Sel,
3739 Context)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003740 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3741 // Check the use of this declaration
3742 if (DiagnoseUseOfDecl(PD, MemberLoc))
3743 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003744
Steve Naroff7cae42b2009-07-10 23:34:53 +00003745 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00003746 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00003747 MemberLoc,
3748 BaseExpr));
Steve Naroff7cae42b2009-07-10 23:34:53 +00003749 }
3750 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3751 // Check the use of this method.
3752 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3753 return ExprError();
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003754 Selector SetterSel =
3755 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3756 PP.getSelectorTable(), Member);
3757 ObjCMethodDecl *SMD = 0;
3758 if (Decl *SDecl = FindGetterSetterNameDecl(QIdTy, /*Property id*/0,
3759 SetterSel, Context))
3760 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3761 QualType PType = OMD->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00003762
3763 ExprValueKind VK = VK_LValue;
3764 if (!getLangOptions().CPlusPlus &&
3765 IsCForbiddenLValueType(Context, PType))
3766 VK = VK_RValue;
3767 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3768
John McCallb7bd14f2010-12-02 01:19:52 +00003769 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType, VK, OK,
3770 MemberLoc, BaseExpr));
Steve Naroff7cae42b2009-07-10 23:34:53 +00003771 }
3772 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003773
Steve Naroff7cae42b2009-07-10 23:34:53 +00003774 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00003775 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003776 }
Alexis Huntc46382e2010-04-28 23:02:27 +00003777
Chris Lattnerdc420f42008-07-21 04:59:05 +00003778 // Handle Objective-C property access, which is "Obj.property" where Obj is a
3779 // pointer to a (potentially qualified) interface type.
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00003780 if (!IsArrow)
3781 if (const ObjCObjectPointerType *OPT =
John McCall34376a62010-12-04 03:47:34 +00003782 BaseType->getAsObjCInterfacePointerType()) {
3783 // This actually uses the base as an r-value.
John McCall27584242010-12-06 20:48:59 +00003784 DefaultLvalueConversion(BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00003785 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3786 SourceLocation(), QualType(), false);
John McCall34376a62010-12-04 03:47:34 +00003787 }
Mike Stump11289f42009-09-09 15:08:12 +00003788
Steve Naroffe87026a2009-07-24 17:54:45 +00003789 // Handle the following exceptional case (*Obj).isa.
John McCall10eae182009-11-30 22:42:35 +00003790 if (!IsArrow &&
John McCall8b07ec22010-05-15 11:32:37 +00003791 BaseType->isObjCObjectType() &&
3792 BaseType->getAs<ObjCObjectType>()->isObjCId() &&
Anders Carlssonf571c112009-08-26 18:25:21 +00003793 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00003794 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00003795 Context.getObjCClassType()));
Steve Naroffe87026a2009-07-24 17:54:45 +00003796
Chris Lattnerb63a7452008-07-21 04:28:12 +00003797 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003798 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00003799 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00003800 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall15317a22010-12-15 04:42:30 +00003801 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00003802 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3803 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00003804 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003805 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00003806
3807 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3808 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003809 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003810
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003811 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3812 << BaseType << BaseExpr->getSourceRange();
3813
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003814 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00003815}
3816
John McCall10eae182009-11-30 22:42:35 +00003817/// The main callback when the parser finds something like
3818/// expression . [nested-name-specifier] identifier
3819/// expression -> [nested-name-specifier] identifier
3820/// where 'identifier' encompasses a fairly broad spectrum of
3821/// possibilities, including destructor and operator references.
3822///
3823/// \param OpKind either tok::arrow or tok::period
3824/// \param HasTrailingLParen whether the next token is '(', which
3825/// is used to diagnose mis-uses of special members that can
3826/// only be called
3827/// \param ObjCImpDecl the current ObjC @implementation decl;
3828/// this is an ugly hack around the fact that ObjC @implementations
3829/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00003830ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00003831 SourceLocation OpLoc,
3832 tok::TokenKind OpKind,
3833 CXXScopeSpec &SS,
3834 UnqualifiedId &Id,
3835 Decl *ObjCImpDecl,
3836 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00003837 if (SS.isSet() && SS.isInvalid())
3838 return ExprError();
3839
3840 TemplateArgumentListInfo TemplateArgsBuffer;
3841
3842 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003843 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00003844 const TemplateArgumentListInfo *TemplateArgs;
3845 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003846 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003847
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003848 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00003849 bool IsArrow = (OpKind == tok::arrow);
3850
3851 NamedDecl *FirstQualifierInScope
3852 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3853 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3854
3855 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003856 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003857 if (Result.isInvalid()) return ExprError();
3858 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00003859
Douglas Gregor41f90302010-04-12 20:54:26 +00003860 if (Base->getType()->isDependentType() || Name.isDependentName() ||
3861 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00003862 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00003863 IsArrow, OpLoc,
3864 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003865 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003866 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003867 LookupResult R(*this, NameInfo, LookupMemberName);
John McCalle9cccd82010-06-16 08:42:20 +00003868 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3869 SS, ObjCImpDecl, TemplateArgs != 0);
Alexis Huntc46382e2010-04-28 23:02:27 +00003870
John McCalle9cccd82010-06-16 08:42:20 +00003871 if (Result.isInvalid()) {
3872 Owned(Base);
3873 return ExprError();
3874 }
John McCall10eae182009-11-30 22:42:35 +00003875
John McCalle9cccd82010-06-16 08:42:20 +00003876 if (Result.get()) {
3877 // The only way a reference to a destructor can be used is to
3878 // immediately call it, which falls into this case. If the
3879 // next token is not a '(', produce a diagnostic and build the
3880 // call now.
3881 if (!HasTrailingLParen &&
3882 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00003883 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00003884
John McCalle9cccd82010-06-16 08:42:20 +00003885 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00003886 }
3887
John McCallb268a282010-08-23 23:25:46 +00003888 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00003889 OpLoc, IsArrow, SS, FirstQualifierInScope,
3890 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003891 }
3892
3893 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003894}
3895
John McCalldadc5752010-08-24 06:29:42 +00003896ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003897 FunctionDecl *FD,
3898 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003899 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003900 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003901 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003902 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003903 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003904 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003905 return ExprError();
3906 }
3907
3908 if (Param->hasUninstantiatedDefaultArg()) {
3909 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003910
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003911 // Instantiate the expression.
3912 MultiLevelTemplateArgumentList ArgList
3913 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003914
Nico Weber44887f62010-11-29 18:19:25 +00003915 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003916 = ArgList.getInnermost();
3917 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3918 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003919
Nico Weber44887f62010-11-29 18:19:25 +00003920 ExprResult Result;
3921 {
3922 // C++ [dcl.fct.default]p5:
3923 // The names in the [default argument] expression are bound, and
3924 // the semantic constraints are checked, at the point where the
3925 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003926 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003927 Result = SubstExpr(UninstExpr, ArgList);
3928 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003929 if (Result.isInvalid())
3930 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003931
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003932 // Check the expression as an initializer for the parameter.
3933 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003934 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003935 InitializationKind Kind
3936 = InitializationKind::CreateCopy(Param->getLocation(),
3937 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3938 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003939
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003940 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3941 Result = InitSeq.Perform(*this, Entity, Kind,
3942 MultiExprArg(*this, &ResultE, 1));
3943 if (Result.isInvalid())
3944 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003945
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003946 // Build the default argument expression.
3947 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3948 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003949 }
3950
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003951 // If the default expression creates temporaries, we need to
3952 // push them to the current stack of expression temporaries so they'll
3953 // be properly destroyed.
3954 // FIXME: We should really be rebuilding the default argument with new
3955 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003956 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3957 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3958 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3959 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3960 ExprTemporaries.push_back(Temporary);
3961 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003962
3963 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003964 // Just mark all of the declarations in this potentially-evaluated expression
3965 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003966 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003967 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003968}
3969
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003970/// ConvertArgumentsForCall - Converts the arguments specified in
3971/// Args/NumArgs to the parameter types of the function FDecl with
3972/// function prototype Proto. Call is the call expression itself, and
3973/// Fn is the function expression. For a C++ member function, this
3974/// routine does not attempt to convert the object argument. Returns
3975/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003976bool
3977Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003978 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003979 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003980 Expr **Args, unsigned NumArgs,
3981 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003982 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003983 // assignment, to the types of the corresponding parameter, ...
3984 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003985 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003986
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003987 // If too few arguments are available (and we don't have default
3988 // arguments for the remaining parameters), don't make the call.
3989 if (NumArgs < NumArgsInProto) {
3990 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3991 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003992 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003993 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003994 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003995 }
3996
3997 // If too many are passed and not variadic, error on the extras and drop
3998 // them.
3999 if (NumArgs > NumArgsInProto) {
4000 if (!Proto->isVariadic()) {
4001 Diag(Args[NumArgsInProto]->getLocStart(),
4002 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004003 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004004 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004005 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4006 Args[NumArgs-1]->getLocEnd());
4007 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004008 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004009 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004010 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004011 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004012 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004013 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004014 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4015 if (Fn->getType()->isBlockPointerType())
4016 CallType = VariadicBlock; // Block
4017 else if (isa<MemberExpr>(Fn))
4018 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004019 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004020 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004021 if (Invalid)
4022 return true;
4023 unsigned TotalNumArgs = AllArgs.size();
4024 for (unsigned i = 0; i < TotalNumArgs; ++i)
4025 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004026
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004027 return false;
4028}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004029
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004030bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4031 FunctionDecl *FDecl,
4032 const FunctionProtoType *Proto,
4033 unsigned FirstProtoArg,
4034 Expr **Args, unsigned NumArgs,
4035 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004036 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004037 unsigned NumArgsInProto = Proto->getNumArgs();
4038 unsigned NumArgsToCheck = NumArgs;
4039 bool Invalid = false;
4040 if (NumArgs != NumArgsInProto)
4041 // Use default arguments for missing arguments
4042 NumArgsToCheck = NumArgsInProto;
4043 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004044 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004045 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004046 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004047
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004048 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004049 if (ArgIx < NumArgs) {
4050 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004051
Eli Friedman3164fb12009-03-22 22:00:50 +00004052 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4053 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004054 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004055 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004056 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004057
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004058 // Pass the argument
4059 ParmVarDecl *Param = 0;
4060 if (FDecl && i < FDecl->getNumParams())
4061 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004062
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004063 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004064 Param? InitializedEntity::InitializeParameter(Context, Param)
4065 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004066 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004067 SourceLocation(),
4068 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004069 if (ArgE.isInvalid())
4070 return true;
4071
4072 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004073 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004074 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004075
John McCalldadc5752010-08-24 06:29:42 +00004076 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004077 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004078 if (ArgExpr.isInvalid())
4079 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004080
Anders Carlsson355933d2009-08-25 03:49:14 +00004081 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004082 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004083 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004084 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004085
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004086 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004087 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004088 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004089 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004090 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004091 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004092 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004093 }
4094 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004095 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004096}
4097
Steve Naroff83895f72007-09-16 03:34:24 +00004098/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004099/// This provides the location of the left/right parens and a list of comma
4100/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004101ExprResult
John McCallb268a282010-08-23 23:25:46 +00004102Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004103 MultiExprArg args, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004104 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004105
4106 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004107 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004108 if (Result.isInvalid()) return ExprError();
4109 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004110
John McCallb268a282010-08-23 23:25:46 +00004111 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004112
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004113 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004114 // If this is a pseudo-destructor expression, build the call immediately.
4115 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4116 if (NumArgs > 0) {
4117 // Pseudo-destructor calls should not have any arguments.
4118 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004119 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004120 SourceRange(Args[0]->getLocStart(),
4121 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004122
Douglas Gregorad8a3362009-09-04 17:36:40 +00004123 NumArgs = 0;
4124 }
Mike Stump11289f42009-09-09 15:08:12 +00004125
Douglas Gregorad8a3362009-09-04 17:36:40 +00004126 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004127 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004128 }
Mike Stump11289f42009-09-09 15:08:12 +00004129
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004130 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004131 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004132 // FIXME: Will need to cache the results of name lookup (including ADL) in
4133 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004134 bool Dependent = false;
4135 if (Fn->isTypeDependent())
4136 Dependent = true;
4137 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4138 Dependent = true;
4139
4140 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004141 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00004142 Context.DependentTy, VK_RValue,
4143 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004144
4145 // Determine whether this is a call to an object (C++ [over.call.object]).
4146 if (Fn->getType()->isRecordType())
4147 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004148 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004149
John McCall10eae182009-11-30 22:42:35 +00004150 Expr *NakedFn = Fn->IgnoreParens();
4151
4152 // Determine whether this is a call to an unresolved member function.
4153 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4154 // If lookup was unresolved but not dependent (i.e. didn't find
4155 // an unresolved using declaration), it has to be an overloaded
4156 // function set, which means it must contain either multiple
4157 // declarations (all methods or method templates) or a single
4158 // method template.
4159 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00004160 isa<FunctionTemplateDecl>(
4161 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00004162 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00004163
John McCall2d74de92009-12-01 22:10:20 +00004164 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004165 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004166 }
4167
Douglas Gregore254f902009-02-04 00:32:51 +00004168 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00004169 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004170 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00004171 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00004172 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004173 RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004174 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004175
Anders Carlsson61914b52009-10-03 17:40:22 +00004176 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00004177 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCalle3027922010-08-25 11:45:40 +00004178 if (BO->getOpcode() == BO_PtrMemD ||
4179 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00004180 if (const FunctionProtoType *FPT
4181 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004182 QualType ResultTy = FPT->getCallResultType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004183 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004184
John McCallb268a282010-08-23 23:25:46 +00004185 CXXMemberCallExpr *TheCall
Abramo Bagnara21e9d862010-12-03 21:39:42 +00004186 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCall7decc9e2010-11-18 06:31:45 +00004187 NumArgs, ResultTy, VK,
John McCallb268a282010-08-23 23:25:46 +00004188 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004189
4190 if (CheckCallReturnType(FPT->getResultType(),
4191 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00004192 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004193 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00004194
John McCallb268a282010-08-23 23:25:46 +00004195 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004196 RParenLoc))
4197 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00004198
John McCallb268a282010-08-23 23:25:46 +00004199 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004200 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004201 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004202 diag::err_typecheck_call_not_function)
4203 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00004204 }
4205 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004206 }
4207
Douglas Gregore254f902009-02-04 00:32:51 +00004208 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004209 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00004210 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004211
Eli Friedmane14b1992009-12-26 03:35:45 +00004212 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004213 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4214 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4215 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4216 RParenLoc);
4217 }
4218
John McCall57500772009-12-16 12:17:52 +00004219 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004220 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4221 if (UnOp->getOpcode() == UO_AddrOf)
4222 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4223
John McCall57500772009-12-16 12:17:52 +00004224 if (isa<DeclRefExpr>(NakedFn))
4225 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4226
John McCall2d74de92009-12-01 22:10:20 +00004227 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
4228}
4229
John McCall57500772009-12-16 12:17:52 +00004230/// BuildResolvedCallExpr - Build a call to a resolved expression,
4231/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004232/// unary-convert to an expression of function-pointer or
4233/// block-pointer type.
4234///
4235/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004236ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004237Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4238 SourceLocation LParenLoc,
4239 Expr **Args, unsigned NumArgs,
4240 SourceLocation RParenLoc) {
4241 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4242
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004243 // Promote the function operand.
4244 UsualUnaryConversions(Fn);
4245
Chris Lattner08464942007-12-28 05:29:59 +00004246 // Make the call expr early, before semantic checks. This guarantees cleanup
4247 // of arguments and function on error.
John McCallb268a282010-08-23 23:25:46 +00004248 CallExpr *TheCall = new (Context) CallExpr(Context, Fn,
4249 Args, NumArgs,
4250 Context.BoolTy,
John McCall7decc9e2010-11-18 06:31:45 +00004251 VK_RValue,
John McCallb268a282010-08-23 23:25:46 +00004252 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004253
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004254 const FunctionType *FuncT;
4255 if (!Fn->getType()->isBlockPointerType()) {
4256 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4257 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004258 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004259 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004260 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4261 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00004262 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004263 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004264 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00004265 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004266 }
Chris Lattner08464942007-12-28 05:29:59 +00004267 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004268 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4269 << Fn->getType() << Fn->getSourceRange());
4270
Eli Friedman3164fb12009-03-22 22:00:50 +00004271 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004272 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00004273 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004274 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004275 return ExprError();
4276
Chris Lattner08464942007-12-28 05:29:59 +00004277 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004278 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004279 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004280
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004281 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00004282 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004283 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004284 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004285 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004286 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004287
Douglas Gregord8e97de2009-04-02 15:37:10 +00004288 if (FDecl) {
4289 // Check if we have too few/too many template arguments, based
4290 // on our knowledge of the function definition.
4291 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004292 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004293 const FunctionProtoType *Proto
4294 = Def->getType()->getAs<FunctionProtoType>();
4295 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004296 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4297 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004298 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004299
4300 // If the function we're calling isn't a function prototype, but we have
4301 // a function prototype from a prior declaratiom, use that prototype.
4302 if (!FDecl->hasPrototype())
4303 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004304 }
4305
Steve Naroff0b661582007-08-28 23:30:39 +00004306 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004307 for (unsigned i = 0; i != NumArgs; i++) {
4308 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004309
4310 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004311 InitializedEntity Entity
4312 = InitializedEntity::InitializeParameter(Context,
4313 Proto->getArgType(i));
4314 ExprResult ArgE = PerformCopyInitialization(Entity,
4315 SourceLocation(),
4316 Owned(Arg));
4317 if (ArgE.isInvalid())
4318 return true;
4319
4320 Arg = ArgE.takeAs<Expr>();
4321
4322 } else {
4323 DefaultArgumentPromotion(Arg);
Douglas Gregor8e09a722010-10-25 20:39:23 +00004324 }
4325
Douglas Gregor83025412010-10-26 05:45:40 +00004326 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4327 Arg->getType(),
4328 PDiag(diag::err_call_incomplete_argument)
4329 << Arg->getSourceRange()))
4330 return ExprError();
4331
Chris Lattner08464942007-12-28 05:29:59 +00004332 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004333 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004334 }
Chris Lattner08464942007-12-28 05:29:59 +00004335
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004336 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4337 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004338 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4339 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004340
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004341 // Check for sentinels
4342 if (NDecl)
4343 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004344
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004345 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004346 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00004347 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004348 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004349
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004350 if (unsigned BuiltinID = FDecl->getBuiltinID())
4351 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004352 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00004353 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004354 return ExprError();
4355 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004356
John McCallb268a282010-08-23 23:25:46 +00004357 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004358}
4359
John McCalldadc5752010-08-24 06:29:42 +00004360ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004361Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004362 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004363 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004364 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004365 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004366
4367 TypeSourceInfo *TInfo;
4368 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4369 if (!TInfo)
4370 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4371
John McCallb268a282010-08-23 23:25:46 +00004372 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004373}
4374
John McCalldadc5752010-08-24 06:29:42 +00004375ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004376Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00004377 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004378 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004379
Eli Friedman37a186d2008-05-20 05:22:08 +00004380 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004381 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4382 PDiag(diag::err_illegal_decl_array_incomplete_type)
4383 << SourceRange(LParenLoc,
4384 literalExpr->getSourceRange().getEnd())))
4385 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004386 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004387 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4388 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004389 } else if (!literalType->isDependentType() &&
4390 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00004391 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00004392 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00004393 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004394 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004395
Douglas Gregor85dabae2009-12-16 01:38:02 +00004396 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004397 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004398 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004399 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004400 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004401 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004402 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004403 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004404 &literalType);
4405 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004406 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004407 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004408
Chris Lattner79413952008-12-04 23:50:19 +00004409 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004410 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00004411 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004412 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004413 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004414
John McCall7decc9e2010-11-18 06:31:45 +00004415 // In C, compound literals are l-values for some reason.
4416 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4417
John McCall5d7aa7f2010-01-19 22:33:45 +00004418 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00004419 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004420}
4421
John McCalldadc5752010-08-24 06:29:42 +00004422ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00004423Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004424 SourceLocation RBraceLoc) {
4425 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00004426 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004427
Steve Naroff30d242c2007-09-15 18:49:24 +00004428 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004429 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004430
Ted Kremenekac034612010-04-13 23:39:13 +00004431 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4432 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004433 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004434 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004435}
4436
John McCalld7646252010-11-14 08:17:51 +00004437/// Prepares for a scalar cast, performing all the necessary stages
4438/// except the final cast and returning the kind required.
4439static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4440 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4441 // Also, callers should have filtered out the invalid cases with
4442 // pointers. Everything else should be possible.
4443
John McCalle84af4e2010-11-13 01:35:44 +00004444 QualType SrcTy = Src->getType();
John McCalld7646252010-11-14 08:17:51 +00004445 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004446 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004447
John McCall8cb679e2010-11-15 09:13:47 +00004448 switch (SrcTy->getScalarTypeKind()) {
4449 case Type::STK_MemberPointer:
4450 llvm_unreachable("member pointer type in C");
4451
4452 case Type::STK_Pointer:
4453 switch (DestTy->getScalarTypeKind()) {
4454 case Type::STK_Pointer:
4455 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00004456 CK_AnyPointerToObjCPointerCast :
4457 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00004458 case Type::STK_Bool:
4459 return CK_PointerToBoolean;
4460 case Type::STK_Integral:
4461 return CK_PointerToIntegral;
4462 case Type::STK_Floating:
4463 case Type::STK_FloatingComplex:
4464 case Type::STK_IntegralComplex:
4465 case Type::STK_MemberPointer:
4466 llvm_unreachable("illegal cast from pointer");
4467 }
4468 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004469
John McCall8cb679e2010-11-15 09:13:47 +00004470 case Type::STK_Bool: // casting from bool is like casting from an integer
4471 case Type::STK_Integral:
4472 switch (DestTy->getScalarTypeKind()) {
4473 case Type::STK_Pointer:
John McCalld7646252010-11-14 08:17:51 +00004474 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004475 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004476 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004477 case Type::STK_Bool:
4478 return CK_IntegralToBoolean;
4479 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004480 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004481 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004482 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004483 case Type::STK_IntegralComplex:
John McCallfcef3cf2010-12-14 17:51:41 +00004484 S.ImpCastExprToType(Src, cast<ComplexType>(DestTy)->getElementType(),
4485 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004486 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004487 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004488 S.ImpCastExprToType(Src, cast<ComplexType>(DestTy)->getElementType(),
4489 CK_IntegralToFloating);
4490 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004491 case Type::STK_MemberPointer:
4492 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004493 }
4494 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004495
John McCall8cb679e2010-11-15 09:13:47 +00004496 case Type::STK_Floating:
4497 switch (DestTy->getScalarTypeKind()) {
4498 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004499 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004500 case Type::STK_Bool:
4501 return CK_FloatingToBoolean;
4502 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004503 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004504 case Type::STK_FloatingComplex:
John McCallfcef3cf2010-12-14 17:51:41 +00004505 S.ImpCastExprToType(Src, cast<ComplexType>(DestTy)->getElementType(),
4506 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004507 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004508 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004509 S.ImpCastExprToType(Src, cast<ComplexType>(DestTy)->getElementType(),
4510 CK_FloatingToIntegral);
4511 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004512 case Type::STK_Pointer:
4513 llvm_unreachable("valid float->pointer cast?");
4514 case Type::STK_MemberPointer:
4515 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004516 }
4517 break;
4518
John McCall8cb679e2010-11-15 09:13:47 +00004519 case Type::STK_FloatingComplex:
4520 switch (DestTy->getScalarTypeKind()) {
4521 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004522 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004523 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004524 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004525 case Type::STK_Floating: {
4526 QualType ET = cast<ComplexType>(SrcTy)->getElementType();
4527 if (S.Context.hasSameType(ET, DestTy))
4528 return CK_FloatingComplexToReal;
4529 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4530 return CK_FloatingCast;
4531 }
John McCall8cb679e2010-11-15 09:13:47 +00004532 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004533 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004534 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004535 S.ImpCastExprToType(Src, cast<ComplexType>(SrcTy)->getElementType(),
4536 CK_FloatingComplexToReal);
4537 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004538 case Type::STK_Pointer:
4539 llvm_unreachable("valid complex float->pointer cast?");
4540 case Type::STK_MemberPointer:
4541 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004542 }
4543 break;
4544
John McCall8cb679e2010-11-15 09:13:47 +00004545 case Type::STK_IntegralComplex:
4546 switch (DestTy->getScalarTypeKind()) {
4547 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004548 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004549 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004550 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004551 case Type::STK_Integral: {
4552 QualType ET = cast<ComplexType>(SrcTy)->getElementType();
4553 if (S.Context.hasSameType(ET, DestTy))
4554 return CK_IntegralComplexToReal;
4555 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4556 return CK_IntegralCast;
4557 }
John McCall8cb679e2010-11-15 09:13:47 +00004558 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004559 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004560 case Type::STK_Floating:
John McCalld7646252010-11-14 08:17:51 +00004561 S.ImpCastExprToType(Src, cast<ComplexType>(SrcTy)->getElementType(),
4562 CK_IntegralComplexToReal);
4563 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004564 case Type::STK_Pointer:
4565 llvm_unreachable("valid complex int->pointer cast?");
4566 case Type::STK_MemberPointer:
4567 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004568 }
4569 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004570 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004571
John McCalld7646252010-11-14 08:17:51 +00004572 llvm_unreachable("Unhandled scalar cast");
4573 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00004574}
4575
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004576/// CheckCastTypes - Check type constraints for casting between types.
John McCall7decc9e2010-11-18 06:31:45 +00004577bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4578 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4579 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00004580 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00004581 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4582 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00004583 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00004584 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00004585
John McCall7decc9e2010-11-18 06:31:45 +00004586 // We only support r-value casts in C.
4587 VK = VK_RValue;
4588
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004589 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4590 // type needs to be scalar.
4591 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004592 // We don't necessarily do lvalue-to-rvalue conversions on this.
4593 IgnoredValueConversions(castExpr);
4594
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004595 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004596 Kind = CK_ToVoid;
Anders Carlssonef918ac2009-10-16 02:35:04 +00004597 return false;
4598 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004599
John McCall34376a62010-12-04 03:47:34 +00004600 DefaultFunctionArrayLvalueConversion(castExpr);
4601
Eli Friedmane98194d2010-07-17 20:43:49 +00004602 if (RequireCompleteType(TyR.getBegin(), castType,
4603 diag::err_typecheck_cast_to_incomplete))
4604 return true;
4605
Anders Carlssonef918ac2009-10-16 02:35:04 +00004606 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004607 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004608 (castType->isStructureType() || castType->isUnionType())) {
4609 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004610 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004611 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4612 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004613 Kind = CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00004614 return false;
4615 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004616
Anders Carlsson525b76b2009-10-16 02:48:28 +00004617 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004618 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004619 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004620 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004621 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004622 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004623 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004624 castExpr->getType()) &&
4625 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004626 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4627 << castExpr->getSourceRange();
4628 break;
4629 }
4630 }
4631 if (Field == FieldEnd)
4632 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4633 << castExpr->getType() << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004634 Kind = CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00004635 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004636 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004637
Anders Carlsson525b76b2009-10-16 02:48:28 +00004638 // Reject any other conversions to non-scalar types.
4639 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
4640 << castType << castExpr->getSourceRange();
4641 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004642
John McCalld7646252010-11-14 08:17:51 +00004643 // The type we're casting to is known to be a scalar or vector.
4644
4645 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004646 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00004647 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004648 return Diag(castExpr->getLocStart(),
4649 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004650 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004651 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004652
4653 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00004654 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004655
Anders Carlsson525b76b2009-10-16 02:48:28 +00004656 if (castType->isVectorType())
4657 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
4658 if (castExpr->getType()->isVectorType())
4659 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
4660
John McCalld7646252010-11-14 08:17:51 +00004661 // The source and target types are both scalars, i.e.
4662 // - arithmetic types (fundamental, enum, and complex)
4663 // - all kinds of pointers
4664 // Note that member pointers were filtered out with C++, above.
4665
Anders Carlsson43d70f82009-10-16 05:23:41 +00004666 if (isa<ObjCSelectorExpr>(castExpr))
4667 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004668
John McCalld7646252010-11-14 08:17:51 +00004669 // If either type is a pointer, the other type has to be either an
4670 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00004671 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004672 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00004673 if (!castExprType->isIntegralType(Context) &&
Douglas Gregorb90df602010-06-16 00:17:44 +00004674 castExprType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004675 return Diag(castExpr->getLocStart(),
4676 diag::err_cast_pointer_from_non_pointer_int)
4677 << castExprType << castExpr->getSourceRange();
4678 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004679 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004680 return Diag(castExpr->getLocStart(),
4681 diag::err_cast_pointer_to_non_pointer_int)
4682 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004683 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004684
John McCalld7646252010-11-14 08:17:51 +00004685 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCall2b5c1b22010-08-12 21:44:57 +00004686
John McCalld7646252010-11-14 08:17:51 +00004687 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004688 CheckCastAlign(castExpr, castType, TyR);
4689
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004690 return false;
4691}
4692
Anders Carlsson525b76b2009-10-16 02:48:28 +00004693bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004694 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004695 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004696
Anders Carlssonde71adf2007-11-27 05:51:55 +00004697 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004698 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004699 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004700 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004701 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004702 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004703 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004704 } else
4705 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004706 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004707 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004708
John McCalle3027922010-08-25 11:45:40 +00004709 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004710 return false;
4711}
4712
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004713bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCalle3027922010-08-25 11:45:40 +00004714 CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004715 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004716
Anders Carlsson43d70f82009-10-16 05:23:41 +00004717 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004718
Nate Begemanc8961a42009-06-27 22:05:55 +00004719 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4720 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004721 if (SrcTy->isVectorType()) {
4722 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
4723 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4724 << DestTy << SrcTy << R;
John McCalle3027922010-08-25 11:45:40 +00004725 Kind = CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00004726 return false;
4727 }
4728
Nate Begemanbd956c42009-06-28 02:36:38 +00004729 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004730 // conversion will take place first from scalar to elt type, and then
4731 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004732 if (SrcTy->isPointerType())
4733 return Diag(R.getBegin(),
4734 diag::err_invalid_conversion_between_vector_and_scalar)
4735 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004736
4737 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4738 ImpCastExprToType(CastExpr, DestElemTy,
John McCalld7646252010-11-14 08:17:51 +00004739 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004740
John McCalle3027922010-08-25 11:45:40 +00004741 Kind = CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00004742 return false;
4743}
4744
John McCalldadc5752010-08-24 06:29:42 +00004745ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004746Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004747 SourceLocation RParenLoc, Expr *castExpr) {
4748 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004749 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004750
John McCall97513962010-01-15 18:39:57 +00004751 TypeSourceInfo *castTInfo;
4752 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4753 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00004754 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00004755
Nate Begeman5ec4b312009-08-10 23:49:36 +00004756 // If the Expr being casted is a ParenListExpr, handle it specially.
4757 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00004758 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00004759 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00004760
John McCallb268a282010-08-23 23:25:46 +00004761 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004762}
4763
John McCalldadc5752010-08-24 06:29:42 +00004764ExprResult
John McCallebe54742010-01-15 18:56:44 +00004765Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004766 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004767 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004768 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004769 CXXCastPath BasePath;
John McCallebe54742010-01-15 18:56:44 +00004770 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCall7decc9e2010-11-18 06:31:45 +00004771 Kind, VK, BasePath))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004772 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00004773
John McCallcf142162010-08-07 06:22:56 +00004774 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +00004775 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00004776 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00004777 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004778}
4779
Nate Begeman5ec4b312009-08-10 23:49:36 +00004780/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4781/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004782ExprResult
John McCallb268a282010-08-23 23:25:46 +00004783Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004784 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4785 if (!E)
4786 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004787
John McCalldadc5752010-08-24 06:29:42 +00004788 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004789
Nate Begeman5ec4b312009-08-10 23:49:36 +00004790 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004791 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4792 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004793
John McCallb268a282010-08-23 23:25:46 +00004794 if (Result.isInvalid()) return ExprError();
4795
4796 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004797}
4798
John McCalldadc5752010-08-24 06:29:42 +00004799ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00004800Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00004801 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00004802 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00004803 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00004804 QualType Ty = TInfo->getType();
John Thompson781ad172010-06-30 22:55:51 +00004805 bool isAltiVecLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00004806
John Thompson781ad172010-06-30 22:55:51 +00004807 // Check for an altivec literal,
4808 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004809 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4810 if (PE->getNumExprs() == 0) {
4811 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4812 return ExprError();
4813 }
John Thompson781ad172010-06-30 22:55:51 +00004814 if (PE->getNumExprs() == 1) {
4815 if (!PE->getExpr(0)->getType()->isVectorType())
4816 isAltiVecLiteral = true;
4817 }
4818 else
4819 isAltiVecLiteral = true;
4820 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004821
John Thompson781ad172010-06-30 22:55:51 +00004822 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
4823 // then handle it as such.
4824 if (isAltiVecLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004825 llvm::SmallVector<Expr *, 8> initExprs;
4826 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4827 initExprs.push_back(PE->getExpr(i));
4828
4829 // FIXME: This means that pretty-printing the final AST will produce curly
4830 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00004831 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4832 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00004833 initExprs.size(), RParenLoc);
4834 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00004835 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004836 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004837 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00004838 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00004839 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00004840 if (Result.isInvalid()) return ExprError();
4841 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004842 }
4843}
4844
John McCalldadc5752010-08-24 06:29:42 +00004845ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004846 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004847 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00004848 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004849 unsigned nexprs = Val.size();
4850 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004851 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4852 Expr *expr;
4853 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4854 expr = new (Context) ParenExpr(L, R, exprs[0]);
4855 else
4856 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004857 return Owned(expr);
4858}
4859
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004860/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4861/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004862/// C99 6.5.15
4863QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall7decc9e2010-11-18 06:31:45 +00004864 Expr *&SAVE, ExprValueKind &VK,
John McCall4bc41ae2010-11-18 19:01:18 +00004865 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004866 SourceLocation QuestionLoc) {
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004867 // If both LHS and RHS are overloaded functions, try to resolve them.
4868 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
4869 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
4870 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
4871 if (LHSResult.isInvalid())
4872 return QualType();
4873
4874 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
4875 if (RHSResult.isInvalid())
4876 return QualType();
4877
4878 LHS = LHSResult.take();
4879 RHS = RHSResult.take();
4880 }
4881
Sebastian Redl1a99f442009-04-16 17:51:27 +00004882 // C++ is sufficiently different to merit its own checker.
4883 if (getLangOptions().CPlusPlus)
John McCall4bc41ae2010-11-18 19:01:18 +00004884 return CXXCheckConditionalOperands(Cond, LHS, RHS, SAVE,
4885 VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004886
4887 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004888 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004889
Chris Lattner432cff52009-02-18 04:28:32 +00004890 UsualUnaryConversions(Cond);
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00004891 if (SAVE) {
4892 SAVE = LHS = Cond;
4893 }
4894 else
4895 UsualUnaryConversions(LHS);
Chris Lattner432cff52009-02-18 04:28:32 +00004896 UsualUnaryConversions(RHS);
4897 QualType CondTy = Cond->getType();
4898 QualType LHSTy = LHS->getType();
4899 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004900
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004901 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004902 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00004903 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4904 // Throw an error if its not either.
4905 if (getLangOptions().OpenCL) {
4906 if (!CondTy->isVectorType()) {
4907 Diag(Cond->getLocStart(),
4908 diag::err_typecheck_cond_expect_scalar_or_vector)
4909 << CondTy;
4910 return QualType();
4911 }
4912 }
4913 else {
4914 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4915 << CondTy;
4916 return QualType();
4917 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004918 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004919
Chris Lattnere2949f42008-01-06 22:42:25 +00004920 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004921 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4922 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00004923
Nate Begemanabb5a732010-09-20 22:41:17 +00004924 // OpenCL: If the condition is a vector, and both operands are scalar,
4925 // attempt to implicity convert them to the vector type to act like the
4926 // built in select.
4927 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4928 // Both operands should be of scalar type.
4929 if (!LHSTy->isScalarType()) {
4930 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4931 << CondTy;
4932 return QualType();
4933 }
4934 if (!RHSTy->isScalarType()) {
4935 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4936 << CondTy;
4937 return QualType();
4938 }
4939 // Implicity convert these scalars to the type of the condition.
4940 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
4941 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
4942 }
4943
Chris Lattnere2949f42008-01-06 22:42:25 +00004944 // If both operands have arithmetic type, do the usual arithmetic conversions
4945 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004946 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4947 UsualArithmeticConversions(LHS, RHS);
4948 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004949 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004950
Chris Lattnere2949f42008-01-06 22:42:25 +00004951 // If both operands are the same structure or union type, the result is that
4952 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004953 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4954 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004955 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004956 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004957 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004958 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004959 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004960 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004961
Chris Lattnere2949f42008-01-06 22:42:25 +00004962 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004963 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004964 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4965 if (!LHSTy->isVoidType())
4966 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4967 << RHS->getSourceRange();
4968 if (!RHSTy->isVoidType())
4969 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4970 << LHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004971 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
4972 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004973 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004974 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004975 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4976 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004977 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004978 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004979 // promote the null to a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00004980 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004981 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004982 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004983 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004984 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00004985 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004986 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004987 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004988
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004989 // All objective-c pointer type analysis is done here.
4990 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4991 QuestionLoc);
4992 if (!compositeType.isNull())
4993 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004994
4995
Steve Naroff05efa972009-07-01 14:36:47 +00004996 // Handle block pointer types.
4997 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4998 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4999 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5000 QualType destType = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005001 ImpCastExprToType(LHS, destType, CK_BitCast);
5002 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005003 return destType;
5004 }
5005 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005006 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005007 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005008 }
Steve Naroff05efa972009-07-01 14:36:47 +00005009 // We have 2 block pointer types.
5010 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5011 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005012 return LHSTy;
5013 }
Steve Naroff05efa972009-07-01 14:36:47 +00005014 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005015 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5016 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005017
Steve Naroff05efa972009-07-01 14:36:47 +00005018 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5019 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005020 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005021 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005022 // In this situation, we assume void* type. No especially good
5023 // reason, but this is what gcc does, and we do have to pick
5024 // to get a consistent AST.
5025 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005026 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5027 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005028 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005029 }
Steve Naroff05efa972009-07-01 14:36:47 +00005030 // The block pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005031 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5032 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005033 return LHSTy;
5034 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005035
Steve Naroff05efa972009-07-01 14:36:47 +00005036 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5037 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5038 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005039 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5040 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005041
5042 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5043 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5044 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005045 QualType destPointee
5046 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005047 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005048 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005049 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005050 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005051 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005052 return destType;
5053 }
5054 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005055 QualType destPointee
5056 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005057 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005058 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005059 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005060 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005061 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005062 return destType;
5063 }
5064
5065 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5066 // Two identical pointer types are always compatible.
5067 return LHSTy;
5068 }
5069 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5070 rhptee.getUnqualifiedType())) {
5071 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5072 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5073 // In this situation, we assume void* type. No especially good
5074 // reason, but this is what gcc does, and we do have to pick
5075 // to get a consistent AST.
5076 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005077 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5078 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005079 return incompatTy;
5080 }
5081 // The pointer types are compatible.
5082 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5083 // differently qualified versions of compatible types, the result type is
5084 // a pointer to an appropriately qualified version of the *composite*
5085 // type.
5086 // FIXME: Need to calculate the composite type.
5087 // FIXME: Need to add qualifiers
John McCalle3027922010-08-25 11:45:40 +00005088 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5089 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005090 return LHSTy;
5091 }
Mike Stump11289f42009-09-09 15:08:12 +00005092
John McCalle84af4e2010-11-13 01:35:44 +00005093 // GCC compatibility: soften pointer/integer mismatch. Note that
5094 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005095 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5096 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5097 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005098 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005099 return RHSTy;
5100 }
5101 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5102 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5103 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005104 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005105 return LHSTy;
5106 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005107
Chris Lattnere2949f42008-01-06 22:42:25 +00005108 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005109 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5110 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005111 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005112}
5113
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005114/// FindCompositeObjCPointerType - Helper method to find composite type of
5115/// two objective-c pointer types of the two input expressions.
5116QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5117 SourceLocation QuestionLoc) {
5118 QualType LHSTy = LHS->getType();
5119 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005120
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005121 // Handle things like Class and struct objc_class*. Here we case the result
5122 // to the pseudo-builtin, because that will be implicitly cast back to the
5123 // redefinition type if an attempt is made to access its fields.
5124 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005125 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005126 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005127 return LHSTy;
5128 }
5129 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005130 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005131 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005132 return RHSTy;
5133 }
5134 // And the same for struct objc_object* / id
5135 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005136 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005137 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005138 return LHSTy;
5139 }
5140 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005141 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005142 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005143 return RHSTy;
5144 }
5145 // And the same for struct objc_selector* / SEL
5146 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005147 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005148 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005149 return LHSTy;
5150 }
5151 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005152 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005153 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005154 return RHSTy;
5155 }
5156 // Check constraints for Objective-C object pointers types.
5157 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005158
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005159 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5160 // Two identical object pointer types are always compatible.
5161 return LHSTy;
5162 }
5163 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5164 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5165 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005166
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005167 // If both operands are interfaces and either operand can be
5168 // assigned to the other, use that type as the composite
5169 // type. This allows
5170 // xxx ? (A*) a : (B*) b
5171 // where B is a subclass of A.
5172 //
5173 // Additionally, as for assignment, if either type is 'id'
5174 // allow silent coercion. Finally, if the types are
5175 // incompatible then make sure to use 'id' as the composite
5176 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005177
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005178 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5179 // It could return the composite type.
5180 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5181 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5182 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5183 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5184 } else if ((LHSTy->isObjCQualifiedIdType() ||
5185 RHSTy->isObjCQualifiedIdType()) &&
5186 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5187 // Need to handle "id<xx>" explicitly.
5188 // GCC allows qualified id and any Objective-C type to devolve to
5189 // id. Currently localizing to here until clear this should be
5190 // part of ObjCQualifiedIdTypesAreCompatible.
5191 compositeType = Context.getObjCIdType();
5192 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5193 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005194 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005195 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5196 ;
5197 else {
5198 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5199 << LHSTy << RHSTy
5200 << LHS->getSourceRange() << RHS->getSourceRange();
5201 QualType incompatTy = Context.getObjCIdType();
John McCalle3027922010-08-25 11:45:40 +00005202 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5203 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005204 return incompatTy;
5205 }
5206 // The object pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005207 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5208 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005209 return compositeType;
5210 }
5211 // Check Objective-C object pointer types and 'void *'
5212 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5213 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5214 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5215 QualType destPointee
5216 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5217 QualType destType = Context.getPointerType(destPointee);
5218 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005219 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005220 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005221 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005222 return destType;
5223 }
5224 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5225 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5226 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5227 QualType destPointee
5228 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5229 QualType destType = Context.getPointerType(destPointee);
5230 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005231 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005232 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005233 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005234 return destType;
5235 }
5236 return QualType();
5237}
5238
Steve Naroff83895f72007-09-16 03:34:24 +00005239/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005240/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005241ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005242 SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +00005243 Expr *CondExpr, Expr *LHSExpr,
5244 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005245 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5246 // was the condition.
5247 bool isLHSNull = LHSExpr == 0;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005248 Expr *SAVEExpr = 0;
5249 if (isLHSNull) {
5250 LHSExpr = SAVEExpr = CondExpr;
5251 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005252
John McCall7decc9e2010-11-18 06:31:45 +00005253 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005254 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00005255 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCall4bc41ae2010-11-18 19:01:18 +00005256 SAVEExpr, VK, OK, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00005257 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005258 return ExprError();
5259
Douglas Gregor7e112b02009-08-26 14:37:04 +00005260 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005261 LHSExpr, ColonLoc,
5262 RHSExpr, SAVEExpr,
John McCall4bc41ae2010-11-18 19:01:18 +00005263 result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005264}
5265
Steve Naroff3f597292007-05-11 22:18:03 +00005266// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005267// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005268// routine is it effectively iqnores the qualifiers on the top level pointee.
5269// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5270// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005271Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00005272Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00005273 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005274
David Chisnall9f57c292009-08-17 16:35:33 +00005275 if ((lhsType->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005276 (Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType))) ||
David Chisnall9f57c292009-08-17 16:35:33 +00005277 (rhsType->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005278 (Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)))) {
David Chisnall9f57c292009-08-17 16:35:33 +00005279 return Compatible;
5280 }
5281
Steve Naroff1f4d7272007-05-11 04:00:31 +00005282 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005283 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
5284 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005285
Steve Naroff1f4d7272007-05-11 04:00:31 +00005286 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00005287 lhptee = Context.getCanonicalType(lhptee);
5288 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00005289
Chris Lattner9bad62c2008-01-04 18:04:52 +00005290 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005291
5292 // C99 6.5.16.1p1: This following citation is common to constraints
5293 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5294 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00005295 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00005296 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00005297 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00005298
Mike Stump4e1f26a2009-02-19 03:04:26 +00005299 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5300 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005301 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005302 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005303 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005304 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005305
Chris Lattner0a788432008-01-03 22:56:36 +00005306 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005307 assert(rhptee->isFunctionType());
5308 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005309 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005310
Chris Lattner0a788432008-01-03 22:56:36 +00005311 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005312 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005313 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005314
5315 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005316 assert(lhptee->isFunctionType());
5317 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005318 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005319 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005320 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00005321 lhptee = lhptee.getUnqualifiedType();
5322 rhptee = rhptee.getUnqualifiedType();
5323 if (!Context.typesAreCompatible(lhptee, rhptee)) {
5324 // Check if the pointee types are compatible ignoring the sign.
5325 // We explicitly check for char so that we catch "char" vs
5326 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005327 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00005328 lhptee = Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005329 else if (lhptee->hasSignedIntegerRepresentation())
Eli Friedman80160bd2009-03-22 23:59:44 +00005330 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005331
Chris Lattnerec3a1562009-10-17 20:33:28 +00005332 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00005333 rhptee = Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005334 else if (rhptee->hasSignedIntegerRepresentation())
Eli Friedman80160bd2009-03-22 23:59:44 +00005335 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005336
Eli Friedman80160bd2009-03-22 23:59:44 +00005337 if (lhptee == rhptee) {
5338 // Types are compatible ignoring the sign. Qualifier incompatibility
5339 // takes priority over sign incompatibility because the sign
5340 // warning can be disabled.
5341 if (ConvTy != Compatible)
5342 return ConvTy;
5343 return IncompatiblePointerSign;
5344 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005345
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005346 // If we are a multi-level pointer, it's possible that our issue is simply
5347 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5348 // the eventual target type is the same and the pointers have the same
5349 // level of indirection, this must be the issue.
5350 if (lhptee->isPointerType() && rhptee->isPointerType()) {
5351 do {
5352 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
5353 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005354
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005355 lhptee = Context.getCanonicalType(lhptee);
5356 rhptee = Context.getCanonicalType(rhptee);
5357 } while (lhptee->isPointerType() && rhptee->isPointerType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005358
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005359 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00005360 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005361 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005362
Eli Friedman80160bd2009-03-22 23:59:44 +00005363 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00005364 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005365 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005366 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005367}
5368
Steve Naroff081c7422008-09-04 15:10:53 +00005369/// CheckBlockPointerTypesForAssignment - This routine determines whether two
5370/// block pointer types are compatible or whether a block and normal pointer
5371/// are compatible. It is more restrict than comparing two function pointer
5372// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005373Sema::AssignConvertType
5374Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00005375 QualType rhsType) {
5376 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005377
Steve Naroff081c7422008-09-04 15:10:53 +00005378 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005379 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
5380 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005381
Steve Naroff081c7422008-09-04 15:10:53 +00005382 // make sure we operate on the canonical type
5383 lhptee = Context.getCanonicalType(lhptee);
5384 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005385
Steve Naroff081c7422008-09-04 15:10:53 +00005386 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005387
Steve Naroff081c7422008-09-04 15:10:53 +00005388 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005389 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00005390 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005391
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005392 if (!getLangOptions().CPlusPlus) {
5393 if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5394 return IncompatibleBlockPointer;
5395 }
5396 else if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00005397 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00005398 return ConvTy;
5399}
5400
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005401/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
5402/// for assignment compatibility.
5403Sema::AssignConvertType
5404Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005405 if (lhsType->isObjCBuiltinType()) {
5406 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005407 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5408 !rhsType->isObjCQualifiedClassType())
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005409 return IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005410 return Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005411 }
5412 if (rhsType->isObjCBuiltinType()) {
5413 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005414 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5415 !lhsType->isObjCQualifiedClassType())
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005416 return IncompatiblePointer;
5417 return Compatible;
5418 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005419 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005420 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005421 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005422 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
5423 // make sure we operate on the canonical type
5424 lhptee = Context.getCanonicalType(lhptee);
5425 rhptee = Context.getCanonicalType(rhptee);
5426 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5427 return CompatiblePointerDiscardsQualifiers;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005428
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005429 if (Context.typesAreCompatible(lhsType, rhsType))
5430 return Compatible;
5431 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
5432 return IncompatibleObjCQualifiedId;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005433 return IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005434}
5435
John McCall29600e12010-11-16 02:32:08 +00005436Sema::AssignConvertType
5437Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
5438 // Fake up an opaque expression. We don't actually care about what
5439 // cast operations are required, so if CheckAssignmentConstraints
5440 // adds casts to this they'll be wasted, but fortunately that doesn't
5441 // usually happen on valid code.
5442 OpaqueValueExpr rhs(rhsType, VK_RValue);
5443 Expr *rhsPtr = &rhs;
5444 CastKind K = CK_Invalid;
5445
5446 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5447}
5448
Mike Stump4e1f26a2009-02-19 03:04:26 +00005449/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5450/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005451/// pointers. Here are some objectionable examples that GCC considers warnings:
5452///
5453/// int a, *pint;
5454/// short *pshort;
5455/// struct foo *pfoo;
5456///
5457/// pint = pshort; // warning: assignment from incompatible pointer type
5458/// a = pint; // warning: assignment makes integer from pointer without a cast
5459/// pint = a; // warning: assignment makes pointer from integer without a cast
5460/// pint = pfoo; // warning: assignment from incompatible pointer type
5461///
5462/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005463/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005464///
John McCall8cb679e2010-11-15 09:13:47 +00005465/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005466Sema::AssignConvertType
John McCall29600e12010-11-16 02:32:08 +00005467Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005468 CastKind &Kind) {
John McCall29600e12010-11-16 02:32:08 +00005469 QualType rhsType = rhs->getType();
5470
Chris Lattnera52c2f22008-01-04 23:18:45 +00005471 // Get canonical types. We're not formatting these types, just comparing
5472 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005473 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5474 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005475
John McCall8cb679e2010-11-15 09:13:47 +00005476 if (lhsType == rhsType) {
5477 Kind = CK_NoOp;
Chris Lattnerf5c973d2008-01-07 17:51:46 +00005478 return Compatible; // Common case: fast path an exact match.
John McCall8cb679e2010-11-15 09:13:47 +00005479 }
Steve Naroff44fd8ff2007-07-24 21:46:40 +00005480
David Chisnall9f57c292009-08-17 16:35:33 +00005481 if ((lhsType->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005482 (Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType))) ||
David Chisnall9f57c292009-08-17 16:35:33 +00005483 (rhsType->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005484 (Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)))) {
John McCall8cb679e2010-11-15 09:13:47 +00005485 Kind = CK_BitCast;
5486 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005487 }
5488
Douglas Gregor6b754842008-10-28 00:22:11 +00005489 // If the left-hand side is a reference type, then we are in a
5490 // (rare!) case where we've allowed the use of references in C,
5491 // e.g., as a parameter type in a built-in function. In this case,
5492 // just make sure that the type referenced is compatible with the
5493 // right-hand side type. The caller is responsible for adjusting
5494 // lhsType so that the resulting expression does not have reference
5495 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005496 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005497 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5498 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005499 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005500 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005501 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005502 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005503 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5504 // to the same ExtVector type.
5505 if (lhsType->isExtVectorType()) {
5506 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005507 return Incompatible;
5508 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005509 // CK_VectorSplat does T -> vector T, so first cast to the
5510 // element type.
5511 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5512 if (elType != rhsType) {
5513 Kind = PrepareScalarCast(*this, rhs, elType);
5514 ImpCastExprToType(rhs, elType, Kind);
5515 }
5516 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005517 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005518 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005519 }
Mike Stump11289f42009-09-09 15:08:12 +00005520
Nate Begeman191a6b12008-07-14 18:02:46 +00005521 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005522 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005523 // Allow assignments of an AltiVec vector type to an equivalent GCC
5524 // vector type and vice versa
5525 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5526 Kind = CK_BitCast;
5527 return Compatible;
5528 }
5529
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005530 // If we are allowing lax vector conversions, and LHS and RHS are both
5531 // vectors, the total size only needs to be the same. This is a bitcast;
5532 // no bits are changed but the result type is different.
5533 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005534 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005535 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005536 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005537 }
Chris Lattner881a2122008-01-04 23:32:24 +00005538 }
5539 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005540 }
Eli Friedman3360d892008-05-30 18:07:22 +00005541
Douglas Gregorbea453a2010-05-23 21:53:47 +00005542 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005543 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005544 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005545 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005546 }
Eli Friedman3360d892008-05-30 18:07:22 +00005547
Chris Lattnerec646832008-04-07 06:49:41 +00005548 if (isa<PointerType>(lhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005549 if (rhsType->isIntegerType()) {
5550 Kind = CK_IntegralToPointer; // FIXME: null?
Chris Lattner940cfeb2008-01-04 18:22:42 +00005551 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005552 }
Eli Friedman3360d892008-05-30 18:07:22 +00005553
John McCall8cb679e2010-11-15 09:13:47 +00005554 if (isa<PointerType>(rhsType)) {
5555 Kind = CK_BitCast;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005556 return CheckPointerTypesForAssignment(lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005557 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005558
Steve Naroffaccc4882009-07-20 17:56:53 +00005559 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005560 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005561 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005562 if (lhsType->isVoidPointerType()) // an exception to the rule.
5563 return Compatible;
5564 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005565 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005566 if (rhsType->getAs<BlockPointerType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005567 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5568 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005569 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005570 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005571
5572 // Treat block pointers as objects.
John McCall8cb679e2010-11-15 09:13:47 +00005573 if (getLangOptions().ObjC1 && lhsType->isObjCIdType()) {
5574 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005575 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005576 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005577 }
Steve Naroff081c7422008-09-04 15:10:53 +00005578 return Incompatible;
5579 }
5580
5581 if (isa<BlockPointerType>(lhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005582 if (rhsType->isIntegerType()) {
5583 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005584 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005585 }
5586
5587 Kind = CK_AnyPointerToObjCPointerCast;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005588
Steve Naroff32d072c2008-09-29 18:10:17 +00005589 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005590 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00005591 return Compatible;
5592
Steve Naroff081c7422008-09-04 15:10:53 +00005593 if (rhsType->isBlockPointerType())
5594 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005595
John McCall8cb679e2010-11-15 09:13:47 +00005596 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
Steve Naroff081c7422008-09-04 15:10:53 +00005597 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00005598 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005599
Chris Lattnera52c2f22008-01-04 23:18:45 +00005600 return Incompatible;
5601 }
5602
Steve Naroff7cae42b2009-07-10 23:34:53 +00005603 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005604 if (rhsType->isIntegerType()) {
5605 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005606 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005607 }
5608
5609 Kind = CK_BitCast;
Mike Stump11289f42009-09-09 15:08:12 +00005610
Steve Naroffaccc4882009-07-20 17:56:53 +00005611 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005612 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005613 if (rhsType->isVoidPointerType()) // an exception to the rule.
5614 return Compatible;
5615 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005616 }
5617 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005618 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005619 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005620 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005621 if (RHSPT->getPointeeType()->isVoidType())
5622 return Compatible;
5623 }
5624 // Treat block pointers as objects.
5625 if (rhsType->isBlockPointerType())
5626 return Compatible;
5627 return Incompatible;
5628 }
Chris Lattnerec646832008-04-07 06:49:41 +00005629 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00005630 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005631 if (lhsType == Context.BoolTy) {
5632 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005633 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005634 }
Eli Friedman3360d892008-05-30 18:07:22 +00005635
John McCall8cb679e2010-11-15 09:13:47 +00005636 if (lhsType->isIntegerType()) {
5637 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005638 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005639 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005640
5641 if (isa<BlockPointerType>(lhsType) &&
John McCall8cb679e2010-11-15 09:13:47 +00005642 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5643 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005644 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005645 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005646 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005647 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005648 if (isa<ObjCObjectPointerType>(rhsType)) {
5649 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005650 if (lhsType == Context.BoolTy) {
5651 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005652 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005653 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005654
John McCall8cb679e2010-11-15 09:13:47 +00005655 if (lhsType->isIntegerType()) {
5656 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005657 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005658 }
5659
5660 Kind = CK_BitCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005661
Steve Naroffaccc4882009-07-20 17:56:53 +00005662 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005663 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005664 if (lhsType->isVoidPointerType()) // an exception to the rule.
5665 return Compatible;
5666 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005667 }
5668 if (isa<BlockPointerType>(lhsType) &&
John McCall8cb679e2010-11-15 09:13:47 +00005669 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5670 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005671 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005672 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005673 return Incompatible;
5674 }
Eli Friedman3360d892008-05-30 18:07:22 +00005675
Chris Lattnera52c2f22008-01-04 23:18:45 +00005676 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005677 if (Context.typesAreCompatible(lhsType, rhsType)) {
5678 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005679 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005680 }
Bill Wendling216423b2007-05-30 06:30:29 +00005681 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00005682 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005683}
5684
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005685/// \brief Constructs a transparent union from an expression that is
5686/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00005687static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005688 QualType UnionType, FieldDecl *Field) {
5689 // Build an initializer list that designates the appropriate member
5690 // of the transparent union.
Ted Kremenekac034612010-04-13 23:39:13 +00005691 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005692 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005693 SourceLocation());
5694 Initializer->setType(UnionType);
5695 Initializer->setInitializedFieldInUnion(Field);
5696
5697 // Build a compound literal constructing a value of the transparent
5698 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005699 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00005700 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall7decc9e2010-11-18 06:31:45 +00005701 VK_RValue, Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005702}
5703
5704Sema::AssignConvertType
5705Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
5706 QualType FromType = rExpr->getType();
5707
Mike Stump11289f42009-09-09 15:08:12 +00005708 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005709 // transparent_union GCC extension.
5710 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005711 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005712 return Incompatible;
5713
5714 // The field to initialize within the transparent union.
5715 RecordDecl *UD = UT->getDecl();
5716 FieldDecl *InitField = 0;
5717 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005718 for (RecordDecl::field_iterator it = UD->field_begin(),
5719 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005720 it != itend; ++it) {
5721 if (it->getType()->isPointerType()) {
5722 // If the transparent union contains a pointer type, we allow:
5723 // 1) void pointer
5724 // 2) null pointer constant
5725 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005726 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +00005727 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005728 InitField = *it;
5729 break;
5730 }
Mike Stump11289f42009-09-09 15:08:12 +00005731
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005732 if (rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005733 Expr::NPC_ValueDependentIsNull)) {
John McCalle84af4e2010-11-13 01:35:44 +00005734 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005735 InitField = *it;
5736 break;
5737 }
5738 }
5739
John McCall29600e12010-11-16 02:32:08 +00005740 Expr *rhs = rExpr;
John McCall8cb679e2010-11-15 09:13:47 +00005741 CastKind Kind = CK_Invalid;
John McCall29600e12010-11-16 02:32:08 +00005742 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005743 == Compatible) {
John McCall29600e12010-11-16 02:32:08 +00005744 ImpCastExprToType(rhs, it->getType(), Kind);
5745 rExpr = rhs;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005746 InitField = *it;
5747 break;
5748 }
5749 }
5750
5751 if (!InitField)
5752 return Incompatible;
5753
5754 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
5755 return Compatible;
5756}
5757
Chris Lattner9bad62c2008-01-04 18:04:52 +00005758Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005759Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005760 if (getLangOptions().CPlusPlus) {
5761 if (!lhsType->isRecordType()) {
5762 // C++ 5.17p3: If the left operand is not of class type, the
5763 // expression is implicitly converted (C++ 4) to the
5764 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00005765 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005766 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00005767 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00005768 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00005769 }
5770
5771 // FIXME: Currently, we fall through and treat C++ classes like C
5772 // structures.
John McCall34376a62010-12-04 03:47:34 +00005773 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005774
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005775 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5776 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00005777 if ((lhsType->isPointerType() ||
5778 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00005779 lhsType->isBlockPointerType())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005780 && rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005781 Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00005782 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005783 return Compatible;
5784 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005785
Chris Lattnere6dcd502007-10-16 02:55:40 +00005786 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005787 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005788 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005789 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005790 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005791 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00005792 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00005793 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005794
John McCall8cb679e2010-11-15 09:13:47 +00005795 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005796 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00005797 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005798
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005799 // C99 6.5.16.1p2: The value of the right operand is converted to the
5800 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005801 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5802 // so that we can use references in built-in functions even in C.
5803 // The getNonReferenceType() call makes sure that the resulting expression
5804 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005805 if (result != Incompatible && rExpr->getType() != lhsType)
John McCall8cb679e2010-11-15 09:13:47 +00005806 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005807 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005808}
5809
Chris Lattner326f7572008-11-18 01:30:42 +00005810QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005811 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005812 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00005813 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005814 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005815}
5816
Chris Lattnerfaa54172010-01-12 21:23:57 +00005817QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005818 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005819 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00005820 QualType lhsType =
5821 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
5822 QualType rhsType =
5823 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005824
Nate Begeman191a6b12008-07-14 18:02:46 +00005825 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005826 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00005827 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005828
Nate Begeman191a6b12008-07-14 18:02:46 +00005829 // Handle the case of a vector & extvector type of the same size and element
5830 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005831 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00005832 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00005833 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00005834 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005835 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005836 if (lhsType->isExtVectorType()) {
John McCalle3027922010-08-25 11:45:40 +00005837 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005838 return lhsType;
5839 }
5840
John McCalle3027922010-08-25 11:45:40 +00005841 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005842 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00005843 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
5844 // If we are allowing lax vector conversions, and LHS and RHS are both
5845 // vectors, the total size only needs to be the same. This is a
5846 // bitcast; no bits are changed but the result type is different.
5847 ImpCastExprToType(rex, lhsType, CK_BitCast);
5848 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005849 }
Eric Christophera613f562010-08-26 00:42:16 +00005850 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00005851 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005852 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005853
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005854 // Handle the case of equivalent AltiVec and GCC vector types
5855 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5856 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCalle3027922010-08-25 11:45:40 +00005857 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005858 return rhsType;
5859 }
5860
Nate Begemanbd956c42009-06-28 02:36:38 +00005861 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5862 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5863 bool swapped = false;
5864 if (rhsType->isExtVectorType()) {
5865 swapped = true;
5866 std::swap(rex, lex);
5867 std::swap(rhsType, lhsType);
5868 }
Mike Stump11289f42009-09-09 15:08:12 +00005869
Nate Begeman886448d2009-06-28 19:12:57 +00005870 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005871 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005872 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005873 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00005874 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5875 if (order > 0)
5876 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
5877 if (order >= 0) {
5878 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005879 if (swapped) std::swap(rex, lex);
5880 return lhsType;
5881 }
5882 }
5883 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5884 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005885 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5886 if (order > 0)
5887 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
5888 if (order >= 0) {
5889 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005890 if (swapped) std::swap(rex, lex);
5891 return lhsType;
5892 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005893 }
5894 }
Mike Stump11289f42009-09-09 15:08:12 +00005895
Nate Begeman886448d2009-06-28 19:12:57 +00005896 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00005897 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005898 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00005899 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005900 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005901}
5902
Chris Lattnerfaa54172010-01-12 21:23:57 +00005903QualType Sema::CheckMultiplyDivideOperands(
5904 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00005905 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005906 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005907
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005908 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005909
Chris Lattnerfaa54172010-01-12 21:23:57 +00005910 if (!lex->getType()->isArithmeticType() ||
5911 !rex->getType()->isArithmeticType())
5912 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005913
Chris Lattnerfaa54172010-01-12 21:23:57 +00005914 // Check for division by zero.
5915 if (isDiv &&
5916 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005917 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattner70117952010-01-12 21:30:55 +00005918 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005919
Chris Lattnerfaa54172010-01-12 21:23:57 +00005920 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005921}
5922
Chris Lattnerfaa54172010-01-12 21:23:57 +00005923QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005924 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005925 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005926 if (lex->getType()->hasIntegerRepresentation() &&
5927 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005928 return CheckVectorOperands(Loc, lex, rex);
5929 return InvalidOperands(Loc, lex, rex);
5930 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005931
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005932 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005933
Chris Lattnerfaa54172010-01-12 21:23:57 +00005934 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
5935 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005936
Chris Lattnerfaa54172010-01-12 21:23:57 +00005937 // Check for remainder by zero.
5938 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00005939 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
5940 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005941
Chris Lattnerfaa54172010-01-12 21:23:57 +00005942 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005943}
5944
Chris Lattnerfaa54172010-01-12 21:23:57 +00005945QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00005946 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005947 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5948 QualType compType = CheckVectorOperands(Loc, lex, rex);
5949 if (CompLHSTy) *CompLHSTy = compType;
5950 return compType;
5951 }
Steve Naroff7a5af782007-07-13 16:58:59 +00005952
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005953 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00005954
Steve Naroffe4718892007-04-27 18:30:00 +00005955 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005956 if (lex->getType()->isArithmeticType() &&
5957 rex->getType()->isArithmeticType()) {
5958 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005959 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005960 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00005961
Eli Friedman8e122982008-05-18 18:08:51 +00005962 // Put any potential pointer into PExp
5963 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00005964 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00005965 std::swap(PExp, IExp);
5966
Steve Naroff6b712a72009-07-14 18:25:06 +00005967 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005968
Eli Friedman8e122982008-05-18 18:08:51 +00005969 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005970 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005971
Chris Lattner12bdebb2009-04-24 23:50:08 +00005972 // Check for arithmetic on pointers to incomplete types.
5973 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00005974 if (getLangOptions().CPlusPlus) {
5975 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00005976 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00005977 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005978 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005979
5980 // GNU extension: arithmetic on pointer to void
5981 Diag(Loc, diag::ext_gnu_void_ptr)
5982 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00005983 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00005984 if (getLangOptions().CPlusPlus) {
5985 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5986 << lex->getType() << lex->getSourceRange();
5987 return QualType();
5988 }
5989
5990 // GNU extension: arithmetic on pointer to function
5991 Diag(Loc, diag::ext_gnu_ptr_func_arith)
5992 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00005993 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005994 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00005995 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00005996 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005997 PExp->getType()->isObjCObjectPointerType()) &&
5998 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00005999 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6000 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006001 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006002 return QualType();
6003 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00006004 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006005 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006006 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6007 << PointeeTy << PExp->getSourceRange();
6008 return QualType();
6009 }
Mike Stump11289f42009-09-09 15:08:12 +00006010
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006011 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00006012 QualType LHSTy = Context.isPromotableBitField(lex);
6013 if (LHSTy.isNull()) {
6014 LHSTy = lex->getType();
6015 if (LHSTy->isPromotableIntegerType())
6016 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006017 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006018 *CompLHSTy = LHSTy;
6019 }
Eli Friedman8e122982008-05-18 18:08:51 +00006020 return PExp->getType();
6021 }
6022 }
6023
Chris Lattner326f7572008-11-18 01:30:42 +00006024 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006025}
6026
Chris Lattner2a3569b2008-04-07 05:30:13 +00006027// C99 6.5.6
6028QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006029 SourceLocation Loc, QualType* CompLHSTy) {
6030 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6031 QualType compType = CheckVectorOperands(Loc, lex, rex);
6032 if (CompLHSTy) *CompLHSTy = compType;
6033 return compType;
6034 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006035
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006036 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006037
Chris Lattner4d62f422007-12-09 21:53:25 +00006038 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006039
Chris Lattner4d62f422007-12-09 21:53:25 +00006040 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00006041 if (lex->getType()->isArithmeticType()
6042 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006043 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006044 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006045 }
Mike Stump11289f42009-09-09 15:08:12 +00006046
Chris Lattner4d62f422007-12-09 21:53:25 +00006047 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00006048 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00006049 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006050
Douglas Gregorac1fb652009-03-24 19:52:54 +00006051 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006052
Douglas Gregorac1fb652009-03-24 19:52:54 +00006053 bool ComplainAboutVoid = false;
6054 Expr *ComplainAboutFunc = 0;
6055 if (lpointee->isVoidType()) {
6056 if (getLangOptions().CPlusPlus) {
6057 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6058 << lex->getSourceRange() << rex->getSourceRange();
6059 return QualType();
6060 }
6061
6062 // GNU C extension: arithmetic on pointer to void
6063 ComplainAboutVoid = true;
6064 } else if (lpointee->isFunctionType()) {
6065 if (getLangOptions().CPlusPlus) {
6066 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006067 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006068 return QualType();
6069 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006070
6071 // GNU C extension: arithmetic on pointer to function
6072 ComplainAboutFunc = lex;
6073 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00006074 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006075 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00006076 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006077 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006078 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006079
Chris Lattner12bdebb2009-04-24 23:50:08 +00006080 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006081 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006082 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6083 << lpointee << lex->getSourceRange();
6084 return QualType();
6085 }
Mike Stump11289f42009-09-09 15:08:12 +00006086
Chris Lattner4d62f422007-12-09 21:53:25 +00006087 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00006088 if (rex->getType()->isIntegerType()) {
6089 if (ComplainAboutVoid)
6090 Diag(Loc, diag::ext_gnu_void_ptr)
6091 << lex->getSourceRange() << rex->getSourceRange();
6092 if (ComplainAboutFunc)
6093 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006094 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006095 << ComplainAboutFunc->getSourceRange();
6096
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006097 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006098 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006099 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006100
Chris Lattner4d62f422007-12-09 21:53:25 +00006101 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006102 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006103 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006104
Douglas Gregorac1fb652009-03-24 19:52:54 +00006105 // RHS must be a completely-type object type.
6106 // Handle the GNU void* extension.
6107 if (rpointee->isVoidType()) {
6108 if (getLangOptions().CPlusPlus) {
6109 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6110 << lex->getSourceRange() << rex->getSourceRange();
6111 return QualType();
6112 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006113
Douglas Gregorac1fb652009-03-24 19:52:54 +00006114 ComplainAboutVoid = true;
6115 } else if (rpointee->isFunctionType()) {
6116 if (getLangOptions().CPlusPlus) {
6117 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006118 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006119 return QualType();
6120 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006121
6122 // GNU extension: arithmetic on pointer to function
6123 if (!ComplainAboutFunc)
6124 ComplainAboutFunc = rex;
6125 } else if (!rpointee->isDependentType() &&
6126 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006127 PDiag(diag::err_typecheck_sub_ptr_object)
6128 << rex->getSourceRange()
6129 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006130 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006131
Eli Friedman168fe152009-05-16 13:54:38 +00006132 if (getLangOptions().CPlusPlus) {
6133 // Pointee types must be the same: C++ [expr.add]
6134 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6135 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6136 << lex->getType() << rex->getType()
6137 << lex->getSourceRange() << rex->getSourceRange();
6138 return QualType();
6139 }
6140 } else {
6141 // Pointee types must be compatible C99 6.5.6p3
6142 if (!Context.typesAreCompatible(
6143 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6144 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6145 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6146 << lex->getType() << rex->getType()
6147 << lex->getSourceRange() << rex->getSourceRange();
6148 return QualType();
6149 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006150 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006151
Douglas Gregorac1fb652009-03-24 19:52:54 +00006152 if (ComplainAboutVoid)
6153 Diag(Loc, diag::ext_gnu_void_ptr)
6154 << lex->getSourceRange() << rex->getSourceRange();
6155 if (ComplainAboutFunc)
6156 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006157 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006158 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006159
6160 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006161 return Context.getPointerDiffType();
6162 }
6163 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006164
Chris Lattner326f7572008-11-18 01:30:42 +00006165 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006166}
6167
Douglas Gregor0bf31402010-10-08 23:50:27 +00006168static bool isScopedEnumerationType(QualType T) {
6169 if (const EnumType *ET = dyn_cast<EnumType>(T))
6170 return ET->getDecl()->isScoped();
6171 return false;
6172}
6173
Chris Lattner2a3569b2008-04-07 05:30:13 +00006174// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00006175QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00006176 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006177 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006178 if (!lex->getType()->hasIntegerRepresentation() ||
6179 !rex->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006180 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006181
Douglas Gregor0bf31402010-10-08 23:50:27 +00006182 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6183 // hasIntegerRepresentation() above instead of this.
6184 if (isScopedEnumerationType(lex->getType()) ||
6185 isScopedEnumerationType(rex->getType())) {
6186 return InvalidOperands(Loc, lex, rex);
6187 }
6188
Nate Begemane46ee9a2009-10-25 02:26:48 +00006189 // Vector shifts promote their scalar inputs to vector type.
6190 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6191 return CheckVectorOperands(Loc, lex, rex);
6192
Chris Lattner5c11c412007-12-12 05:47:28 +00006193 // Shifts don't perform usual arithmetic conversions, they just do integer
6194 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00006195 QualType LHSTy = Context.isPromotableBitField(lex);
6196 if (LHSTy.isNull()) {
6197 LHSTy = lex->getType();
6198 if (LHSTy->isPromotableIntegerType())
6199 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006200 }
Chris Lattner3c133402007-12-13 07:28:16 +00006201 if (!isCompAssign)
John McCalle3027922010-08-25 11:45:40 +00006202 ImpCastExprToType(lex, LHSTy, CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006203
Chris Lattner5c11c412007-12-12 05:47:28 +00006204 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006205
Ryan Flynnf53fab82009-08-07 16:20:20 +00006206 // Sanity-check shift operands
6207 llvm::APSInt Right;
6208 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00006209 if (!rex->isValueDependent() &&
6210 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00006211 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00006212 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6213 else {
6214 llvm::APInt LeftBits(Right.getBitWidth(),
6215 Context.getTypeSize(lex->getType()));
6216 if (Right.uge(LeftBits))
6217 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6218 }
6219 }
6220
Chris Lattner5c11c412007-12-12 05:47:28 +00006221 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006222 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006223}
6224
Chandler Carruth17773fc2010-07-10 12:30:03 +00006225static bool IsWithinTemplateSpecialization(Decl *D) {
6226 if (DeclContext *DC = D->getDeclContext()) {
6227 if (isa<ClassTemplateSpecializationDecl>(DC))
6228 return true;
6229 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6230 return FD->isFunctionTemplateSpecialization();
6231 }
6232 return false;
6233}
6234
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006235// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00006236QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006237 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006238 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006239
Chris Lattner9a152e22009-12-05 05:40:13 +00006240 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00006241 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006242 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006243
Steve Naroff31090012007-07-16 21:54:35 +00006244 QualType lType = lex->getType();
6245 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006246
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006247 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006248 !(lType->isBlockPointerType() && isRelational) &&
6249 !lex->getLocStart().isMacroID() &&
6250 !rex->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006251 // For non-floating point types, check for self-comparisons of the form
6252 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6253 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006254 //
6255 // NOTE: Don't warn about comparison expressions resulting from macro
6256 // expansion. Also don't warn about comparisons which are only self
6257 // comparisons within a template specialization. The warnings should catch
6258 // obvious cases in the definition of the template anyways. The idea is to
6259 // warn when the typed comparison operator will always evaluate to the same
6260 // result.
John McCall34376a62010-12-04 03:47:34 +00006261 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6262 Expr *RHSStripped = rex->IgnoreParenImpCasts();
Chandler Carruth17773fc2010-07-10 12:30:03 +00006263 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006264 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006265 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006266 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006267 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6268 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006269 << (Opc == BO_EQ
6270 || Opc == BO_LE
6271 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006272 } else if (lType->isArrayType() && rType->isArrayType() &&
6273 !DRL->getDecl()->getType()->isReferenceType() &&
6274 !DRR->getDecl()->getType()->isReferenceType()) {
6275 // what is it always going to eval to?
6276 char always_evals_to;
6277 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006278 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006279 always_evals_to = 0; // false
6280 break;
John McCalle3027922010-08-25 11:45:40 +00006281 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006282 always_evals_to = 1; // true
6283 break;
6284 default:
6285 // best we can say is 'a constant'
6286 always_evals_to = 2; // e.g. array1 <= array2
6287 break;
6288 }
6289 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6290 << 1 // array
6291 << always_evals_to);
6292 }
6293 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006294 }
Mike Stump11289f42009-09-09 15:08:12 +00006295
Chris Lattner222b8bd2009-03-08 19:39:53 +00006296 if (isa<CastExpr>(LHSStripped))
6297 LHSStripped = LHSStripped->IgnoreParenCasts();
6298 if (isa<CastExpr>(RHSStripped))
6299 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006300
Chris Lattner222b8bd2009-03-08 19:39:53 +00006301 // Warn about comparisons against a string constant (unless the other
6302 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006303 Expr *literalString = 0;
6304 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006305 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006306 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006307 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006308 literalString = lex;
6309 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006310 } else if ((isa<StringLiteral>(RHSStripped) ||
6311 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006312 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006313 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006314 literalString = rex;
6315 literalStringStripped = RHSStripped;
6316 }
6317
6318 if (literalString) {
6319 std::string resultComparison;
6320 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006321 case BO_LT: resultComparison = ") < 0"; break;
6322 case BO_GT: resultComparison = ") > 0"; break;
6323 case BO_LE: resultComparison = ") <= 0"; break;
6324 case BO_GE: resultComparison = ") >= 0"; break;
6325 case BO_EQ: resultComparison = ") == 0"; break;
6326 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006327 default: assert(false && "Invalid comparison operator");
6328 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006329
Douglas Gregor49862b82010-01-12 23:18:54 +00006330 DiagRuntimeBehavior(Loc,
6331 PDiag(diag::warn_stringcompare)
6332 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006333 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006334 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006335 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006336
Douglas Gregorec170db2010-06-08 19:50:34 +00006337 // C99 6.5.8p3 / C99 6.5.9p4
6338 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6339 UsualArithmeticConversions(lex, rex);
6340 else {
6341 UsualUnaryConversions(lex);
6342 UsualUnaryConversions(rex);
6343 }
6344
6345 lType = lex->getType();
6346 rType = rex->getType();
6347
Douglas Gregorca63811b2008-11-19 03:25:36 +00006348 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00006349 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00006350
Chris Lattnerb620c342007-08-26 01:18:55 +00006351 if (isRelational) {
6352 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006353 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006354 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006355 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006356 if (lType->hasFloatingRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006357 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006358
Chris Lattnerb620c342007-08-26 01:18:55 +00006359 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006360 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006361 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006362
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006363 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006364 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006365 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006366 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006367
Douglas Gregorf267edd2010-06-15 21:38:40 +00006368 // All of the following pointer-related warnings are GCC extensions, except
6369 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006370 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006371 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006372 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006373 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006374 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006375
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006376 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006377 if (LCanPointeeTy == RCanPointeeTy)
6378 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006379 if (!isRelational &&
6380 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6381 // Valid unless comparison between non-null pointer and function pointer
6382 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006383 // In a SFINAE context, we treat this as a hard error to maintain
6384 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006385 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6386 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006387 Diag(Loc,
6388 isSFINAEContext()?
6389 diag::err_typecheck_comparison_of_fptr_to_void
6390 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006391 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006392
6393 if (isSFINAEContext())
6394 return QualType();
6395
John McCalle3027922010-08-25 11:45:40 +00006396 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006397 return ResultTy;
6398 }
6399 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006400
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006401 // C++ [expr.rel]p2:
6402 // [...] Pointer conversions (4.10) and qualification
6403 // conversions (4.4) are performed on pointer operands (or on
6404 // a pointer operand and a null pointer constant) to bring
6405 // them to their composite pointer type. [...]
6406 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006407 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006408 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006409 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006410 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006411 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006412 if (T.isNull()) {
6413 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6414 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6415 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006416 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006417 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006418 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006419 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006420 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006421 }
6422
John McCalle3027922010-08-25 11:45:40 +00006423 ImpCastExprToType(lex, T, CK_BitCast);
6424 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006425 return ResultTy;
6426 }
Eli Friedman16c209612009-08-23 00:27:47 +00006427 // C99 6.5.9p2 and C99 6.5.8p2
6428 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6429 RCanPointeeTy.getUnqualifiedType())) {
6430 // Valid unless a relational comparison of function pointers
6431 if (isRelational && LCanPointeeTy->isFunctionType()) {
6432 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6433 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6434 }
6435 } else if (!isRelational &&
6436 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6437 // Valid unless comparison between non-null pointer and function pointer
6438 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6439 && !LHSIsNull && !RHSIsNull) {
6440 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6441 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6442 }
6443 } else {
6444 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006445 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006446 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006447 }
Eli Friedman16c209612009-08-23 00:27:47 +00006448 if (LCanPointeeTy != RCanPointeeTy)
John McCalle3027922010-08-25 11:45:40 +00006449 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006450 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006451 }
Mike Stump11289f42009-09-09 15:08:12 +00006452
Sebastian Redl576fd422009-05-10 18:38:11 +00006453 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006454 // Comparison of nullptr_t with itself.
6455 if (lType->isNullPtrType() && rType->isNullPtrType())
6456 return ResultTy;
6457
Mike Stump11289f42009-09-09 15:08:12 +00006458 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006459 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006460 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006461 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006462 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006463 ImpCastExprToType(rex, lType,
6464 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006465 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006466 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006467 return ResultTy;
6468 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006469 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006470 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006471 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006472 ImpCastExprToType(lex, rType,
6473 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006474 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006475 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006476 return ResultTy;
6477 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006478
6479 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006480 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006481 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6482 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006483 // In addition, pointers to members can be compared, or a pointer to
6484 // member and a null pointer constant. Pointer to member conversions
6485 // (4.11) and qualification conversions (4.4) are performed to bring
6486 // them to a common type. If one operand is a null pointer constant,
6487 // the common type is the type of the other operand. Otherwise, the
6488 // common type is a pointer to member type similar (4.4) to the type
6489 // of one of the operands, with a cv-qualification signature (4.4)
6490 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006491 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006492 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006493 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006494 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006495 if (T.isNull()) {
6496 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006497 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006498 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006499 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006500 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006501 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006502 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006503 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006504 }
Mike Stump11289f42009-09-09 15:08:12 +00006505
John McCalle3027922010-08-25 11:45:40 +00006506 ImpCastExprToType(lex, T, CK_BitCast);
6507 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006508 return ResultTy;
6509 }
Sebastian Redl576fd422009-05-10 18:38:11 +00006510 }
Mike Stump11289f42009-09-09 15:08:12 +00006511
Steve Naroff081c7422008-09-04 15:10:53 +00006512 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00006513 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006514 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6515 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006516
Steve Naroff081c7422008-09-04 15:10:53 +00006517 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006518 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006519 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006520 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006521 }
John McCalle3027922010-08-25 11:45:40 +00006522 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006523 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006524 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00006525 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006526 if (!isRelational
6527 && ((lType->isBlockPointerType() && rType->isPointerType())
6528 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006529 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006530 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006531 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006532 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006533 ->getPointeeType()->isVoidType())))
6534 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6535 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006536 }
John McCalle3027922010-08-25 11:45:40 +00006537 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006538 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006539 }
Steve Naroff081c7422008-09-04 15:10:53 +00006540
Steve Naroff7cae42b2009-07-10 23:34:53 +00006541 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006542 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006543 const PointerType *LPT = lType->getAs<PointerType>();
6544 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006545 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00006546 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006547 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00006548 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006549
Steve Naroff753567f2008-11-17 19:49:16 +00006550 if (!LPtrToVoid && !RPtrToVoid &&
6551 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006552 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006553 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006554 }
John McCalle3027922010-08-25 11:45:40 +00006555 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006556 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006557 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006558 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006559 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006560 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6561 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006562 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006563 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006564 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006565 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006566 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6567 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006568 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006569 bool isError = false;
6570 if ((LHSIsNull && lType->isIntegerType()) ||
6571 (RHSIsNull && rType->isIntegerType())) {
6572 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006573 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006574 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006575 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006576 else if (getLangOptions().CPlusPlus) {
6577 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6578 isError = true;
6579 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006580 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006581
Chris Lattnerd99bd522009-08-23 00:03:44 +00006582 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006583 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00006584 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006585 if (isError)
6586 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006587 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006588
6589 if (lType->isIntegerType())
John McCalle84af4e2010-11-13 01:35:44 +00006590 ImpCastExprToType(lex, rType,
6591 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006592 else
John McCalle84af4e2010-11-13 01:35:44 +00006593 ImpCastExprToType(rex, lType,
6594 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006595 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006596 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006597
Steve Naroff4b191572008-09-04 16:56:14 +00006598 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006599 if (!isRelational && RHSIsNull
6600 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00006601 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006602 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006603 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006604 if (!isRelational && LHSIsNull
6605 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00006606 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006607 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006608 }
Chris Lattner326f7572008-11-18 01:30:42 +00006609 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006610}
6611
Nate Begeman191a6b12008-07-14 18:02:46 +00006612/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006613/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006614/// like a scalar comparison, a vector comparison produces a vector of integer
6615/// types.
6616QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00006617 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006618 bool isRelational) {
6619 // Check to make sure we're operating on vectors of the same type and width,
6620 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00006621 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00006622 if (vType.isNull())
6623 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006624
Anton Yartsev3f8f2882010-11-18 03:19:30 +00006625 // If AltiVec, the comparison results in a numeric type, i.e.
6626 // bool for C++, int for C
6627 if (getLangOptions().AltiVec)
6628 return (getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy);
6629
Nate Begeman191a6b12008-07-14 18:02:46 +00006630 QualType lType = lex->getType();
6631 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006632
Nate Begeman191a6b12008-07-14 18:02:46 +00006633 // For non-floating point types, check for self-comparisons of the form
6634 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6635 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006636 if (!lType->hasFloatingRepresentation()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006637 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
6638 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
6639 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregorec170db2010-06-08 19:50:34 +00006640 DiagRuntimeBehavior(Loc,
6641 PDiag(diag::warn_comparison_always)
6642 << 0 // self-
6643 << 2 // "a constant"
6644 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006645 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006646
Nate Begeman191a6b12008-07-14 18:02:46 +00006647 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006648 if (!isRelational && lType->hasFloatingRepresentation()) {
6649 assert (rType->hasFloatingRepresentation());
Chris Lattner326f7572008-11-18 01:30:42 +00006650 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00006651 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006652
Nate Begeman191a6b12008-07-14 18:02:46 +00006653 // Return the type for the comparison, which is the same as vector type for
6654 // integer vectors, or an integer type of identical size and number of
6655 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006656 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00006657 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006658
John McCall9dd450b2009-09-21 23:43:11 +00006659 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006660 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006661 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006662 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006663 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006664 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6665
Mike Stump4e1f26a2009-02-19 03:04:26 +00006666 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006667 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006668 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6669}
6670
Steve Naroff218bc2b2007-05-04 21:54:46 +00006671inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00006672 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006673 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6674 if (lex->getType()->hasIntegerRepresentation() &&
6675 rex->getType()->hasIntegerRepresentation())
6676 return CheckVectorOperands(Loc, lex, rex);
6677
6678 return InvalidOperands(Loc, lex, rex);
6679 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006680
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006681 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006682
Douglas Gregor0bf31402010-10-08 23:50:27 +00006683 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
6684 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006685 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00006686 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006687}
6688
Steve Naroff218bc2b2007-05-04 21:54:46 +00006689inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner8406c512010-07-13 19:41:32 +00006690 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
6691
6692 // Diagnose cases where the user write a logical and/or but probably meant a
6693 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6694 // is a constant.
6695 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman6b197e02010-07-27 19:14:53 +00006696 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00006697 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00006698 !Loc.isMacroID()) {
6699 // If the RHS can be constant folded, and if it constant folds to something
6700 // that isn't 0 or 1 (which indicate a potential logical operation that
6701 // happened to fold to true/false) then warn.
6702 Expr::EvalResult Result;
6703 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
6704 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
6705 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6706 << rex->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00006707 << (Opc == BO_LAnd ? "&&" : "||")
6708 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00006709 }
6710 }
Chris Lattner8406c512010-07-13 19:41:32 +00006711
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006712 if (!Context.getLangOptions().CPlusPlus) {
6713 UsualUnaryConversions(lex);
6714 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006715
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006716 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
6717 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006718
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006719 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006720 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006721
John McCall4a2429a2010-06-04 00:29:51 +00006722 // The following is safe because we only use this method for
6723 // non-overloadable operands.
6724
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006725 // C++ [expr.log.and]p1
6726 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006727 // The operands are both contextually converted to type bool.
6728 if (PerformContextuallyConvertToBool(lex) ||
6729 PerformContextuallyConvertToBool(rex))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006730 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006731
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006732 // C++ [expr.log.and]p2
6733 // C++ [expr.log.or]p2
6734 // The result is a bool.
6735 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006736}
6737
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006738/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6739/// is a read-only property; return true if so. A readonly property expression
6740/// depends on various declarations and thus must be treated specially.
6741///
Mike Stump11289f42009-09-09 15:08:12 +00006742static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006743 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6744 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006745 if (PropExpr->isImplicitProperty()) return false;
6746
6747 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6748 QualType BaseType = PropExpr->isSuperReceiver() ?
6749 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006750 PropExpr->getBase()->getType();
6751
John McCallb7bd14f2010-12-02 01:19:52 +00006752 if (const ObjCObjectPointerType *OPT =
6753 BaseType->getAsObjCInterfacePointerType())
6754 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6755 if (S.isPropertyReadonly(PDecl, IFace))
6756 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006757 }
6758 return false;
6759}
6760
Chris Lattner30bd3272008-11-18 01:22:49 +00006761/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6762/// emit an error and return true. If so, return false.
6763static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006764 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006765 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006766 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006767 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6768 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00006769 if (IsLV == Expr::MLV_Valid)
6770 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006771
Chris Lattner30bd3272008-11-18 01:22:49 +00006772 unsigned Diag = 0;
6773 bool NeedType = false;
6774 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00006775 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006776 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006777 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6778 NeedType = true;
6779 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006780 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006781 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6782 NeedType = true;
6783 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006784 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006785 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6786 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006787 case Expr::MLV_Valid:
6788 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006789 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006790 case Expr::MLV_MemberFunction:
6791 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006792 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6793 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006794 case Expr::MLV_IncompleteType:
6795 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006796 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006797 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006798 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006799 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006800 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6801 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006802 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006803 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6804 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006805 case Expr::MLV_ReadonlyProperty:
6806 Diag = diag::error_readonly_property_assignment;
6807 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006808 case Expr::MLV_NoSetterProperty:
6809 Diag = diag::error_nosetter_property_assignment;
6810 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006811 case Expr::MLV_SubObjCPropertySetting:
6812 Diag = diag::error_no_subobject_property_setting;
6813 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006814 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006815
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006816 SourceRange Assign;
6817 if (Loc != OrigLoc)
6818 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006819 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006820 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006821 else
Mike Stump11289f42009-09-09 15:08:12 +00006822 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006823 return true;
6824}
6825
6826
6827
6828// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00006829QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
6830 SourceLocation Loc,
6831 QualType CompoundType) {
6832 // Verify that LHS is a modifiable lvalue, and emit error if not.
6833 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00006834 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00006835
6836 QualType LHSType = LHS->getType();
6837 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006838 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00006839 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006840 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006841 // Simple assignment "x = y".
John McCall34376a62010-12-04 03:47:34 +00006842 if (LHS->getObjectKind() == OK_ObjCProperty)
6843 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006844 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006845 // Special case of NSObject attributes on c-style pointer types.
6846 if (ConvTy == IncompatiblePointer &&
6847 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006848 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006849 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006850 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006851 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006852
John McCall7decc9e2010-11-18 06:31:45 +00006853 if (ConvTy == Compatible &&
6854 getLangOptions().ObjCNonFragileABI &&
6855 LHSType->isObjCObjectType())
6856 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6857 << LHSType;
6858
Chris Lattnerea714382008-08-21 18:04:13 +00006859 // If the RHS is a unary plus or minus, check to see if they = and + are
6860 // right next to each other. If so, the user may have typo'd "x =+ 4"
6861 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00006862 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00006863 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6864 RHSCheck = ICE->getSubExpr();
6865 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00006866 if ((UO->getOpcode() == UO_Plus ||
6867 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00006868 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00006869 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00006870 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6871 // And there is a space or other character before the subexpr of the
6872 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00006873 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6874 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006875 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00006876 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00006877 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00006878 }
Chris Lattnerea714382008-08-21 18:04:13 +00006879 }
6880 } else {
6881 // Compound assignment "x += y"
John McCall29600e12010-11-16 02:32:08 +00006882 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006883 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006884
Chris Lattner326f7572008-11-18 01:30:42 +00006885 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006886 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00006887 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006888
Chris Lattner39561062010-07-07 06:14:23 +00006889
6890 // Check to see if the destination operand is a dereferenced null pointer. If
6891 // so, and if not volatile-qualified, this is undefined behavior that the
6892 // optimizer will delete, so warn about it. People sometimes try to use this
6893 // to get a deterministic trap and are surprised by clang's behavior. This
6894 // only handles the pattern "*null = whatever", which is a very syntactic
6895 // check.
6896 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCalle3027922010-08-25 11:45:40 +00006897 if (UO->getOpcode() == UO_Deref &&
Chris Lattner39561062010-07-07 06:14:23 +00006898 UO->getSubExpr()->IgnoreParenCasts()->
6899 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
6900 !UO->getType().isVolatileQualified()) {
6901 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
6902 << UO->getSubExpr()->getSourceRange();
6903 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
6904 }
6905
Steve Naroff98cf3e92007-06-06 18:38:38 +00006906 // C99 6.5.16p3: The type of an assignment expression is the type of the
6907 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00006908 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00006909 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6910 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00006911 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00006912 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00006913 return (getLangOptions().CPlusPlus
6914 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00006915}
6916
Chris Lattner326f7572008-11-18 01:30:42 +00006917// C99 6.5.17
John McCall34376a62010-12-04 03:47:34 +00006918static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00006919 SourceLocation Loc) {
6920 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00006921
John McCall4bc41ae2010-11-18 19:01:18 +00006922 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006923 if (LHSResult.isInvalid())
6924 return QualType();
6925
John McCall4bc41ae2010-11-18 19:01:18 +00006926 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006927 if (RHSResult.isInvalid())
6928 return QualType();
6929 RHS = RHSResult.take();
6930
John McCall73d36182010-10-12 07:14:40 +00006931 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
6932 // operands, but not unary promotions.
6933 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00006934
John McCall34376a62010-12-04 03:47:34 +00006935 // So we treat the LHS as a ignored value, and in C++ we allow the
6936 // containing site to determine what should be done with the RHS.
6937 S.IgnoredValueConversions(LHS);
6938
6939 if (!S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00006940 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCall73d36182010-10-12 07:14:40 +00006941 if (!RHS->getType()->isVoidType())
John McCall4bc41ae2010-11-18 19:01:18 +00006942 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00006943 }
Eli Friedmanba961a92009-03-23 00:24:07 +00006944
Chris Lattner326f7572008-11-18 01:30:42 +00006945 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00006946}
6947
Steve Naroff7a5af782007-07-13 16:58:59 +00006948/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6949/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00006950static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
6951 ExprValueKind &VK,
6952 SourceLocation OpLoc,
6953 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006954 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00006955 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006956
Chris Lattner6b0cf142008-11-21 07:05:48 +00006957 QualType ResType = Op->getType();
6958 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00006959
John McCall4bc41ae2010-11-18 19:01:18 +00006960 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00006961 // Decrement of bool is not allowed.
6962 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00006963 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00006964 return QualType();
6965 }
6966 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00006967 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00006968 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006969 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00006970 } else if (ResType->isAnyPointerType()) {
6971 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006972
Chris Lattner6b0cf142008-11-21 07:05:48 +00006973 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00006974 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00006975 if (S.getLangOptions().CPlusPlus) {
6976 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006977 << Op->getSourceRange();
6978 return QualType();
6979 }
6980
6981 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00006982 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006983 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00006984 if (S.getLangOptions().CPlusPlus) {
6985 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006986 << Op->getType() << Op->getSourceRange();
6987 return QualType();
6988 }
6989
John McCall4bc41ae2010-11-18 19:01:18 +00006990 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006991 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00006992 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
6993 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00006994 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006995 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00006996 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006997 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00006998 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
6999 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007000 << PointeeTy << Op->getSourceRange();
7001 return QualType();
7002 }
Eli Friedman090addd2010-01-03 00:20:48 +00007003 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007004 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007005 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007006 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007007 } else if (ResType->isPlaceholderType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007008 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007009 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007010 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7011 isInc, isPrefix);
Chris Lattner6b0cf142008-11-21 07:05:48 +00007012 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007013 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007014 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007015 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007016 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007017 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007018 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007019 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007020 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007021 // In C++, a prefix increment is the same type as the operand. Otherwise
7022 // (in C or with postfix), the increment is the unqualified type of the
7023 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007024 if (isPrefix && S.getLangOptions().CPlusPlus) {
7025 VK = VK_LValue;
7026 return ResType;
7027 } else {
7028 VK = VK_RValue;
7029 return ResType.getUnqualifiedType();
7030 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007031}
7032
John McCall34376a62010-12-04 03:47:34 +00007033void Sema::ConvertPropertyForRValue(Expr *&E) {
7034 assert(E->getValueKind() == VK_LValue &&
7035 E->getObjectKind() == OK_ObjCProperty);
7036 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7037
7038 ExprValueKind VK = VK_RValue;
7039 if (PRE->isImplicitProperty()) {
7040 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7041 VK = Expr::getValueKindForType(Result);
7042 }
7043
7044 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7045 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007046
7047 ExprResult Result = MaybeBindToTemporary(E);
7048 if (!Result.isInvalid())
7049 E = Result.take();
John McCall34376a62010-12-04 03:47:34 +00007050}
7051
7052void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7053 assert(LHS->getValueKind() == VK_LValue &&
7054 LHS->getObjectKind() == OK_ObjCProperty);
7055 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7056
7057 if (PRE->isImplicitProperty()) {
7058 // If using property-dot syntax notation for assignment, and there is a
7059 // setter, RHS expression is being passed to the setter argument. So,
7060 // type conversion (and comparison) is RHS to setter's argument type.
7061 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7062 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7063 LHSTy = (*P)->getType();
7064
7065 // Otherwise, if the getter returns an l-value, just call that.
7066 } else {
7067 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7068 ExprValueKind VK = Expr::getValueKindForType(Result);
7069 if (VK == VK_LValue) {
7070 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7071 CK_GetObjCProperty, LHS, 0, VK);
7072 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007073 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007074 }
John McCall34376a62010-12-04 03:47:34 +00007075 }
7076
7077 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007078 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007079 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007080 Expr *Arg = RHS;
7081 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7082 Owned(Arg));
7083 if (!ArgE.isInvalid())
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007084 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007085 }
7086}
7087
7088
Anders Carlsson806700f2008-02-01 07:15:58 +00007089/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007090/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007091/// where the declaration is needed for type checking. We only need to
7092/// handle cases when the expression references a function designator
7093/// or is an lvalue. Here are some examples:
7094/// - &(x) => x
7095/// - &*****f => f for f a function designator.
7096/// - &s.xx => s
7097/// - &s.zz[1].yy -> s, if zz is an array
7098/// - *(x + 1) -> x, if x is an array
7099/// - &"123"[2] -> 0
7100/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007101static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007102 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007103 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007104 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007105 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007106 // If this is an arrow operator, the address is an offset from
7107 // the base's value, so the object the base refers to is
7108 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007109 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007110 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007111 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007112 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007113 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007114 // FIXME: This code shouldn't be necessary! We should catch the implicit
7115 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007116 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7117 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7118 if (ICE->getSubExpr()->getType()->isArrayType())
7119 return getPrimaryDecl(ICE->getSubExpr());
7120 }
7121 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007122 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007123 case Stmt::UnaryOperatorClass: {
7124 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007125
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007126 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007127 case UO_Real:
7128 case UO_Imag:
7129 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007130 return getPrimaryDecl(UO->getSubExpr());
7131 default:
7132 return 0;
7133 }
7134 }
Steve Naroff47500512007-04-19 23:00:49 +00007135 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007136 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007137 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007138 // If the result of an implicit cast is an l-value, we care about
7139 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007140 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007141 default:
7142 return 0;
7143 }
7144}
7145
7146/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007147/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007148/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007149/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007150/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007151/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007152/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007153static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7154 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007155 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007156 return S.Context.DependentTy;
7157 if (OrigOp->getType() == S.Context.OverloadTy)
7158 return S.Context.OverloadTy;
John McCall8d08b9b2010-08-27 09:08:28 +00007159
John McCall4bc41ae2010-11-18 19:01:18 +00007160 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007161 if (PR.isInvalid()) return QualType();
7162 OrigOp = PR.take();
7163
John McCall8d08b9b2010-08-27 09:08:28 +00007164 // Make sure to ignore parentheses in subsequent checks
7165 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007166
John McCall4bc41ae2010-11-18 19:01:18 +00007167 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007168 // Implement C99-only parts of addressof rules.
7169 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007170 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007171 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7172 // (assuming the deref expression is valid).
7173 return uOp->getSubExpr()->getType();
7174 }
7175 // Technically, there should be a check for array subscript
7176 // expressions here, but the result of one is always an lvalue anyway.
7177 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007178 NamedDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007179 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007180
Chris Lattner9156f1b2010-07-05 19:17:26 +00007181 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007182 bool sfinae = S.isSFINAEContext();
7183 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7184 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007185 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007186 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007187 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007188 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007189 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007190 } else if (lval == Expr::LV_MemberFunction) {
7191 // If it's an instance method, make a member pointer.
7192 // The expression must have exactly the form &A::foo.
7193
7194 // If the underlying expression isn't a decl ref, give up.
7195 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007196 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007197 << OrigOp->getSourceRange();
7198 return QualType();
7199 }
7200 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7201 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7202
7203 // The id-expression was parenthesized.
7204 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007205 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007206 << OrigOp->getSourceRange();
7207
7208 // The method was named without a qualifier.
7209 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007210 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007211 << op->getSourceRange();
7212 }
7213
John McCall4bc41ae2010-11-18 19:01:18 +00007214 return S.Context.getMemberPointerType(op->getType(),
7215 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007216 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007217 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007218 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007219 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007220 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007221 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007222 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007223 return QualType();
7224 }
John McCall086a4642010-11-24 05:12:34 +00007225 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007226 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007227 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007228 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007229 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007230 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007231 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007232 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007233 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007234 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007235 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007236 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007237 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007238 << "property expression" << op->getSourceRange();
7239 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007240 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007241 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007242 // with the register storage-class specifier.
7243 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007244 // in C++ it is not error to take address of a register
7245 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007246 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007247 !S.getLangOptions().CPlusPlus) {
7248 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007249 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007250 return QualType();
7251 }
John McCalld14a8642009-11-21 08:51:07 +00007252 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007253 return S.Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00007254 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007255 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007256 // Could be a pointer to member, though, if there is an explicit
7257 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007258 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007259 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007260 if (Ctx && Ctx->isRecord()) {
7261 if (FD->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007262 S.Diag(OpLoc,
7263 diag::err_cannot_form_pointer_to_member_of_reference_type)
Anders Carlsson0b675f52009-07-08 21:45:58 +00007264 << FD->getDeclName() << FD->getType();
7265 return QualType();
7266 }
Mike Stump11289f42009-09-09 15:08:12 +00007267
John McCall4bc41ae2010-11-18 19:01:18 +00007268 return S.Context.getMemberPointerType(op->getType(),
7269 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007270 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007271 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007272 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007273 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007274 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007275
Eli Friedmance7f9002009-05-16 23:27:50 +00007276 if (lval == Expr::LV_IncompleteVoidType) {
7277 // Taking the address of a void variable is technically illegal, but we
7278 // allow it in cases which are otherwise valid.
7279 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007280 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007281 }
7282
Steve Naroff47500512007-04-19 23:00:49 +00007283 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007284 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007285 return S.Context.getObjCObjectPointerType(op->getType());
7286 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007287}
7288
Chris Lattner9156f1b2010-07-05 19:17:26 +00007289/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007290static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7291 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007292 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007293 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007294
John McCall4bc41ae2010-11-18 19:01:18 +00007295 S.UsualUnaryConversions(Op);
Chris Lattner9156f1b2010-07-05 19:17:26 +00007296 QualType OpTy = Op->getType();
7297 QualType Result;
7298
7299 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7300 // is an incomplete type or void. It would be possible to warn about
7301 // dereferencing a void pointer, but it's completely well-defined, and such a
7302 // warning is unlikely to catch any mistakes.
7303 if (const PointerType *PT = OpTy->getAs<PointerType>())
7304 Result = PT->getPointeeType();
7305 else if (const ObjCObjectPointerType *OPT =
7306 OpTy->getAs<ObjCObjectPointerType>())
7307 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007308 else {
John McCall4bc41ae2010-11-18 19:01:18 +00007309 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007310 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007311 if (PR.take() != Op)
7312 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007313 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007314
Chris Lattner9156f1b2010-07-05 19:17:26 +00007315 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007316 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007317 << OpTy << Op->getSourceRange();
7318 return QualType();
7319 }
John McCall4bc41ae2010-11-18 19:01:18 +00007320
7321 // Dereferences are usually l-values...
7322 VK = VK_LValue;
7323
7324 // ...except that certain expressions are never l-values in C.
7325 if (!S.getLangOptions().CPlusPlus &&
7326 IsCForbiddenLValueType(S.Context, Result))
7327 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007328
7329 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007330}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007331
John McCalle3027922010-08-25 11:45:40 +00007332static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007333 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007334 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007335 switch (Kind) {
7336 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007337 case tok::periodstar: Opc = BO_PtrMemD; break;
7338 case tok::arrowstar: Opc = BO_PtrMemI; break;
7339 case tok::star: Opc = BO_Mul; break;
7340 case tok::slash: Opc = BO_Div; break;
7341 case tok::percent: Opc = BO_Rem; break;
7342 case tok::plus: Opc = BO_Add; break;
7343 case tok::minus: Opc = BO_Sub; break;
7344 case tok::lessless: Opc = BO_Shl; break;
7345 case tok::greatergreater: Opc = BO_Shr; break;
7346 case tok::lessequal: Opc = BO_LE; break;
7347 case tok::less: Opc = BO_LT; break;
7348 case tok::greaterequal: Opc = BO_GE; break;
7349 case tok::greater: Opc = BO_GT; break;
7350 case tok::exclaimequal: Opc = BO_NE; break;
7351 case tok::equalequal: Opc = BO_EQ; break;
7352 case tok::amp: Opc = BO_And; break;
7353 case tok::caret: Opc = BO_Xor; break;
7354 case tok::pipe: Opc = BO_Or; break;
7355 case tok::ampamp: Opc = BO_LAnd; break;
7356 case tok::pipepipe: Opc = BO_LOr; break;
7357 case tok::equal: Opc = BO_Assign; break;
7358 case tok::starequal: Opc = BO_MulAssign; break;
7359 case tok::slashequal: Opc = BO_DivAssign; break;
7360 case tok::percentequal: Opc = BO_RemAssign; break;
7361 case tok::plusequal: Opc = BO_AddAssign; break;
7362 case tok::minusequal: Opc = BO_SubAssign; break;
7363 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7364 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7365 case tok::ampequal: Opc = BO_AndAssign; break;
7366 case tok::caretequal: Opc = BO_XorAssign; break;
7367 case tok::pipeequal: Opc = BO_OrAssign; break;
7368 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007369 }
7370 return Opc;
7371}
7372
John McCalle3027922010-08-25 11:45:40 +00007373static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007374 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007375 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007376 switch (Kind) {
7377 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007378 case tok::plusplus: Opc = UO_PreInc; break;
7379 case tok::minusminus: Opc = UO_PreDec; break;
7380 case tok::amp: Opc = UO_AddrOf; break;
7381 case tok::star: Opc = UO_Deref; break;
7382 case tok::plus: Opc = UO_Plus; break;
7383 case tok::minus: Opc = UO_Minus; break;
7384 case tok::tilde: Opc = UO_Not; break;
7385 case tok::exclaim: Opc = UO_LNot; break;
7386 case tok::kw___real: Opc = UO_Real; break;
7387 case tok::kw___imag: Opc = UO_Imag; break;
7388 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007389 }
7390 return Opc;
7391}
7392
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007393/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7394/// operator @p Opc at location @c TokLoc. This routine only supports
7395/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007396ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007397 unsigned Op,
7398 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007399 QualType ResultTy; // Result type of the binary operator.
John McCalle3027922010-08-25 11:45:40 +00007400 BinaryOperatorKind Opc = (BinaryOperatorKind) Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007401 // The following two variables are used for compound assignment operators
7402 QualType CompLHSTy; // Type of LHS after promotions for computation
7403 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007404 ExprValueKind VK = VK_RValue;
7405 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007406
7407 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007408 case BO_Assign:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007409 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007410 if (getLangOptions().CPlusPlus &&
7411 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall4bc41ae2010-11-18 19:01:18 +00007412 VK = lhs->getValueKind();
7413 OK = lhs->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007414 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007415 break;
John McCalle3027922010-08-25 11:45:40 +00007416 case BO_PtrMemD:
7417 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007418 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007419 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007420 break;
John McCalle3027922010-08-25 11:45:40 +00007421 case BO_Mul:
7422 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007423 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007424 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007425 break;
John McCalle3027922010-08-25 11:45:40 +00007426 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007427 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7428 break;
John McCalle3027922010-08-25 11:45:40 +00007429 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007430 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7431 break;
John McCalle3027922010-08-25 11:45:40 +00007432 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007433 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7434 break;
John McCalle3027922010-08-25 11:45:40 +00007435 case BO_Shl:
7436 case BO_Shr:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007437 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
7438 break;
John McCalle3027922010-08-25 11:45:40 +00007439 case BO_LE:
7440 case BO_LT:
7441 case BO_GE:
7442 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007443 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007444 break;
John McCalle3027922010-08-25 11:45:40 +00007445 case BO_EQ:
7446 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007447 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007448 break;
John McCalle3027922010-08-25 11:45:40 +00007449 case BO_And:
7450 case BO_Xor:
7451 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007452 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7453 break;
John McCalle3027922010-08-25 11:45:40 +00007454 case BO_LAnd:
7455 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007456 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007457 break;
John McCalle3027922010-08-25 11:45:40 +00007458 case BO_MulAssign:
7459 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007460 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007461 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007462 CompLHSTy = CompResultTy;
7463 if (!CompResultTy.isNull())
7464 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007465 break;
John McCalle3027922010-08-25 11:45:40 +00007466 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007467 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7468 CompLHSTy = CompResultTy;
7469 if (!CompResultTy.isNull())
7470 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007471 break;
John McCalle3027922010-08-25 11:45:40 +00007472 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007473 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7474 if (!CompResultTy.isNull())
7475 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007476 break;
John McCalle3027922010-08-25 11:45:40 +00007477 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007478 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7479 if (!CompResultTy.isNull())
7480 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007481 break;
John McCalle3027922010-08-25 11:45:40 +00007482 case BO_ShlAssign:
7483 case BO_ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007484 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
7485 CompLHSTy = CompResultTy;
7486 if (!CompResultTy.isNull())
7487 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007488 break;
John McCalle3027922010-08-25 11:45:40 +00007489 case BO_AndAssign:
7490 case BO_XorAssign:
7491 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007492 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7493 CompLHSTy = CompResultTy;
7494 if (!CompResultTy.isNull())
7495 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007496 break;
John McCalle3027922010-08-25 11:45:40 +00007497 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007498 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCall7decc9e2010-11-18 06:31:45 +00007499 if (getLangOptions().CPlusPlus) {
7500 VK = rhs->getValueKind();
7501 OK = rhs->getObjectKind();
7502 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007503 break;
7504 }
7505 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007506 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007507 if (CompResultTy.isNull())
John McCall7decc9e2010-11-18 06:31:45 +00007508 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
7509 VK, OK, OpLoc));
7510
John McCall34376a62010-12-04 03:47:34 +00007511 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007512 VK = VK_LValue;
7513 OK = lhs->getObjectKind();
7514 }
7515 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
7516 VK, OK, CompLHSTy,
7517 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007518}
7519
Sebastian Redl44615072009-10-27 12:10:02 +00007520/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
7521/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007522static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7523 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007524 const PartialDiagnostic &FirstNote,
7525 SourceRange FirstParenRange,
7526 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00007527 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007528 Self.Diag(Loc, PD);
7529
7530 if (!FirstNote.getDiagID())
7531 return;
7532
7533 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
7534 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7535 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007536 return;
7537 }
7538
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007539 Self.Diag(Loc, FirstNote)
7540 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00007541 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007542
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007543 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007544 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007545
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007546 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
7547 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7548 // We can't display the parentheses, so just dig the
7549 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007550 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007551 return;
7552 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007553
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007554 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00007555 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
7556 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007557}
7558
Sebastian Redl44615072009-10-27 12:10:02 +00007559/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7560/// operators are mixed in a way that suggests that the programmer forgot that
7561/// comparison operators have higher precedence. The most typical example of
7562/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007563static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007564 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007565 typedef BinaryOperator BinOp;
7566 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7567 rhsopc = static_cast<BinOp::Opcode>(-1);
7568 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007569 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007570 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007571 rhsopc = BO->getOpcode();
7572
7573 // Subs are not binary operators.
7574 if (lhsopc == -1 && rhsopc == -1)
7575 return;
7576
7577 // Bitwise operations are sometimes used as eager logical ops.
7578 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007579 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7580 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007581 return;
7582
Sebastian Redl44615072009-10-27 12:10:02 +00007583 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007584 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007585 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00007586 << SourceRange(lhs->getLocStart(), OpLoc)
7587 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00007588 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007589 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007590 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
7591 Self.PDiag(diag::note_precedence_bitwise_silence)
7592 << BinOp::getOpcodeStr(lhsopc),
7593 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00007594 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007595 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007596 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00007597 << SourceRange(OpLoc, rhs->getLocEnd())
7598 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00007599 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007600 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007601 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
7602 Self.PDiag(diag::note_precedence_bitwise_silence)
7603 << BinOp::getOpcodeStr(rhsopc),
7604 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00007605}
7606
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007607/// \brief It accepts a '&&' expr that is inside a '||' one.
7608/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7609/// in parentheses.
7610static void
7611EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
7612 Expr *E) {
7613 assert(isa<BinaryOperator>(E) &&
7614 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
7615 SuggestParentheses(Self, OpLoc,
7616 Self.PDiag(diag::warn_logical_and_in_logical_or)
7617 << E->getSourceRange(),
7618 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
7619 E->getSourceRange(),
7620 Self.PDiag(0), SourceRange());
7621}
7622
7623/// \brief Returns true if the given expression can be evaluated as a constant
7624/// 'true'.
7625static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7626 bool Res;
7627 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7628}
7629
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007630/// \brief Returns true if the given expression can be evaluated as a constant
7631/// 'false'.
7632static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7633 bool Res;
7634 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7635}
7636
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007637/// \brief Look for '&&' in the left hand of a '||' expr.
7638static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007639 Expr *OrLHS, Expr *OrRHS) {
7640 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007641 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007642 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7643 if (EvaluatesAsFalse(S, OrRHS))
7644 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007645 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7646 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7647 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7648 } else if (Bop->getOpcode() == BO_LOr) {
7649 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7650 // If it's "a || b && 1 || c" we didn't warn earlier for
7651 // "a || b && 1", but warn now.
7652 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7653 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7654 }
7655 }
7656 }
7657}
7658
7659/// \brief Look for '&&' in the right hand of a '||' expr.
7660static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007661 Expr *OrLHS, Expr *OrRHS) {
7662 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007663 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007664 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7665 if (EvaluatesAsFalse(S, OrLHS))
7666 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007667 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7668 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7669 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007670 }
7671 }
7672}
7673
Sebastian Redl43028242009-10-26 15:24:15 +00007674/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007675/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007676static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007677 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007678 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007679 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007680 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7681
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007682 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7683 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007684 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007685 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7686 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007687 }
Sebastian Redl43028242009-10-26 15:24:15 +00007688}
7689
Steve Naroff218bc2b2007-05-04 21:54:46 +00007690// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007691ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00007692 tok::TokenKind Kind,
7693 Expr *lhs, Expr *rhs) {
7694 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00007695 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7696 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00007697
Sebastian Redl43028242009-10-26 15:24:15 +00007698 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7699 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7700
Douglas Gregor5287f092009-11-05 00:51:44 +00007701 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7702}
7703
John McCalldadc5752010-08-24 06:29:42 +00007704ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007705 BinaryOperatorKind Opc,
7706 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00007707 if (getLangOptions().CPlusPlus) {
7708 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007709
John McCall622114c2010-12-06 05:26:58 +00007710 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7711 UseBuiltinOperator = false;
7712 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7713 UseBuiltinOperator = true;
7714 } else {
7715 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7716 !rhs->getType()->isOverloadableType();
7717 }
7718
7719 if (!UseBuiltinOperator) {
7720 // Find all of the overloaded operators visible from this
7721 // point. We perform both an operator-name lookup from the local
7722 // scope and an argument-dependent lookup based on the types of
7723 // the arguments.
7724 UnresolvedSet<16> Functions;
7725 OverloadedOperatorKind OverOp
7726 = BinaryOperator::getOverloadedOperator(Opc);
7727 if (S && OverOp != OO_None)
7728 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7729 Functions);
7730
7731 // Build the (potentially-overloaded, potentially-dependent)
7732 // binary operation.
7733 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7734 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00007735 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007736
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007737 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00007738 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007739}
7740
John McCalldadc5752010-08-24 06:29:42 +00007741ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
John McCall36226622010-10-12 02:09:17 +00007742 unsigned OpcIn,
7743 Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00007744 UnaryOperatorKind Opc = static_cast<UnaryOperatorKind>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00007745
John McCall7decc9e2010-11-18 06:31:45 +00007746 ExprValueKind VK = VK_RValue;
7747 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00007748 QualType resultType;
7749 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007750 case UO_PreInc:
7751 case UO_PreDec:
7752 case UO_PostInc:
7753 case UO_PostDec:
John McCall4bc41ae2010-11-18 19:01:18 +00007754 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007755 Opc == UO_PreInc ||
7756 Opc == UO_PostInc,
7757 Opc == UO_PreInc ||
7758 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00007759 break;
John McCalle3027922010-08-25 11:45:40 +00007760 case UO_AddrOf:
John McCall4bc41ae2010-11-18 19:01:18 +00007761 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007762 break;
John McCalle3027922010-08-25 11:45:40 +00007763 case UO_Deref:
Douglas Gregorb92a1562010-02-03 00:27:59 +00007764 DefaultFunctionArrayLvalueConversion(Input);
John McCall4bc41ae2010-11-18 19:01:18 +00007765 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007766 break;
John McCalle3027922010-08-25 11:45:40 +00007767 case UO_Plus:
7768 case UO_Minus:
Steve Naroff31090012007-07-16 21:54:35 +00007769 UsualUnaryConversions(Input);
7770 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007771 if (resultType->isDependentType())
7772 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00007773 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7774 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00007775 break;
7776 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7777 resultType->isEnumeralType())
7778 break;
7779 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00007780 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00007781 resultType->isPointerType())
7782 break;
John McCall36226622010-10-12 02:09:17 +00007783 else if (resultType->isPlaceholderType()) {
7784 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7785 if (PR.isInvalid()) return ExprError();
7786 return CreateBuiltinUnaryOp(OpLoc, OpcIn, PR.take());
7787 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007788
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007789 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7790 << resultType << Input->getSourceRange());
John McCalle3027922010-08-25 11:45:40 +00007791 case UO_Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00007792 UsualUnaryConversions(Input);
7793 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007794 if (resultType->isDependentType())
7795 break;
Chris Lattner0d707612008-07-25 23:52:49 +00007796 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
7797 if (resultType->isComplexType() || resultType->isComplexIntegerType())
7798 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00007799 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007800 << resultType << Input->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007801 else if (resultType->hasIntegerRepresentation())
7802 break;
7803 else if (resultType->isPlaceholderType()) {
7804 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7805 if (PR.isInvalid()) return ExprError();
7806 return CreateBuiltinUnaryOp(OpLoc, OpcIn, PR.take());
7807 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007808 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7809 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007810 }
Steve Naroff35d85152007-05-07 00:24:15 +00007811 break;
John McCalle3027922010-08-25 11:45:40 +00007812 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00007813 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00007814 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00007815 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007816 if (resultType->isDependentType())
7817 break;
John McCall36226622010-10-12 02:09:17 +00007818 if (resultType->isScalarType()) { // C99 6.5.3.3p1
7819 // ok, fallthrough
7820 } else if (resultType->isPlaceholderType()) {
7821 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7822 if (PR.isInvalid()) return ExprError();
7823 return CreateBuiltinUnaryOp(OpLoc, OpcIn, PR.take());
7824 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007825 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7826 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007827 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00007828
Chris Lattnerbe31ed82007-06-02 19:11:33 +00007829 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007830 // In C++, it's bool. C++ 5.3.1p8
7831 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00007832 break;
John McCalle3027922010-08-25 11:45:40 +00007833 case UO_Real:
7834 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00007835 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00007836 // _Real and _Imag map ordinary l-values into ordinary l-values.
7837 if (Input->getValueKind() != VK_RValue &&
7838 Input->getObjectKind() == OK_Ordinary)
7839 VK = Input->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00007840 break;
John McCalle3027922010-08-25 11:45:40 +00007841 case UO_Extension:
Chris Lattner86554282007-06-08 22:32:33 +00007842 resultType = Input->getType();
John McCall7decc9e2010-11-18 06:31:45 +00007843 VK = Input->getValueKind();
7844 OK = Input->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00007845 break;
Steve Naroff35d85152007-05-07 00:24:15 +00007846 }
7847 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007848 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00007849
John McCall7decc9e2010-11-18 06:31:45 +00007850 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
7851 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00007852}
Chris Lattnereefa10e2007-05-28 06:56:27 +00007853
John McCalldadc5752010-08-24 06:29:42 +00007854ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007855 UnaryOperatorKind Opc,
7856 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00007857 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00007858 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007859 // Find all of the overloaded operators visible from this
7860 // point. We perform both an operator-name lookup from the local
7861 // scope and an argument-dependent lookup based on the types of
7862 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00007863 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00007864 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00007865 if (S && OverOp != OO_None)
7866 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
7867 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007868
John McCallb268a282010-08-23 23:25:46 +00007869 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007870 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007871
John McCallb268a282010-08-23 23:25:46 +00007872 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007873}
7874
Douglas Gregor5287f092009-11-05 00:51:44 +00007875// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007876ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00007877 tok::TokenKind Op, Expr *Input) {
7878 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00007879}
7880
Steve Naroff66356bd2007-09-16 14:56:35 +00007881/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
John McCalldadc5752010-08-24 06:29:42 +00007882ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007883 SourceLocation LabLoc,
7884 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00007885 // Look up the record for this label identifier.
John McCallaab3e412010-08-25 08:40:02 +00007886 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00007887
Daniel Dunbar88402ce2008-08-04 16:51:22 +00007888 // If we haven't seen this label yet, create a forward reference. It
7889 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00007890 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00007891 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007892
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00007893 LabelDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00007894 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007895 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
7896 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00007897}
7898
John McCalldadc5752010-08-24 06:29:42 +00007899ExprResult
John McCallb268a282010-08-23 23:25:46 +00007900Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007901 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00007902 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
7903 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
7904
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00007905 bool isFileScope
7906 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00007907 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007908 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00007909
Chris Lattner366727f2007-07-24 16:58:17 +00007910 // FIXME: there are a variety of strange constraints to enforce here, for
7911 // example, it is not possible to goto into a stmt expression apparently.
7912 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007913
Chris Lattner366727f2007-07-24 16:58:17 +00007914 // If there are sub stmts in the compound stmt, take the type of the last one
7915 // as the type of the stmtexpr.
7916 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007917 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00007918 if (!Compound->body_empty()) {
7919 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007920 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00007921 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007922 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
7923 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00007924 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007925 }
7926 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00007927 // Do function/array conversion on the last expression, but not
7928 // lvalue-to-rvalue. However, initialize an unqualified type.
7929 DefaultFunctionArrayConversion(LastExpr);
7930 Ty = LastExpr->getType().getUnqualifiedType();
7931
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007932 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
7933 ExprResult Res = PerformCopyInitialization(
7934 InitializedEntity::InitializeResult(LPLoc,
7935 Ty,
7936 false),
7937 SourceLocation(),
7938 Owned(LastExpr));
7939 if (Res.isInvalid())
7940 return ExprError();
7941 if ((LastExpr = Res.takeAs<Expr>())) {
7942 if (!LastLabelStmt)
7943 Compound->setLastStmt(LastExpr);
7944 else
7945 LastLabelStmt->setSubStmt(LastExpr);
7946 StmtExprMayBindToTemp = true;
7947 }
7948 }
7949 }
Chris Lattner944d3062008-07-26 19:51:01 +00007950 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007951
Eli Friedmanba961a92009-03-23 00:24:07 +00007952 // FIXME: Check that expression type is complete/non-abstract; statement
7953 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007954 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
7955 if (StmtExprMayBindToTemp)
7956 return MaybeBindToTemporary(ResStmtExpr);
7957 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00007958}
Steve Naroff78864672007-08-01 22:05:33 +00007959
John McCalldadc5752010-08-24 06:29:42 +00007960ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00007961 TypeSourceInfo *TInfo,
7962 OffsetOfComponent *CompPtr,
7963 unsigned NumComponents,
7964 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007965 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007966 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00007967 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00007968
Chris Lattnerf17bd422007-08-30 17:45:32 +00007969 // We must have at least one component that refers to the type, and the first
7970 // one is known to be a field designator. Verify that the ArgTy represents
7971 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007972 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00007973 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
7974 << ArgTy << TypeRange);
7975
7976 // Type must be complete per C99 7.17p3 because a declaring a variable
7977 // with an incomplete type would be ill-formed.
7978 if (!Dependent
7979 && RequireCompleteType(BuiltinLoc, ArgTy,
7980 PDiag(diag::err_offsetof_incomplete_type)
7981 << TypeRange))
7982 return ExprError();
7983
Chris Lattner78502cf2007-08-31 21:49:13 +00007984 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
7985 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00007986 // FIXME: This diagnostic isn't actually visible because the location is in
7987 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00007988 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00007989 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
7990 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00007991
7992 bool DidWarnAboutNonPOD = false;
7993 QualType CurrentType = ArgTy;
7994 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
7995 llvm::SmallVector<OffsetOfNode, 4> Comps;
7996 llvm::SmallVector<Expr*, 4> Exprs;
7997 for (unsigned i = 0; i != NumComponents; ++i) {
7998 const OffsetOfComponent &OC = CompPtr[i];
7999 if (OC.isBrackets) {
8000 // Offset of an array sub-field. TODO: Should we allow vector elements?
8001 if (!CurrentType->isDependentType()) {
8002 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8003 if(!AT)
8004 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8005 << CurrentType);
8006 CurrentType = AT->getElementType();
8007 } else
8008 CurrentType = Context.DependentTy;
8009
8010 // The expression must be an integral expression.
8011 // FIXME: An integral constant expression?
8012 Expr *Idx = static_cast<Expr*>(OC.U.E);
8013 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8014 !Idx->getType()->isIntegerType())
8015 return ExprError(Diag(Idx->getLocStart(),
8016 diag::err_typecheck_subscript_not_integer)
8017 << Idx->getSourceRange());
8018
8019 // Record this array index.
8020 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8021 Exprs.push_back(Idx);
8022 continue;
8023 }
8024
8025 // Offset of a field.
8026 if (CurrentType->isDependentType()) {
8027 // We have the offset of a field, but we can't look into the dependent
8028 // type. Just record the identifier of the field.
8029 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8030 CurrentType = Context.DependentTy;
8031 continue;
8032 }
8033
8034 // We need to have a complete type to look into.
8035 if (RequireCompleteType(OC.LocStart, CurrentType,
8036 diag::err_offsetof_incomplete_type))
8037 return ExprError();
8038
8039 // Look for the designated field.
8040 const RecordType *RC = CurrentType->getAs<RecordType>();
8041 if (!RC)
8042 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8043 << CurrentType);
8044 RecordDecl *RD = RC->getDecl();
8045
8046 // C++ [lib.support.types]p5:
8047 // The macro offsetof accepts a restricted set of type arguments in this
8048 // International Standard. type shall be a POD structure or a POD union
8049 // (clause 9).
8050 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8051 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8052 DiagRuntimeBehavior(BuiltinLoc,
8053 PDiag(diag::warn_offsetof_non_pod_type)
8054 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8055 << CurrentType))
8056 DidWarnAboutNonPOD = true;
8057 }
8058
8059 // Look for the field.
8060 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8061 LookupQualifiedName(R, RD);
8062 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008063 IndirectFieldDecl *IndirectMemberDecl = 0;
8064 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008065 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008066 MemberDecl = IndirectMemberDecl->getAnonField();
8067 }
8068
Douglas Gregor882211c2010-04-28 22:16:22 +00008069 if (!MemberDecl)
8070 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8071 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8072 OC.LocEnd));
8073
Douglas Gregor10982ea2010-04-28 22:36:06 +00008074 // C99 7.17p3:
8075 // (If the specified member is a bit-field, the behavior is undefined.)
8076 //
8077 // We diagnose this as an error.
8078 if (MemberDecl->getBitWidth()) {
8079 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8080 << MemberDecl->getDeclName()
8081 << SourceRange(BuiltinLoc, RParenLoc);
8082 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8083 return ExprError();
8084 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008085
8086 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008087 if (IndirectMemberDecl)
8088 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008089
Douglas Gregord1702062010-04-29 00:18:15 +00008090 // If the member was found in a base class, introduce OffsetOfNodes for
8091 // the base class indirections.
8092 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8093 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008094 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008095 CXXBasePath &Path = Paths.front();
8096 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8097 B != BEnd; ++B)
8098 Comps.push_back(OffsetOfNode(B->Base));
8099 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008100
Francois Pichet783dd6e2010-11-21 06:08:52 +00008101 if (IndirectMemberDecl) {
8102 for (IndirectFieldDecl::chain_iterator FI =
8103 IndirectMemberDecl->chain_begin(),
8104 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8105 assert(isa<FieldDecl>(*FI));
8106 Comps.push_back(OffsetOfNode(OC.LocStart,
8107 cast<FieldDecl>(*FI), OC.LocEnd));
8108 }
8109 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008110 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008111
Douglas Gregor882211c2010-04-28 22:16:22 +00008112 CurrentType = MemberDecl->getType().getNonReferenceType();
8113 }
8114
8115 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8116 TInfo, Comps.data(), Comps.size(),
8117 Exprs.data(), Exprs.size(), RParenLoc));
8118}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008119
John McCalldadc5752010-08-24 06:29:42 +00008120ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008121 SourceLocation BuiltinLoc,
8122 SourceLocation TypeLoc,
8123 ParsedType argty,
8124 OffsetOfComponent *CompPtr,
8125 unsigned NumComponents,
8126 SourceLocation RPLoc) {
8127
Douglas Gregor882211c2010-04-28 22:16:22 +00008128 TypeSourceInfo *ArgTInfo;
8129 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8130 if (ArgTy.isNull())
8131 return ExprError();
8132
Eli Friedman06dcfd92010-08-05 10:15:45 +00008133 if (!ArgTInfo)
8134 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8135
8136 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8137 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008138}
8139
8140
John McCalldadc5752010-08-24 06:29:42 +00008141ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008142 Expr *CondExpr,
8143 Expr *LHSExpr, Expr *RHSExpr,
8144 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008145 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8146
John McCall7decc9e2010-11-18 06:31:45 +00008147 ExprValueKind VK = VK_RValue;
8148 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008149 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008150 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008151 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008152 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008153 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008154 } else {
8155 // The conditional expression is required to be a constant expression.
8156 llvm::APSInt condEval(32);
8157 SourceLocation ExpLoc;
8158 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008159 return ExprError(Diag(ExpLoc,
8160 diag::err_typecheck_choose_expr_requires_constant)
8161 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008162
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008163 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008164 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8165
8166 resType = ActiveExpr->getType();
8167 ValueDependent = ActiveExpr->isValueDependent();
8168 VK = ActiveExpr->getValueKind();
8169 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008170 }
8171
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008172 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008173 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008174 resType->isDependentType(),
8175 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008176}
8177
Steve Naroffc540d662008-09-03 18:15:37 +00008178//===----------------------------------------------------------------------===//
8179// Clang Extensions.
8180//===----------------------------------------------------------------------===//
8181
8182/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008183void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008184 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8185 PushBlockScope(BlockScope, Block);
8186 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008187 if (BlockScope)
8188 PushDeclContext(BlockScope, Block);
8189 else
8190 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008191}
8192
Mike Stump82f071f2009-02-04 22:31:32 +00008193void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008194 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Douglas Gregor9a28e842010-03-01 23:15:13 +00008195 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008196
John McCall8cb7bdf2010-06-04 23:28:52 +00008197 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCalla3ccba02010-06-04 11:21:44 +00008198 CurBlock->TheDecl->setSignatureAsWritten(Sig);
John McCall8cb7bdf2010-06-04 23:28:52 +00008199 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008200
John McCall8e346702010-06-04 19:02:56 +00008201 bool isVariadic;
John McCalla3ccba02010-06-04 11:21:44 +00008202 QualType RetTy;
8203 if (const FunctionType *Fn = T->getAs<FunctionType>()) {
John McCall8e346702010-06-04 19:02:56 +00008204 CurBlock->FunctionType = T;
John McCalla3ccba02010-06-04 11:21:44 +00008205 RetTy = Fn->getResultType();
John McCall8e346702010-06-04 19:02:56 +00008206 isVariadic =
John McCalla3ccba02010-06-04 11:21:44 +00008207 !isa<FunctionProtoType>(Fn) || cast<FunctionProtoType>(Fn)->isVariadic();
8208 } else {
8209 RetTy = T;
John McCall8e346702010-06-04 19:02:56 +00008210 isVariadic = false;
John McCalla3ccba02010-06-04 11:21:44 +00008211 }
Mike Stump11289f42009-09-09 15:08:12 +00008212
John McCall8e346702010-06-04 19:02:56 +00008213 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008214
John McCalla3ccba02010-06-04 11:21:44 +00008215 // Don't allow returning an array by value.
8216 if (RetTy->isArrayType()) {
8217 Diag(ParamInfo.getSourceRange().getBegin(), diag::err_block_returns_array);
Mike Stump82f071f2009-02-04 22:31:32 +00008218 return;
8219 }
8220
John McCalla3ccba02010-06-04 11:21:44 +00008221 // Don't allow returning a objc interface by value.
8222 if (RetTy->isObjCObjectType()) {
8223 Diag(ParamInfo.getSourceRange().getBegin(),
8224 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8225 return;
8226 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008227
John McCalla3ccba02010-06-04 11:21:44 +00008228 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008229 // return type. TODO: what should we do with declarators like:
8230 // ^ * { ... }
8231 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008232 if (RetTy != Context.DependentTy)
8233 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008234
John McCalla3ccba02010-06-04 11:21:44 +00008235 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00008236 llvm::SmallVector<ParmVarDecl*, 8> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00008237 if (isa<FunctionProtoType>(T.IgnoreParens())) {
8238 FunctionProtoTypeLoc TL
8239 = cast<FunctionProtoTypeLoc>(Sig->getTypeLoc().IgnoreParens());
John McCalla3ccba02010-06-04 11:21:44 +00008240 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
8241 ParmVarDecl *Param = TL.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008242 if (Param->getIdentifier() == 0 &&
8243 !Param->isImplicit() &&
8244 !Param->isInvalidDecl() &&
8245 !getLangOptions().CPlusPlus)
8246 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008247 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008248 }
John McCalla3ccba02010-06-04 11:21:44 +00008249
8250 // Fake up parameter variables if we have a typedef, like
8251 // ^ fntype { ... }
8252 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8253 for (FunctionProtoType::arg_type_iterator
8254 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8255 ParmVarDecl *Param =
8256 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8257 ParamInfo.getSourceRange().getBegin(),
8258 *I);
John McCall8e346702010-06-04 19:02:56 +00008259 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008260 }
Steve Naroffc540d662008-09-03 18:15:37 +00008261 }
John McCalla3ccba02010-06-04 11:21:44 +00008262
John McCall8e346702010-06-04 19:02:56 +00008263 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008264 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008265 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008266 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8267 CurBlock->TheDecl->param_end(),
8268 /*CheckParameterNames=*/false);
8269 }
8270
John McCalla3ccba02010-06-04 11:21:44 +00008271 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008272 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008273
John McCall8e346702010-06-04 19:02:56 +00008274 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008275 Diag(ParamInfo.getAttributes()->getLoc(),
8276 diag::warn_attribute_sentinel_not_variadic) << 1;
8277 // FIXME: remove the attribute.
8278 }
8279
8280 // Put the parameter variables in scope. We can bail out immediately
8281 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008282 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008283 return;
8284
John McCalldf8b37c2010-03-22 09:20:08 +00008285 bool ShouldCheckShadow =
8286 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
8287
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008288 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008289 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8290 (*AI)->setOwningFunction(CurBlock->TheDecl);
8291
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008292 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008293 if ((*AI)->getIdentifier()) {
8294 if (ShouldCheckShadow)
8295 CheckShadow(CurBlock->TheScope, *AI);
8296
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008297 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008298 }
John McCallf7b2fb52010-01-22 00:28:27 +00008299 }
Steve Naroffc540d662008-09-03 18:15:37 +00008300}
8301
8302/// ActOnBlockError - If there is an error parsing a block, this callback
8303/// is invoked to pop the information about the block from the action impl.
8304void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008305 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008306 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008307 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008308}
8309
8310/// ActOnBlockStmtExpr - This is called when the body of a block statement
8311/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008312ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
John McCallb268a282010-08-23 23:25:46 +00008313 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008314 // If blocks are disabled, emit an error.
8315 if (!LangOpts.Blocks)
8316 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008317
Douglas Gregor9a28e842010-03-01 23:15:13 +00008318 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008319
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008320 PopDeclContext();
8321
Steve Naroffc540d662008-09-03 18:15:37 +00008322 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008323 if (!BSI->ReturnType.isNull())
8324 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008325
Mike Stump3bf1ab42009-07-28 22:04:01 +00008326 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008327 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008328
8329 // If the user wrote a function type in some form, try to use that.
8330 if (!BSI->FunctionType.isNull()) {
8331 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8332
8333 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8334 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8335
8336 // Turn protoless block types into nullary block types.
8337 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008338 FunctionProtoType::ExtProtoInfo EPI;
8339 EPI.ExtInfo = Ext;
8340 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008341
8342 // Otherwise, if we don't need to change anything about the function type,
8343 // preserve its sugar structure.
8344 } else if (FTy->getResultType() == RetTy &&
8345 (!NoReturn || FTy->getNoReturnAttr())) {
8346 BlockTy = BSI->FunctionType;
8347
8348 // Otherwise, make the minimal modifications to the function type.
8349 } else {
8350 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008351 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8352 EPI.TypeQuals = 0; // FIXME: silently?
8353 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008354 BlockTy = Context.getFunctionType(RetTy,
8355 FPT->arg_type_begin(),
8356 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008357 EPI);
John McCall8e346702010-06-04 19:02:56 +00008358 }
8359
8360 // If we don't have a function type, just build one from nothing.
8361 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008362 FunctionProtoType::ExtProtoInfo EPI;
8363 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
8364 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008365 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008366
John McCall8e346702010-06-04 19:02:56 +00008367 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8368 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008369 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008370
Chris Lattner45542ea2009-04-19 05:28:12 +00008371 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00008372 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008373 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008374
John McCallb268a282010-08-23 23:25:46 +00008375 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Mike Stump314825b2010-01-19 23:08:01 +00008376
8377 bool Good = true;
8378 // Check goto/label use.
8379 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
8380 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
8381 LabelStmt *L = I->second;
8382
8383 // Verify that we have no forward references left. If so, there was a goto
8384 // or address of a label taken, but no definition of it.
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00008385 if (L->getSubStmt() != 0) {
8386 if (!L->isUsed())
8387 Diag(L->getIdentLoc(), diag::warn_unused_label) << L->getName();
Mike Stump314825b2010-01-19 23:08:01 +00008388 continue;
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00008389 }
Mike Stump314825b2010-01-19 23:08:01 +00008390
8391 // Emit error.
8392 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
8393 Good = false;
8394 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00008395 if (!Good) {
8396 PopFunctionOrBlockScope();
Mike Stump314825b2010-01-19 23:08:01 +00008397 return ExprError();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008398 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008399
John McCall1d570a72010-08-25 05:56:39 +00008400 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
8401 BSI->hasBlockDeclRefExprs);
8402
Ted Kremenek918fe842010-03-20 21:06:02 +00008403 // Issue any analysis-based warnings.
Ted Kremenek0b405322010-03-23 00:13:23 +00008404 const sema::AnalysisBasedWarnings::Policy &WP =
8405 AnalysisWarnings.getDefaultPolicy();
John McCall1d570a72010-08-25 05:56:39 +00008406 AnalysisWarnings.IssueWarnings(WP, Result);
Ted Kremenek918fe842010-03-20 21:06:02 +00008407
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008408 PopFunctionOrBlockScope();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008409 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008410}
8411
John McCalldadc5752010-08-24 06:29:42 +00008412ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008413 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008414 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008415 TypeSourceInfo *TInfo;
8416 QualType T = GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008417 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008418}
8419
John McCalldadc5752010-08-24 06:29:42 +00008420ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008421 Expr *E, TypeSourceInfo *TInfo,
8422 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008423 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008424
Eli Friedman121ba0c2008-08-09 23:32:40 +00008425 // Get the va_list type
8426 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008427 if (VaListType->isArrayType()) {
8428 // Deal with implicit array decay; for example, on x86-64,
8429 // va_list is an array, but it's supposed to decay to
8430 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008431 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008432 // Make sure the input expression also decays appropriately.
8433 UsualUnaryConversions(E);
8434 } else {
8435 // Otherwise, the va_list argument must be an l-value because
8436 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008437 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008438 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008439 return ExprError();
8440 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008441
Douglas Gregorad3150c2009-05-19 23:10:31 +00008442 if (!E->isTypeDependent() &&
8443 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008444 return ExprError(Diag(E->getLocStart(),
8445 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008446 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008447 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008448
Eli Friedmanba961a92009-03-23 00:24:07 +00008449 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008450 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008451
Abramo Bagnara27db2392010-08-10 10:06:15 +00008452 QualType T = TInfo->getType().getNonLValueExprType(Context);
8453 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008454}
8455
John McCalldadc5752010-08-24 06:29:42 +00008456ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008457 // The type of __null will be int or long, depending on the size of
8458 // pointers on the target.
8459 QualType Ty;
8460 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
8461 Ty = Context.IntTy;
8462 else
8463 Ty = Context.LongTy;
8464
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008465 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008466}
8467
Alexis Huntc46382e2010-04-28 23:02:27 +00008468static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008469 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008470 if (!SemaRef.getLangOptions().ObjC1)
8471 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008472
Anders Carlssonace5d072009-11-10 04:46:30 +00008473 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8474 if (!PT)
8475 return;
8476
8477 // Check if the destination is of type 'id'.
8478 if (!PT->isObjCIdType()) {
8479 // Check if the destination is the 'NSString' interface.
8480 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8481 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8482 return;
8483 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008484
Anders Carlssonace5d072009-11-10 04:46:30 +00008485 // Strip off any parens and casts.
8486 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8487 if (!SL || SL->isWide())
8488 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008489
Douglas Gregora771f462010-03-31 17:46:05 +00008490 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008491}
8492
Chris Lattner9bad62c2008-01-04 18:04:52 +00008493bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8494 SourceLocation Loc,
8495 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008496 Expr *SrcExpr, AssignmentAction Action,
8497 bool *Complained) {
8498 if (Complained)
8499 *Complained = false;
8500
Chris Lattner9bad62c2008-01-04 18:04:52 +00008501 // Decode the result (notice that AST's are still created for extensions).
8502 bool isInvalid = false;
8503 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008504 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008505
Chris Lattner9bad62c2008-01-04 18:04:52 +00008506 switch (ConvTy) {
8507 default: assert(0 && "Unknown conversion type");
8508 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008509 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008510 DiagKind = diag::ext_typecheck_convert_pointer_int;
8511 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008512 case IntToPointer:
8513 DiagKind = diag::ext_typecheck_convert_int_pointer;
8514 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008515 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008516 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008517 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
8518 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008519 case IncompatiblePointerSign:
8520 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8521 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008522 case FunctionVoidPointer:
8523 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8524 break;
8525 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008526 // If the qualifiers lost were because we were applying the
8527 // (deprecated) C++ conversion from a string literal to a char*
8528 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8529 // Ideally, this check would be performed in
8530 // CheckPointerTypesForAssignment. However, that would require a
8531 // bit of refactoring (so that the second argument is an
8532 // expression, rather than a type), which should be done as part
8533 // of a larger effort to fix CheckPointerTypesForAssignment for
8534 // C++ semantics.
8535 if (getLangOptions().CPlusPlus &&
8536 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8537 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008538 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8539 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008540 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008541 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008542 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008543 case IntToBlockPointer:
8544 DiagKind = diag::err_int_to_block_pointer;
8545 break;
8546 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008547 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008548 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008549 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008550 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008551 // it can give a more specific diagnostic.
8552 DiagKind = diag::warn_incompatible_qualified_id;
8553 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008554 case IncompatibleVectors:
8555 DiagKind = diag::warn_incompatible_vectors;
8556 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008557 case Incompatible:
8558 DiagKind = diag::err_typecheck_convert_incompatible;
8559 isInvalid = true;
8560 break;
8561 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008562
Douglas Gregorc68e1402010-04-09 00:35:39 +00008563 QualType FirstType, SecondType;
8564 switch (Action) {
8565 case AA_Assigning:
8566 case AA_Initializing:
8567 // The destination type comes first.
8568 FirstType = DstType;
8569 SecondType = SrcType;
8570 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00008571
Douglas Gregorc68e1402010-04-09 00:35:39 +00008572 case AA_Returning:
8573 case AA_Passing:
8574 case AA_Converting:
8575 case AA_Sending:
8576 case AA_Casting:
8577 // The source type comes first.
8578 FirstType = SrcType;
8579 SecondType = DstType;
8580 break;
8581 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008582
Douglas Gregorc68e1402010-04-09 00:35:39 +00008583 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00008584 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008585 if (Complained)
8586 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008587 return isInvalid;
8588}
Anders Carlssone54e8a12008-11-30 19:50:32 +00008589
Chris Lattnerc71d08b2009-04-25 21:59:05 +00008590bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008591 llvm::APSInt ICEResult;
8592 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8593 if (Result)
8594 *Result = ICEResult;
8595 return false;
8596 }
8597
Anders Carlssone54e8a12008-11-30 19:50:32 +00008598 Expr::EvalResult EvalResult;
8599
Mike Stump4e1f26a2009-02-19 03:04:26 +00008600 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00008601 EvalResult.HasSideEffects) {
8602 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8603
8604 if (EvalResult.Diag) {
8605 // We only show the note if it's not the usual "invalid subexpression"
8606 // or if it's actually in a subexpression.
8607 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8608 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8609 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8610 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008611
Anders Carlssone54e8a12008-11-30 19:50:32 +00008612 return true;
8613 }
8614
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008615 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8616 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00008617
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008618 if (EvalResult.Diag &&
8619 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
8620 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008621
Anders Carlssone54e8a12008-11-30 19:50:32 +00008622 if (Result)
8623 *Result = EvalResult.Val.getInt();
8624 return false;
8625}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008626
Douglas Gregorff790f12009-11-26 00:44:06 +00008627void
Mike Stump11289f42009-09-09 15:08:12 +00008628Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008629 ExprEvalContexts.push_back(
8630 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008631}
8632
Mike Stump11289f42009-09-09 15:08:12 +00008633void
Douglas Gregorff790f12009-11-26 00:44:06 +00008634Sema::PopExpressionEvaluationContext() {
8635 // Pop the current expression evaluation context off the stack.
8636 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8637 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008638
Douglas Gregorfab31f42009-12-12 07:57:52 +00008639 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8640 if (Rec.PotentiallyReferenced) {
8641 // Mark any remaining declarations in the current position of the stack
8642 // as "referenced". If they were not meant to be referenced, semantic
8643 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008644 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00008645 I = Rec.PotentiallyReferenced->begin(),
8646 IEnd = Rec.PotentiallyReferenced->end();
8647 I != IEnd; ++I)
8648 MarkDeclarationReferenced(I->first, I->second);
8649 }
8650
8651 if (Rec.PotentiallyDiagnosed) {
8652 // Emit any pending diagnostics.
8653 for (PotentiallyEmittedDiagnostics::iterator
8654 I = Rec.PotentiallyDiagnosed->begin(),
8655 IEnd = Rec.PotentiallyDiagnosed->end();
8656 I != IEnd; ++I)
8657 Diag(I->first, I->second);
8658 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008659 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008660
8661 // When are coming out of an unevaluated context, clear out any
8662 // temporaries that we may have created as part of the evaluation of
8663 // the expression in that context: they aren't relevant because they
8664 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008665 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00008666 ExprTemporaries.size() > Rec.NumTemporaries)
8667 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
8668 ExprTemporaries.end());
8669
8670 // Destroy the popped expression evaluation record.
8671 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008672}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008673
8674/// \brief Note that the given declaration was referenced in the source code.
8675///
8676/// This routine should be invoke whenever a given declaration is referenced
8677/// in the source code, and where that reference occurred. If this declaration
8678/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
8679/// C99 6.9p3), then the declaration will be marked as used.
8680///
8681/// \param Loc the location where the declaration was referenced.
8682///
8683/// \param D the declaration that has been referenced by the source code.
8684void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
8685 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00008686
Douglas Gregorebada0772010-06-17 23:14:26 +00008687 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00008688 return;
Mike Stump11289f42009-09-09 15:08:12 +00008689
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00008690 // Mark a parameter or variable declaration "used", regardless of whether we're in a
8691 // template or not. The reason for this is that unevaluated expressions
8692 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
8693 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008694 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008695 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00008696 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008697 return;
8698 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008699
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008700 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
8701 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00008702
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008703 // Do not mark anything as "used" within a dependent context; wait for
8704 // an instantiation.
8705 if (CurContext->isDependentContext())
8706 return;
Mike Stump11289f42009-09-09 15:08:12 +00008707
Douglas Gregorff790f12009-11-26 00:44:06 +00008708 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008709 case Unevaluated:
8710 // We are in an expression that is not potentially evaluated; do nothing.
8711 return;
Mike Stump11289f42009-09-09 15:08:12 +00008712
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008713 case PotentiallyEvaluated:
8714 // We are in a potentially-evaluated expression, so this declaration is
8715 // "used"; handle this below.
8716 break;
Mike Stump11289f42009-09-09 15:08:12 +00008717
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008718 case PotentiallyPotentiallyEvaluated:
8719 // We are in an expression that may be potentially evaluated; queue this
8720 // declaration reference until we know whether the expression is
8721 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00008722 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008723 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008724
8725 case PotentiallyEvaluatedIfUsed:
8726 // Referenced declarations will only be used if the construct in the
8727 // containing expression is used.
8728 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008729 }
Mike Stump11289f42009-09-09 15:08:12 +00008730
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008731 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00008732 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008733 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008734 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00008735 if (Constructor->getParent()->hasTrivialConstructor())
8736 return;
8737 if (!Constructor->isUsed(false))
8738 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00008739 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00008740 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008741 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008742 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
8743 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008744
Douglas Gregor88d292c2010-05-13 16:44:06 +00008745 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008746 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008747 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008748 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008749 if (Destructor->isVirtual())
8750 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008751 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
8752 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
8753 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008754 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00008755 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008756 } else if (MethodDecl->isVirtual())
8757 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008758 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00008759 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00008760 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00008761 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00008762 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00008763 bool AlreadyInstantiated = false;
8764 if (FunctionTemplateSpecializationInfo *SpecInfo
8765 = Function->getTemplateSpecializationInfo()) {
8766 if (SpecInfo->getPointOfInstantiation().isInvalid())
8767 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008768 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008769 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008770 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008771 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00008772 = Function->getMemberSpecializationInfo()) {
8773 if (MSInfo->getPointOfInstantiation().isInvalid())
8774 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008775 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008776 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008777 AlreadyInstantiated = true;
8778 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008779
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008780 if (!AlreadyInstantiated) {
8781 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
8782 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
8783 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
8784 Loc));
8785 else
Chandler Carruth54080172010-08-25 08:44:16 +00008786 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008787 }
Gabor Greifb6aba3e2010-08-28 00:16:06 +00008788 } else // Walk redefinitions, as some of them may be instantiable.
8789 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
8790 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00008791 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00008792 MarkDeclarationReferenced(Loc, *i);
8793 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008794
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008795 // FIXME: keep track of references to static functions
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00008796
8797 // Recursive functions should be marked when used from another function.
8798 if (CurContext != Function)
8799 Function->setUsed(true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008800
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008801 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00008802 }
Mike Stump11289f42009-09-09 15:08:12 +00008803
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008804 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008805 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00008806 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00008807 Var->getInstantiatedFromStaticDataMember()) {
8808 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
8809 assert(MSInfo && "Missing member specialization information?");
8810 if (MSInfo->getPointOfInstantiation().isInvalid() &&
8811 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
8812 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +00008813 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00008814 }
8815 }
Mike Stump11289f42009-09-09 15:08:12 +00008816
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008817 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008818
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008819 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008820 return;
Sam Weinigbae69142009-09-11 03:29:30 +00008821 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008822}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008823
Douglas Gregor5597ab42010-05-07 23:12:07 +00008824namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00008825 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00008826 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00008827 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00008828 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
8829 Sema &S;
8830 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00008831
Douglas Gregor5597ab42010-05-07 23:12:07 +00008832 public:
8833 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00008834
Douglas Gregor5597ab42010-05-07 23:12:07 +00008835 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00008836
8837 bool TraverseTemplateArgument(const TemplateArgument &Arg);
8838 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00008839 };
8840}
8841
Chandler Carruthaf80f662010-06-09 08:17:30 +00008842bool MarkReferencedDecls::TraverseTemplateArgument(
8843 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00008844 if (Arg.getKind() == TemplateArgument::Declaration) {
8845 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
8846 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00008847
8848 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00008849}
8850
Chandler Carruthaf80f662010-06-09 08:17:30 +00008851bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00008852 if (ClassTemplateSpecializationDecl *Spec
8853 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
8854 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008855 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00008856 }
8857
Chandler Carruthc65667c2010-06-10 10:31:57 +00008858 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00008859}
8860
8861void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
8862 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00008863 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00008864}
8865
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008866namespace {
8867 /// \brief Helper class that marks all of the declarations referenced by
8868 /// potentially-evaluated subexpressions as "referenced".
8869 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
8870 Sema &S;
8871
8872 public:
8873 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
8874
8875 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
8876
8877 void VisitDeclRefExpr(DeclRefExpr *E) {
8878 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
8879 }
8880
8881 void VisitMemberExpr(MemberExpr *E) {
8882 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00008883 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008884 }
8885
8886 void VisitCXXNewExpr(CXXNewExpr *E) {
8887 if (E->getConstructor())
8888 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
8889 if (E->getOperatorNew())
8890 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
8891 if (E->getOperatorDelete())
8892 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00008893 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008894 }
8895
8896 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
8897 if (E->getOperatorDelete())
8898 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00008899 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
8900 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
8901 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
8902 S.MarkDeclarationReferenced(E->getLocStart(),
8903 S.LookupDestructor(Record));
8904 }
8905
Douglas Gregor32b3de52010-09-11 23:32:50 +00008906 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008907 }
8908
8909 void VisitCXXConstructExpr(CXXConstructExpr *E) {
8910 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00008911 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008912 }
8913
8914 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
8915 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
8916 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00008917
8918 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
8919 Visit(E->getExpr());
8920 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008921 };
8922}
8923
8924/// \brief Mark any declarations that appear within this expression or any
8925/// potentially-evaluated subexpressions as "referenced".
8926void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
8927 EvaluatedExprMarker(*this).Visit(E);
8928}
8929
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008930/// \brief Emit a diagnostic that describes an effect on the run-time behavior
8931/// of the program being compiled.
8932///
8933/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008934/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008935/// possibility that the code will actually be executable. Code in sizeof()
8936/// expressions, code used only during overload resolution, etc., are not
8937/// potentially evaluated. This routine will suppress such diagnostics or,
8938/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008939/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008940/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008941///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008942/// This routine should be used for all diagnostics that describe the run-time
8943/// behavior of a program, such as passing a non-POD value through an ellipsis.
8944/// Failure to do so will likely result in spurious diagnostics or failures
8945/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008946bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008947 const PartialDiagnostic &PD) {
8948 switch (ExprEvalContexts.back().Context ) {
8949 case Unevaluated:
8950 // The argument will never be evaluated, so don't complain.
8951 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008952
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008953 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008954 case PotentiallyEvaluatedIfUsed:
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008955 Diag(Loc, PD);
8956 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008957
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008958 case PotentiallyPotentiallyEvaluated:
8959 ExprEvalContexts.back().addDiagnostic(Loc, PD);
8960 break;
8961 }
8962
8963 return false;
8964}
8965
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008966bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
8967 CallExpr *CE, FunctionDecl *FD) {
8968 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
8969 return false;
8970
8971 PartialDiagnostic Note =
8972 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
8973 << FD->getDeclName() : PDiag();
8974 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008975
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008976 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008977 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008978 PDiag(diag::err_call_function_incomplete_return)
8979 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008980 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008981 << CE->getSourceRange(),
8982 std::make_pair(NoteLoc, Note)))
8983 return true;
8984
8985 return false;
8986}
8987
John McCalld5707ab2009-10-12 21:59:07 +00008988// Diagnose the common s/=/==/ typo. Note that adding parentheses
8989// will prevent this condition from triggering, which is what we want.
8990void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
8991 SourceLocation Loc;
8992
John McCall0506e4a2009-11-11 02:41:58 +00008993 unsigned diagnostic = diag::warn_condition_is_assignment;
8994
John McCalld5707ab2009-10-12 21:59:07 +00008995 if (isa<BinaryOperator>(E)) {
8996 BinaryOperator *Op = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00008997 if (Op->getOpcode() != BO_Assign)
John McCalld5707ab2009-10-12 21:59:07 +00008998 return;
8999
John McCallb0e419e2009-11-12 00:06:05 +00009000 // Greylist some idioms by putting them into a warning subcategory.
9001 if (ObjCMessageExpr *ME
9002 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9003 Selector Sel = ME->getSelector();
9004
John McCallb0e419e2009-11-12 00:06:05 +00009005 // self = [<foo> init...]
9006 if (isSelfExpr(Op->getLHS())
9007 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
9008 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9009
9010 // <foo> = [<bar> nextObject]
9011 else if (Sel.isUnarySelector() &&
9012 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
9013 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9014 }
John McCall0506e4a2009-11-11 02:41:58 +00009015
John McCalld5707ab2009-10-12 21:59:07 +00009016 Loc = Op->getOperatorLoc();
9017 } else if (isa<CXXOperatorCallExpr>(E)) {
9018 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
9019 if (Op->getOperator() != OO_Equal)
9020 return;
9021
9022 Loc = Op->getOperatorLoc();
9023 } else {
9024 // Not an assignment.
9025 return;
9026 }
9027
John McCalld5707ab2009-10-12 21:59:07 +00009028 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00009029 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009030
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009031 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00009032 Diag(Loc, diag::note_condition_assign_to_comparison)
Douglas Gregora771f462010-03-31 17:46:05 +00009033 << FixItHint::CreateReplacement(Loc, "==");
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009034 Diag(Loc, diag::note_condition_assign_silence)
9035 << FixItHint::CreateInsertion(Open, "(")
9036 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +00009037}
9038
9039bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9040 DiagnoseAssignmentAsCondition(E);
9041
9042 if (!E->isTypeDependent()) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009043 if (E->isBoundMemberFunction(Context))
9044 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9045 << E->getSourceRange();
9046
John McCall34376a62010-12-04 03:47:34 +00009047 if (getLangOptions().CPlusPlus)
9048 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9049
9050 DefaultFunctionArrayLvalueConversion(E);
John McCall29cb2fd2010-12-04 06:09:13 +00009051
9052 QualType T = E->getType();
John McCall34376a62010-12-04 03:47:34 +00009053 if (!T->isScalarType()) // C99 6.8.4.1p1
9054 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9055 << T << E->getSourceRange();
John McCalld5707ab2009-10-12 21:59:07 +00009056 }
9057
9058 return false;
9059}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009060
John McCalldadc5752010-08-24 06:29:42 +00009061ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9062 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009063 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009064 return ExprError();
9065
Douglas Gregorb412e172010-07-25 18:17:45 +00009066 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00009067 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00009068
9069 return Owned(Sub);
9070}
John McCall36e7fe32010-10-12 00:20:44 +00009071
9072/// Check for operands with placeholder types and complain if found.
9073/// Returns true if there was an error and no recovery was possible.
9074ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9075 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9076 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9077
9078 // If this is overload, check for a single overload.
9079 if (BT->getKind() == BuiltinType::Overload) {
9080 if (FunctionDecl *Specialization
9081 = ResolveSingleFunctionTemplateSpecialization(E)) {
9082 // The access doesn't really matter in this case.
9083 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9084 Specialization->getAccess());
9085 E = FixOverloadedFunctionReference(E, Found, Specialization);
9086 if (!E) return ExprError();
9087 return Owned(E);
9088 }
9089
John McCall36226622010-10-12 02:09:17 +00009090 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
John McCall36e7fe32010-10-12 00:20:44 +00009091 return ExprError();
9092 }
9093
9094 // Otherwise it's a use of undeduced auto.
9095 assert(BT->getKind() == BuiltinType::UndeducedAuto);
9096
9097 DeclRefExpr *DRE = cast<DeclRefExpr>(E->IgnoreParens());
9098 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
9099 << DRE->getDecl() << E->getSourceRange();
9100 return ExprError();
9101}