blob: 15751d078bd9b66200c26391ab5c91541a4cf0e0 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/ASTContext.h"
Sebastian Redlf79a7192011-04-29 08:19:30 +000019#include "clang/AST/ASTMutationListener.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000020#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000023#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000024#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000025#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000027#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000028#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000032#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Designator.h"
36#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000037#include "clang/Sema/ScopeInfo.h"
John McCall19510852010-08-20 18:27:03 +000038#include "clang/Sema/ParsedTemplate.h"
John McCall7cd088e2010-08-24 07:21:54 +000039#include "clang/Sema/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000040using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000041using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000042
David Chisnall0f436562009-08-17 16:35:33 +000043
Douglas Gregor48f3bb92009-02-18 21:56:37 +000044/// \brief Determine whether the use of this declaration is valid, and
45/// emit any corresponding diagnostics.
46///
47/// This routine diagnoses various problems with referencing
48/// declarations that can occur when using a declaration. For example,
49/// it might warn if a deprecated or unavailable declaration is being
50/// used, or produce an error (and return true) if a C++0x deleted
51/// function is being used.
52///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000053/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattner52338262009-10-25 22:31:57 +000054/// decls.
55///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000056/// \returns true if there was an error (this declaration cannot be
57/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000058///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000059bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +000060 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor9b623632010-10-12 23:32:35 +000061 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
62 // If there were any diagnostics suppressed by template argument deduction,
63 // emit them now.
64 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
65 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
66 if (Pos != SuppressedDiagnostics.end()) {
67 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
68 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
69 Diag(Suppressed[I].first, Suppressed[I].second);
70
71 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000072 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +000073 // entry from the table, because we want to avoid ever emitting these
74 // diagnostics again.
75 Suppressed.clear();
76 }
77 }
78
Richard Smith34b41d92011-02-20 03:19:35 +000079 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +000080 if (ParsingInitForAutoVars.count(D)) {
81 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
82 << D->getDeclName();
83 return true;
Richard Smith34b41d92011-02-20 03:19:35 +000084 }
85
Douglas Gregor48f3bb92009-02-18 21:56:37 +000086 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000087 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000088 if (FD->isDeleted()) {
89 Diag(Loc, diag::err_deleted_function_use);
John McCallf85e1932011-06-15 23:02:42 +000090 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000091 return true;
92 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000093 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000094
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000095 // See if this declaration is unavailable or deprecated.
96 std::string Message;
97 switch (D->getAvailability(&Message)) {
98 case AR_Available:
99 case AR_NotYetIntroduced:
100 break;
101
102 case AR_Deprecated:
103 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
104 break;
105
106 case AR_Unavailable:
Argyrios Kyrtzidis12189f52011-06-17 17:28:30 +0000107 if (cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) {
108 if (Message.empty()) {
109 if (!UnknownObjCClass)
110 Diag(Loc, diag::err_unavailable) << D->getDeclName();
111 else
112 Diag(Loc, diag::warn_unavailable_fwdclass_message)
113 << D->getDeclName();
114 }
115 else
116 Diag(Loc, diag::err_unavailable_message)
117 << D->getDeclName() << Message;
118 Diag(D->getLocation(), diag::note_unavailable_here)
119 << isa<FunctionDecl>(D) << false;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000120 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000121 break;
122 }
123
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000124 // Warn if this is used but marked unused.
125 if (D->hasAttr<UnusedAttr>())
126 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
127
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000128 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000129}
130
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000131/// \brief Retrieve the message suffix that should be added to a
132/// diagnostic complaining about the given function being deleted or
133/// unavailable.
134std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
135 // FIXME: C++0x implicitly-deleted special member functions could be
136 // detected here so that we could improve diagnostics to say, e.g.,
137 // "base class 'A' had a deleted copy constructor".
138 if (FD->isDeleted())
139 return std::string();
140
141 std::string Message;
142 if (FD->getAvailability(&Message))
143 return ": " + Message;
144
145 return std::string();
146}
147
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000148/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +0000149/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000150/// attribute. It warns if call does not have the sentinel argument.
151///
152void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000153 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000154 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000155 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000156 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000157
158 // FIXME: In C++0x, if any of the arguments are parameter pack
159 // expansions, we can't check for the sentinel now.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000160 int sentinelPos = attr->getSentinel();
161 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +0000162
Mike Stump390b4cc2009-05-16 07:39:55 +0000163 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
164 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000165 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000166 bool warnNotEnoughArgs = false;
167 int isMethod = 0;
168 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
169 // skip over named parameters.
170 ObjCMethodDecl::param_iterator P, E = MD->param_end();
171 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
172 if (nullPos)
173 --nullPos;
174 else
175 ++i;
176 }
177 warnNotEnoughArgs = (P != E || i >= NumArgs);
178 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000179 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000180 // skip over named parameters.
181 ObjCMethodDecl::param_iterator P, E = FD->param_end();
182 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
183 if (nullPos)
184 --nullPos;
185 else
186 ++i;
187 }
188 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000189 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000190 // block or function pointer call.
191 QualType Ty = V->getType();
192 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000193 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000194 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
195 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000196 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
197 unsigned NumArgsInProto = Proto->getNumArgs();
198 unsigned k;
199 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
200 if (nullPos)
201 --nullPos;
202 else
203 ++i;
204 }
205 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
206 }
207 if (Ty->isBlockPointerType())
208 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000209 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000210 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000211 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000212 return;
213
214 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000215 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000216 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000217 return;
218 }
219 int sentinel = i;
220 while (sentinelPos > 0 && i < NumArgs-1) {
221 --sentinelPos;
222 ++i;
223 }
224 if (sentinelPos > 0) {
225 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000226 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000227 return;
228 }
229 while (i < NumArgs-1) {
230 ++i;
231 ++sentinel;
232 }
233 Expr *sentinelExpr = Args[sentinel];
John McCall8eb662e2010-05-06 23:53:00 +0000234 if (!sentinelExpr) return;
235 if (sentinelExpr->isTypeDependent()) return;
236 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000237
238 // nullptr_t is always treated as null.
239 if (sentinelExpr->getType()->isNullPtrType()) return;
240
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000241 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000242 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
243 Expr::NPC_ValueDependentIsNull))
244 return;
245
246 // Unfortunately, __null has type 'int'.
247 if (isa<GNUNullExpr>(sentinelExpr)) return;
248
249 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
250 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000251}
252
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000253SourceRange Sema::getExprRange(ExprTy *E) const {
254 Expr *Ex = (Expr *)E;
255 return Ex? Ex->getSourceRange() : SourceRange();
256}
257
Chris Lattnere7a2e912008-07-25 21:10:04 +0000258//===----------------------------------------------------------------------===//
259// Standard Promotions and Conversions
260//===----------------------------------------------------------------------===//
261
Chris Lattnere7a2e912008-07-25 21:10:04 +0000262/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000263ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000264 QualType Ty = E->getType();
265 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
266
Chris Lattnere7a2e912008-07-25 21:10:04 +0000267 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000268 E = ImpCastExprToType(E, Context.getPointerType(Ty),
269 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000270 else if (Ty->isArrayType()) {
271 // In C90 mode, arrays only promote to pointers if the array expression is
272 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
273 // type 'array of type' is converted to an expression that has type 'pointer
274 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
275 // that has type 'array of type' ...". The relevant change is "an lvalue"
276 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000277 //
278 // C++ 4.2p1:
279 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
280 // T" can be converted to an rvalue of type "pointer to T".
281 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000282 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000283 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
284 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000285 }
John Wiegley429bb272011-04-08 18:41:53 +0000286 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000287}
288
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000289static void CheckForNullPointerDereference(Sema &S, Expr *E) {
290 // Check to see if we are dereferencing a null pointer. If so,
291 // and if not volatile-qualified, this is undefined behavior that the
292 // optimizer will delete, so warn about it. People sometimes try to use this
293 // to get a deterministic trap and are surprised by clang's behavior. This
294 // only handles the pattern "*null", which is a very syntactic check.
295 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
296 if (UO->getOpcode() == UO_Deref &&
297 UO->getSubExpr()->IgnoreParenCasts()->
298 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
299 !UO->getType().isVolatileQualified()) {
300 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
301 S.PDiag(diag::warn_indirection_through_null)
302 << UO->getSubExpr()->getSourceRange());
303 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
304 S.PDiag(diag::note_indirection_through_null));
305 }
306}
307
John Wiegley429bb272011-04-08 18:41:53 +0000308ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000309 // C++ [conv.lval]p1:
310 // A glvalue of a non-function, non-array type T can be
311 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000312 if (!E->isGLValue()) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +0000313
John McCall409fa9a2010-12-06 20:48:59 +0000314 QualType T = E->getType();
315 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000316
John McCall409fa9a2010-12-06 20:48:59 +0000317 // Create a load out of an ObjCProperty l-value, if necessary.
318 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +0000319 ExprResult Res = ConvertPropertyForRValue(E);
320 if (Res.isInvalid())
321 return Owned(E);
322 E = Res.take();
John McCall409fa9a2010-12-06 20:48:59 +0000323 if (!E->isGLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000324 return Owned(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000325 }
John McCall409fa9a2010-12-06 20:48:59 +0000326
327 // We don't want to throw lvalue-to-rvalue casts on top of
328 // expressions of certain types in C++.
329 if (getLangOptions().CPlusPlus &&
330 (E->getType() == Context.OverloadTy ||
331 T->isDependentType() ||
332 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000333 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000334
335 // The C standard is actually really unclear on this point, and
336 // DR106 tells us what the result should be but not why. It's
337 // generally best to say that void types just doesn't undergo
338 // lvalue-to-rvalue at all. Note that expressions of unqualified
339 // 'void' type are never l-values, but qualified void can be.
340 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000341 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000342
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000343 CheckForNullPointerDereference(*this, E);
344
John McCall409fa9a2010-12-06 20:48:59 +0000345 // C++ [conv.lval]p1:
346 // [...] If T is a non-class type, the type of the prvalue is the
347 // cv-unqualified version of T. Otherwise, the type of the
348 // rvalue is T.
349 //
350 // C99 6.3.2.1p2:
351 // If the lvalue has qualified type, the value has the unqualified
352 // version of the type of the lvalue; otherwise, the value has the
353 // type of the lvalue.
354 if (T.hasQualifiers())
355 T = T.getUnqualifiedType();
356
Ted Kremenek3aea4da2011-03-01 18:41:00 +0000357 CheckArrayAccess(E);
Ted Kremeneka0125d82011-02-16 01:57:07 +0000358
John Wiegley429bb272011-04-08 18:41:53 +0000359 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
360 E, 0, VK_RValue));
John McCall409fa9a2010-12-06 20:48:59 +0000361}
362
John Wiegley429bb272011-04-08 18:41:53 +0000363ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
364 ExprResult Res = DefaultFunctionArrayConversion(E);
365 if (Res.isInvalid())
366 return ExprError();
367 Res = DefaultLvalueConversion(Res.take());
368 if (Res.isInvalid())
369 return ExprError();
370 return move(Res);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000371}
372
373
Chris Lattnere7a2e912008-07-25 21:10:04 +0000374/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000375/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000376/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000377/// apply if the array is an argument to the sizeof or address (&) operators.
378/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000379ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000380 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000381 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
382 if (Res.isInvalid())
383 return Owned(E);
384 E = Res.take();
John McCall0ae287a2010-12-01 04:43:34 +0000385
386 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000387 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000388
389 // Try to perform integral promotions if the object has a theoretically
390 // promotable type.
391 if (Ty->isIntegralOrUnscopedEnumerationType()) {
392 // C99 6.3.1.1p2:
393 //
394 // The following may be used in an expression wherever an int or
395 // unsigned int may be used:
396 // - an object or expression with an integer type whose integer
397 // conversion rank is less than or equal to the rank of int
398 // and unsigned int.
399 // - A bit-field of type _Bool, int, signed int, or unsigned int.
400 //
401 // If an int can represent all values of the original type, the
402 // value is converted to an int; otherwise, it is converted to an
403 // unsigned int. These are called the integer promotions. All
404 // other types are unchanged by the integer promotions.
405
406 QualType PTy = Context.isPromotableBitField(E);
407 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000408 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
409 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000410 }
411 if (Ty->isPromotableIntegerType()) {
412 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000413 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
414 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000415 }
Eli Friedman04e83572009-08-20 04:21:42 +0000416 }
John Wiegley429bb272011-04-08 18:41:53 +0000417 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000418}
419
Chris Lattner05faf172008-07-25 22:25:12 +0000420/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000421/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000422/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000423ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
424 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000425 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000426
John Wiegley429bb272011-04-08 18:41:53 +0000427 ExprResult Res = UsualUnaryConversions(E);
428 if (Res.isInvalid())
429 return Owned(E);
430 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000431
Chris Lattner05faf172008-07-25 22:25:12 +0000432 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000433 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000434 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
435
436 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000437}
438
Chris Lattner312531a2009-04-12 08:11:20 +0000439/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
440/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley429bb272011-04-08 18:41:53 +0000441/// interfaces passed by value.
442ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000443 FunctionDecl *FDecl) {
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000444 ExprResult ExprRes = CheckPlaceholderExpr(E);
445 if (ExprRes.isInvalid())
446 return ExprError();
447
448 ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000449 if (ExprRes.isInvalid())
450 return ExprError();
451 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Chris Lattner40378332010-05-16 04:01:30 +0000453 // __builtin_va_start takes the second argument as a "varargs" argument, but
454 // it doesn't actually do anything with it. It doesn't need to be non-pod
455 // etc.
456 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley429bb272011-04-08 18:41:53 +0000457 return Owned(E);
Chris Lattner40378332010-05-16 04:01:30 +0000458
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000459 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley429bb272011-04-08 18:41:53 +0000460 if (E->getType()->isObjCObjectType() &&
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000461 DiagRuntimeBehavior(E->getLocStart(), 0,
462 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
463 << E->getType() << CT))
John Wiegley429bb272011-04-08 18:41:53 +0000464 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000465
John McCallf85e1932011-06-15 23:02:42 +0000466 if (!E->getType().isPODType(Context)) {
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000467 // C++0x [expr.call]p7:
468 // Passing a potentially-evaluated argument of class type (Clause 9)
469 // having a non-trivial copy constructor, a non-trivial move constructor,
470 // or a non-trivial destructor, with no corresponding parameter,
471 // is conditionally-supported with implementation-defined semantics.
472 bool TrivialEnough = false;
473 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
474 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
475 if (Record->hasTrivialCopyConstructor() &&
476 Record->hasTrivialMoveConstructor() &&
477 Record->hasTrivialDestructor())
478 TrivialEnough = true;
479 }
480 }
John McCallf85e1932011-06-15 23:02:42 +0000481
482 if (!TrivialEnough &&
483 getLangOptions().ObjCAutoRefCount &&
484 E->getType()->isObjCLifetimeType())
485 TrivialEnough = true;
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000486
487 if (TrivialEnough) {
488 // Nothing to diagnose. This is okay.
489 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000490 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000491 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000492 << CT)) {
493 // Turn this into a trap.
494 CXXScopeSpec SS;
495 UnqualifiedId Name;
496 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
497 E->getLocStart());
498 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
499 if (TrapFn.isInvalid())
500 return ExprError();
501
502 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
503 MultiExprArg(), E->getLocEnd());
504 if (Call.isInvalid())
505 return ExprError();
506
507 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
508 Call.get(), E);
509 if (Comma.isInvalid())
510 return ExprError();
511
512 E = Comma.get();
513 }
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000514 }
515
John Wiegley429bb272011-04-08 18:41:53 +0000516 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000517}
518
Chris Lattnere7a2e912008-07-25 21:10:04 +0000519/// UsualArithmeticConversions - Performs various conversions that are common to
520/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000521/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000522/// responsible for emitting appropriate error diagnostics.
523/// FIXME: verify the conversion rules for "complex int" are consistent with
524/// GCC.
John Wiegley429bb272011-04-08 18:41:53 +0000525QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattnere7a2e912008-07-25 21:10:04 +0000526 bool isCompAssign) {
John Wiegley429bb272011-04-08 18:41:53 +0000527 if (!isCompAssign) {
528 lhsExpr = UsualUnaryConversions(lhsExpr.take());
529 if (lhsExpr.isInvalid())
530 return QualType();
531 }
Eli Friedmanab3a8522009-03-28 01:22:36 +0000532
John Wiegley429bb272011-04-08 18:41:53 +0000533 rhsExpr = UsualUnaryConversions(rhsExpr.take());
534 if (rhsExpr.isInvalid())
535 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000536
Mike Stump1eb44332009-09-09 15:08:12 +0000537 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000538 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000539 QualType lhs =
John Wiegley429bb272011-04-08 18:41:53 +0000540 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000541 QualType rhs =
John Wiegley429bb272011-04-08 18:41:53 +0000542 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000543
544 // If both types are identical, no conversion is needed.
545 if (lhs == rhs)
546 return lhs;
547
548 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
549 // The caller can deal with this (e.g. pointer + int).
550 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
551 return lhs;
552
John McCallcf33b242010-11-13 08:17:45 +0000553 // Apply unary and bitfield promotions to the LHS's type.
554 QualType lhs_unpromoted = lhs;
555 if (lhs->isPromotableIntegerType())
556 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley429bb272011-04-08 18:41:53 +0000557 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +0000558 if (!LHSBitfieldPromoteTy.isNull())
559 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000560 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000561 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000562
John McCallcf33b242010-11-13 08:17:45 +0000563 // If both types are identical, no conversion is needed.
564 if (lhs == rhs)
565 return lhs;
566
567 // At this point, we have two different arithmetic types.
568
569 // Handle complex types first (C99 6.3.1.8p1).
570 bool LHSComplexFloat = lhs->isComplexType();
571 bool RHSComplexFloat = rhs->isComplexType();
572 if (LHSComplexFloat || RHSComplexFloat) {
573 // if we have an integer operand, the result is the complex type.
574
John McCall2bb5d002010-11-13 09:02:35 +0000575 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
576 if (rhs->isIntegerType()) {
577 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000578 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
579 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000580 } else {
581 assert(rhs->isComplexIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +0000582 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000583 }
John McCallcf33b242010-11-13 08:17:45 +0000584 return lhs;
585 }
586
John McCall2bb5d002010-11-13 09:02:35 +0000587 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
588 if (!isCompAssign) {
589 // int -> float -> _Complex float
590 if (lhs->isIntegerType()) {
591 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000592 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
593 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000594 } else {
595 assert(lhs->isComplexIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +0000596 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000597 }
598 }
John McCallcf33b242010-11-13 08:17:45 +0000599 return rhs;
600 }
601
602 // This handles complex/complex, complex/float, or float/complex.
603 // When both operands are complex, the shorter operand is converted to the
604 // type of the longer, and that is the type of the result. This corresponds
605 // to what is done when combining two real floating-point operands.
606 // The fun begins when size promotion occur across type domains.
607 // From H&S 6.3.4: When one operand is complex and the other is a real
608 // floating-point type, the less precise type is converted, within it's
609 // real or complex domain, to the precision of the other type. For example,
610 // when combining a "long double" with a "double _Complex", the
611 // "double _Complex" is promoted to "long double _Complex".
612 int order = Context.getFloatingTypeOrder(lhs, rhs);
613
614 // If both are complex, just cast to the more precise type.
615 if (LHSComplexFloat && RHSComplexFloat) {
616 if (order > 0) {
617 // _Complex float -> _Complex double
John Wiegley429bb272011-04-08 18:41:53 +0000618 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000619 return lhs;
620
621 } else if (order < 0) {
622 // _Complex float -> _Complex double
623 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000624 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000625 return rhs;
626 }
627 return lhs;
628 }
629
630 // If just the LHS is complex, the RHS needs to be converted,
631 // and the LHS might need to be promoted.
632 if (LHSComplexFloat) {
633 if (order > 0) { // LHS is wider
634 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000635 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000636 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
637 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000638 return lhs;
639 }
640
641 // RHS is at least as wide. Find its corresponding complex type.
642 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
643
644 // double -> _Complex double
John Wiegley429bb272011-04-08 18:41:53 +0000645 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000646
647 // _Complex float -> _Complex double
648 if (!isCompAssign && order < 0)
John Wiegley429bb272011-04-08 18:41:53 +0000649 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000650
651 return result;
652 }
653
654 // Just the RHS is complex, so the LHS needs to be converted
655 // and the RHS might need to be promoted.
656 assert(RHSComplexFloat);
657
658 if (order < 0) { // RHS is wider
659 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000660 if (!isCompAssign) {
Argyrios Kyrtzidise1889332011-01-18 18:49:33 +0000661 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000662 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
663 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000664 }
John McCallcf33b242010-11-13 08:17:45 +0000665 return rhs;
666 }
667
668 // LHS is at least as wide. Find its corresponding complex type.
669 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
670
671 // double -> _Complex double
672 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000673 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000674
675 // _Complex float -> _Complex double
676 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +0000677 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000678
679 return result;
680 }
681
682 // Now handle "real" floating types (i.e. float, double, long double).
683 bool LHSFloat = lhs->isRealFloatingType();
684 bool RHSFloat = rhs->isRealFloatingType();
685 if (LHSFloat || RHSFloat) {
686 // If we have two real floating types, convert the smaller operand
687 // to the bigger result.
688 if (LHSFloat && RHSFloat) {
689 int order = Context.getFloatingTypeOrder(lhs, rhs);
690 if (order > 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000691 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000692 return lhs;
693 }
694
695 assert(order < 0 && "illegal float comparison");
696 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000697 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000698 return rhs;
699 }
700
701 // If we have an integer operand, the result is the real floating type.
702 if (LHSFloat) {
703 if (rhs->isIntegerType()) {
704 // Convert rhs to the lhs floating point type.
John Wiegley429bb272011-04-08 18:41:53 +0000705 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCallcf33b242010-11-13 08:17:45 +0000706 return lhs;
707 }
708
709 // Convert both sides to the appropriate complex float.
710 assert(rhs->isComplexIntegerType());
711 QualType result = Context.getComplexType(lhs);
712
713 // _Complex int -> _Complex float
John Wiegley429bb272011-04-08 18:41:53 +0000714 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000715
716 // float -> _Complex float
717 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000718 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000719
720 return result;
721 }
722
723 assert(RHSFloat);
724 if (lhs->isIntegerType()) {
725 // Convert lhs to the rhs floating point type.
726 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000727 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCallcf33b242010-11-13 08:17:45 +0000728 return rhs;
729 }
730
731 // Convert both sides to the appropriate complex float.
732 assert(lhs->isComplexIntegerType());
733 QualType result = Context.getComplexType(rhs);
734
735 // _Complex int -> _Complex float
736 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000737 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000738
739 // float -> _Complex float
John Wiegley429bb272011-04-08 18:41:53 +0000740 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000741
742 return result;
743 }
744
745 // Handle GCC complex int extension.
746 // FIXME: if the operands are (int, _Complex long), we currently
747 // don't promote the complex. Also, signedness?
748 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
749 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
750 if (lhsComplexInt && rhsComplexInt) {
751 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
752 rhsComplexInt->getElementType());
753 assert(order && "inequal types with equal element ordering");
754 if (order > 0) {
755 // _Complex int -> _Complex long
John Wiegley429bb272011-04-08 18:41:53 +0000756 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000757 return lhs;
758 }
759
760 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000761 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000762 return rhs;
763 } else if (lhsComplexInt) {
764 // int -> _Complex int
John Wiegley429bb272011-04-08 18:41:53 +0000765 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000766 return lhs;
767 } else if (rhsComplexInt) {
768 // int -> _Complex int
769 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000770 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000771 return rhs;
772 }
773
774 // Finally, we have two differing integer types.
775 // The rules for this case are in C99 6.3.1.8
776 int compare = Context.getIntegerTypeOrder(lhs, rhs);
777 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
778 rhsSigned = rhs->hasSignedIntegerRepresentation();
779 if (lhsSigned == rhsSigned) {
780 // Same signedness; use the higher-ranked type
781 if (compare >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000782 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000783 return lhs;
784 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000785 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000786 return rhs;
787 } else if (compare != (lhsSigned ? 1 : -1)) {
788 // The unsigned type has greater than or equal rank to the
789 // signed type, so use the unsigned type
790 if (rhsSigned) {
John Wiegley429bb272011-04-08 18:41:53 +0000791 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000792 return lhs;
793 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000794 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000795 return rhs;
796 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
797 // The two types are different widths; if we are here, that
798 // means the signed type is larger than the unsigned type, so
799 // use the signed type.
800 if (lhsSigned) {
John Wiegley429bb272011-04-08 18:41:53 +0000801 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000802 return lhs;
803 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000804 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000805 return rhs;
806 } else {
807 // The signed type is higher-ranked than the unsigned type,
808 // but isn't actually any bigger (like unsigned int and long
809 // on most 32-bit systems). Use the unsigned type corresponding
810 // to the signed type.
811 QualType result =
812 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley429bb272011-04-08 18:41:53 +0000813 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000814 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000815 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000816 return result;
817 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000818}
819
Chris Lattnere7a2e912008-07-25 21:10:04 +0000820//===----------------------------------------------------------------------===//
821// Semantic Analysis for various Expression Types
822//===----------------------------------------------------------------------===//
823
824
Peter Collingbournef111d932011-04-15 00:35:48 +0000825ExprResult
826Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
827 SourceLocation DefaultLoc,
828 SourceLocation RParenLoc,
829 Expr *ControllingExpr,
830 MultiTypeArg types,
831 MultiExprArg exprs) {
832 unsigned NumAssocs = types.size();
833 assert(NumAssocs == exprs.size());
834
835 ParsedType *ParsedTypes = types.release();
836 Expr **Exprs = exprs.release();
837
838 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
839 for (unsigned i = 0; i < NumAssocs; ++i) {
840 if (ParsedTypes[i])
841 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
842 else
843 Types[i] = 0;
844 }
845
846 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
847 ControllingExpr, Types, Exprs,
848 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +0000849 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +0000850 return ER;
851}
852
853ExprResult
854Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
855 SourceLocation DefaultLoc,
856 SourceLocation RParenLoc,
857 Expr *ControllingExpr,
858 TypeSourceInfo **Types,
859 Expr **Exprs,
860 unsigned NumAssocs) {
861 bool TypeErrorFound = false,
862 IsResultDependent = ControllingExpr->isTypeDependent(),
863 ContainsUnexpandedParameterPack
864 = ControllingExpr->containsUnexpandedParameterPack();
865
866 for (unsigned i = 0; i < NumAssocs; ++i) {
867 if (Exprs[i]->containsUnexpandedParameterPack())
868 ContainsUnexpandedParameterPack = true;
869
870 if (Types[i]) {
871 if (Types[i]->getType()->containsUnexpandedParameterPack())
872 ContainsUnexpandedParameterPack = true;
873
874 if (Types[i]->getType()->isDependentType()) {
875 IsResultDependent = true;
876 } else {
877 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
878 // complete object type other than a variably modified type."
879 unsigned D = 0;
880 if (Types[i]->getType()->isIncompleteType())
881 D = diag::err_assoc_type_incomplete;
882 else if (!Types[i]->getType()->isObjectType())
883 D = diag::err_assoc_type_nonobject;
884 else if (Types[i]->getType()->isVariablyModifiedType())
885 D = diag::err_assoc_type_variably_modified;
886
887 if (D != 0) {
888 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
889 << Types[i]->getTypeLoc().getSourceRange()
890 << Types[i]->getType();
891 TypeErrorFound = true;
892 }
893
894 // C1X 6.5.1.1p2 "No two generic associations in the same generic
895 // selection shall specify compatible types."
896 for (unsigned j = i+1; j < NumAssocs; ++j)
897 if (Types[j] && !Types[j]->getType()->isDependentType() &&
898 Context.typesAreCompatible(Types[i]->getType(),
899 Types[j]->getType())) {
900 Diag(Types[j]->getTypeLoc().getBeginLoc(),
901 diag::err_assoc_compatible_types)
902 << Types[j]->getTypeLoc().getSourceRange()
903 << Types[j]->getType()
904 << Types[i]->getType();
905 Diag(Types[i]->getTypeLoc().getBeginLoc(),
906 diag::note_compat_assoc)
907 << Types[i]->getTypeLoc().getSourceRange()
908 << Types[i]->getType();
909 TypeErrorFound = true;
910 }
911 }
912 }
913 }
914 if (TypeErrorFound)
915 return ExprError();
916
917 // If we determined that the generic selection is result-dependent, don't
918 // try to compute the result expression.
919 if (IsResultDependent)
920 return Owned(new (Context) GenericSelectionExpr(
921 Context, KeyLoc, ControllingExpr,
922 Types, Exprs, NumAssocs, DefaultLoc,
923 RParenLoc, ContainsUnexpandedParameterPack));
924
925 llvm::SmallVector<unsigned, 1> CompatIndices;
926 unsigned DefaultIndex = -1U;
927 for (unsigned i = 0; i < NumAssocs; ++i) {
928 if (!Types[i])
929 DefaultIndex = i;
930 else if (Context.typesAreCompatible(ControllingExpr->getType(),
931 Types[i]->getType()))
932 CompatIndices.push_back(i);
933 }
934
935 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
936 // type compatible with at most one of the types named in its generic
937 // association list."
938 if (CompatIndices.size() > 1) {
939 // We strip parens here because the controlling expression is typically
940 // parenthesized in macro definitions.
941 ControllingExpr = ControllingExpr->IgnoreParens();
942 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
943 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
944 << (unsigned) CompatIndices.size();
945 for (llvm::SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
946 E = CompatIndices.end(); I != E; ++I) {
947 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
948 diag::note_compat_assoc)
949 << Types[*I]->getTypeLoc().getSourceRange()
950 << Types[*I]->getType();
951 }
952 return ExprError();
953 }
954
955 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
956 // its controlling expression shall have type compatible with exactly one of
957 // the types named in its generic association list."
958 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
959 // We strip parens here because the controlling expression is typically
960 // parenthesized in macro definitions.
961 ControllingExpr = ControllingExpr->IgnoreParens();
962 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
963 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
964 return ExprError();
965 }
966
967 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
968 // type name that is compatible with the type of the controlling expression,
969 // then the result expression of the generic selection is the expression
970 // in that generic association. Otherwise, the result expression of the
971 // generic selection is the expression in the default generic association."
972 unsigned ResultIndex =
973 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
974
975 return Owned(new (Context) GenericSelectionExpr(
976 Context, KeyLoc, ControllingExpr,
977 Types, Exprs, NumAssocs, DefaultLoc,
978 RParenLoc, ContainsUnexpandedParameterPack,
979 ResultIndex));
980}
981
Steve Narofff69936d2007-09-16 03:34:24 +0000982/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000983/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
984/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
985/// multiple tokens. However, the common case is that StringToks points to one
986/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000987///
John McCall60d7b3a2010-08-24 06:29:42 +0000988ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +0000989Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000990 assert(NumStringToks && "Must have at least one string!");
991
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000992 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000993 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000994 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000995
996 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
997 for (unsigned i = 0; i != NumStringToks; ++i)
998 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000999
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001000 QualType StrTy = Context.CharTy;
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001001 if (Literal.AnyWide)
1002 StrTy = Context.getWCharType();
1003 else if (Literal.Pascal)
1004 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001005
1006 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +00001007 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001008 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001009
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001010 // Get an array type for the string, according to C99 6.4.5. This includes
1011 // the nul terminator character as well as the string length for pascal
1012 // strings.
1013 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001014 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001015 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001016
Reid Spencer5f016e22007-07-11 17:01:13 +00001017 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +00001018 return Owned(StringLiteral::Create(Context, Literal.GetString(),
1019 Literal.GetStringLength(),
Anders Carlsson3e2193c2011-04-14 00:40:03 +00001020 Literal.AnyWide, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +00001021 &StringTokLocs[0],
1022 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001023}
1024
John McCall469a1eb2011-02-02 13:00:07 +00001025enum CaptureResult {
1026 /// No capture is required.
1027 CR_NoCapture,
1028
1029 /// A capture is required.
1030 CR_Capture,
1031
John McCall6b5a61b2011-02-07 10:33:21 +00001032 /// A by-ref capture is required.
1033 CR_CaptureByRef,
1034
John McCall469a1eb2011-02-02 13:00:07 +00001035 /// An error occurred when trying to capture the given variable.
1036 CR_Error
1037};
1038
1039/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +00001040///
John McCall469a1eb2011-02-02 13:00:07 +00001041/// \param var - the variable referenced
1042/// \param DC - the context which we couldn't capture through
1043static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +00001044diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001045 VarDecl *var, DeclContext *DC) {
1046 switch (S.ExprEvalContexts.back().Context) {
1047 case Sema::Unevaluated:
1048 // The argument will never be evaluated, so don't complain.
1049 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +00001050
John McCall469a1eb2011-02-02 13:00:07 +00001051 case Sema::PotentiallyEvaluated:
1052 case Sema::PotentiallyEvaluatedIfUsed:
1053 break;
Chris Lattner639e2d32008-10-20 05:16:36 +00001054
John McCall469a1eb2011-02-02 13:00:07 +00001055 case Sema::PotentiallyPotentiallyEvaluated:
1056 // FIXME: delay these!
1057 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +00001058 }
Mike Stump1eb44332009-09-09 15:08:12 +00001059
John McCall469a1eb2011-02-02 13:00:07 +00001060 // Don't diagnose about capture if we're not actually in code right
1061 // now; in general, there are more appropriate places that will
1062 // diagnose this.
1063 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1064
John McCall4f38f412011-03-22 23:15:50 +00001065 // Certain madnesses can happen with parameter declarations, which
1066 // we want to ignore.
1067 if (isa<ParmVarDecl>(var)) {
1068 // - If the parameter still belongs to the translation unit, then
1069 // we're actually just using one parameter in the declaration of
1070 // the next. This is useful in e.g. VLAs.
1071 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1072 return CR_NoCapture;
1073
1074 // - This particular madness can happen in ill-formed default
1075 // arguments; claim it's okay and let downstream code handle it.
1076 if (S.CurContext == var->getDeclContext()->getParent())
1077 return CR_NoCapture;
1078 }
John McCall469a1eb2011-02-02 13:00:07 +00001079
1080 DeclarationName functionName;
1081 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1082 functionName = fn->getDeclName();
1083 // FIXME: variable from enclosing block that we couldn't capture from!
1084
1085 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1086 << var->getIdentifier() << functionName;
1087 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1088 << var->getIdentifier();
1089
1090 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001091}
1092
John McCall6b5a61b2011-02-07 10:33:21 +00001093/// There is a well-formed capture at a particular scope level;
1094/// propagate it through all the nested blocks.
1095static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1096 const BlockDecl::Capture &capture) {
1097 VarDecl *var = capture.getVariable();
1098
1099 // Update all the inner blocks with the capture information.
1100 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1101 i != e; ++i) {
1102 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1103 innerBlock->Captures.push_back(
1104 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1105 /*nested*/ true, capture.getCopyExpr()));
1106 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1107 }
1108
1109 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1110}
1111
1112/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +00001113/// given value in the current context requires a variable capture.
1114///
1115/// This also keeps the captures set in the BlockScopeInfo records
1116/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +00001117static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001118 ValueDecl *value) {
1119 // Only variables ever require capture.
1120 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +00001121 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +00001122
1123 // Fast path: variables from the current context never require capture.
1124 DeclContext *DC = S.CurContext;
1125 if (var->getDeclContext() == DC) return CR_NoCapture;
1126
1127 // Only variables with local storage require capture.
1128 // FIXME: What about 'const' variables in C++?
1129 if (!var->hasLocalStorage()) return CR_NoCapture;
1130
1131 // Otherwise, we need to capture.
1132
1133 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +00001134 do {
1135 // Only blocks (and eventually C++0x closures) can capture; other
1136 // scopes don't work.
1137 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +00001138 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +00001139
1140 BlockScopeInfo *blockScope =
1141 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1142 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1143
John McCall6b5a61b2011-02-07 10:33:21 +00001144 // Check whether we've already captured it in this block. If so,
1145 // we're done.
1146 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1147 return propagateCapture(S, functionScopesIndex,
1148 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +00001149
1150 functionScopesIndex--;
1151 DC = cast<BlockDecl>(DC)->getDeclContext();
1152 } while (var->getDeclContext() != DC);
1153
John McCall6b5a61b2011-02-07 10:33:21 +00001154 // Okay, we descended all the way to the block that defines the variable.
1155 // Actually try to capture it.
1156 QualType type = var->getType();
1157
1158 // Prohibit variably-modified types.
1159 if (type->isVariablyModifiedType()) {
1160 S.Diag(loc, diag::err_ref_vm_type);
1161 S.Diag(var->getLocation(), diag::note_declared_at);
1162 return CR_Error;
1163 }
1164
1165 // Prohibit arrays, even in __block variables, but not references to
1166 // them.
1167 if (type->isArrayType()) {
1168 S.Diag(loc, diag::err_ref_array_type);
1169 S.Diag(var->getLocation(), diag::note_declared_at);
1170 return CR_Error;
1171 }
1172
1173 S.MarkDeclarationReferenced(loc, var);
1174
1175 // The BlocksAttr indicates the variable is bound by-reference.
1176 bool byRef = var->hasAttr<BlocksAttr>();
1177
1178 // Build a copy expression.
1179 Expr *copyExpr = 0;
John McCall642a75f2011-04-28 02:15:35 +00001180 const RecordType *rtype;
1181 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1182 (rtype = type->getAs<RecordType>())) {
1183
1184 // The capture logic needs the destructor, so make sure we mark it.
1185 // Usually this is unnecessary because most local variables have
1186 // their destructors marked at declaration time, but parameters are
1187 // an exception because it's technically only the call site that
1188 // actually requires the destructor.
1189 if (isa<ParmVarDecl>(var))
1190 S.FinalizeVarWithDestructor(var, rtype);
1191
John McCall6b5a61b2011-02-07 10:33:21 +00001192 // According to the blocks spec, the capture of a variable from
1193 // the stack requires a const copy constructor. This is not true
1194 // of the copy/move done to move a __block variable to the heap.
1195 type.addConst();
1196
1197 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1198 ExprResult result =
1199 S.PerformCopyInitialization(
1200 InitializedEntity::InitializeBlock(var->getLocation(),
1201 type, false),
1202 loc, S.Owned(declRef));
1203
1204 // Build a full-expression copy expression if initialization
1205 // succeeded and used a non-trivial constructor. Recover from
1206 // errors by pretending that the copy isn't necessary.
1207 if (!result.isInvalid() &&
1208 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1209 result = S.MaybeCreateExprWithCleanups(result);
1210 copyExpr = result.take();
1211 }
1212 }
1213
1214 // We're currently at the declarer; go back to the closure.
1215 functionScopesIndex++;
1216 BlockScopeInfo *blockScope =
1217 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1218
1219 // Build a valid capture in this scope.
1220 blockScope->Captures.push_back(
1221 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1222 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1223
1224 // Propagate that to inner captures if necessary.
1225 return propagateCapture(S, functionScopesIndex,
1226 blockScope->Captures.back());
1227}
1228
1229static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1230 const DeclarationNameInfo &NameInfo,
1231 bool byRef) {
1232 assert(isa<VarDecl>(vd) && "capturing non-variable");
1233
1234 VarDecl *var = cast<VarDecl>(vd);
1235 assert(var->hasLocalStorage() && "capturing non-local");
1236 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1237
1238 QualType exprType = var->getType().getNonReferenceType();
1239
1240 BlockDeclRefExpr *BDRE;
1241 if (!byRef) {
1242 // The variable will be bound by copy; make it const within the
1243 // closure, but record that this was done in the expression.
1244 bool constAdded = !exprType.isConstQualified();
1245 exprType.addConst();
1246
1247 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1248 NameInfo.getLoc(), false,
1249 constAdded);
1250 } else {
1251 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1252 NameInfo.getLoc(), true);
1253 }
1254
1255 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +00001256}
Chris Lattner639e2d32008-10-20 05:16:36 +00001257
John McCall60d7b3a2010-08-24 06:29:42 +00001258ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001259Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001260 SourceLocation Loc,
1261 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001262 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001263 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001264}
1265
John McCall76a40212011-02-09 01:13:10 +00001266/// BuildDeclRefExpr - Build an expression that references a
1267/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001268ExprResult
John McCall76a40212011-02-09 01:13:10 +00001269Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001270 const DeclarationNameInfo &NameInfo,
1271 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001272 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001273
John McCall7eb0a9e2010-11-24 05:12:34 +00001274 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001275 SS? SS->getWithLocInContext(Context)
1276 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +00001277 D, NameInfo, Ty, VK);
1278
1279 // Just in case we're building an illegal pointer-to-member.
1280 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1281 E->setObjectKind(OK_BitField);
1282
1283 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001284}
1285
John McCalldfa1edb2010-11-23 20:48:44 +00001286static ExprResult
1287BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1288 const CXXScopeSpec &SS, FieldDecl *Field,
1289 DeclAccessPair FoundDecl,
1290 const DeclarationNameInfo &MemberNameInfo);
1291
John McCall60d7b3a2010-08-24 06:29:42 +00001292ExprResult
John McCall5808ce42011-02-03 08:15:49 +00001293Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1294 SourceLocation loc,
1295 IndirectFieldDecl *indirectField,
1296 Expr *baseObjectExpr,
1297 SourceLocation opLoc) {
1298 // First, build the expression that refers to the base object.
1299
1300 bool baseObjectIsPointer = false;
1301 Qualifiers baseQuals;
1302
1303 // Case 1: the base of the indirect field is not a field.
1304 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregorf5848322011-02-18 02:44:58 +00001305 CXXScopeSpec EmptySS;
John McCall5808ce42011-02-03 08:15:49 +00001306 if (baseVariable) {
1307 assert(baseVariable->getType()->isRecordType());
1308
1309 // In principle we could have a member access expression that
1310 // accesses an anonymous struct/union that's a static member of
1311 // the base object's class. However, under the current standard,
1312 // static data members cannot be anonymous structs or unions.
1313 // Supporting this is as easy as building a MemberExpr here.
1314 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1315
1316 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1317
1318 ExprResult result =
Douglas Gregorf5848322011-02-18 02:44:58 +00001319 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCall5808ce42011-02-03 08:15:49 +00001320 if (result.isInvalid()) return ExprError();
1321
1322 baseObjectExpr = result.take();
1323 baseObjectIsPointer = false;
1324 baseQuals = baseObjectExpr->getType().getQualifiers();
1325
1326 // Case 2: the base of the indirect field is a field and the user
1327 // wrote a member expression.
1328 } else if (baseObjectExpr) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001329 // The caller provided the base object expression. Determine
1330 // whether its a pointer and whether it adds any qualifiers to the
1331 // anonymous struct/union fields we're looking into.
John McCall5808ce42011-02-03 08:15:49 +00001332 QualType objectType = baseObjectExpr->getType();
1333
1334 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1335 baseObjectIsPointer = true;
1336 objectType = ptr->getPointeeType();
1337 } else {
1338 baseObjectIsPointer = false;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001339 }
John McCall5808ce42011-02-03 08:15:49 +00001340 baseQuals = objectType.getQualifiers();
1341
1342 // Case 3: the base of the indirect field is a field and we should
1343 // build an implicit member access.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001344 } else {
1345 // We've found a member of an anonymous struct/union that is
1346 // inside a non-anonymous struct/union, so in a well-formed
1347 // program our base object expression is "this".
Richard Smith7a614d82011-06-11 17:19:42 +00001348 QualType ThisTy = getAndCaptureCurrentThisType();
1349 if (ThisTy.isNull()) {
John McCall5808ce42011-02-03 08:15:49 +00001350 Diag(loc, diag::err_invalid_member_use_in_static_method)
1351 << indirectField->getDeclName();
1352 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001353 }
1354
John McCall5808ce42011-02-03 08:15:49 +00001355 // Our base object expression is "this".
1356 baseObjectExpr =
Richard Smith7a614d82011-06-11 17:19:42 +00001357 new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
John McCall5808ce42011-02-03 08:15:49 +00001358 baseObjectIsPointer = true;
Richard Smith7a614d82011-06-11 17:19:42 +00001359 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001360 }
1361
1362 // Build the implicit member references to the field of the
1363 // anonymous struct/union.
John McCall5808ce42011-02-03 08:15:49 +00001364 Expr *result = baseObjectExpr;
1365 IndirectFieldDecl::chain_iterator
1366 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCalldfa1edb2010-11-23 20:48:44 +00001367
John McCall5808ce42011-02-03 08:15:49 +00001368 // Build the first member access in the chain with full information.
1369 if (!baseVariable) {
1370 FieldDecl *field = cast<FieldDecl>(*FI);
John McCalldfa1edb2010-11-23 20:48:44 +00001371
John McCall5808ce42011-02-03 08:15:49 +00001372 // FIXME: use the real found-decl info!
1373 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall0953e762009-09-24 19:53:00 +00001374
John McCall5808ce42011-02-03 08:15:49 +00001375 // Make a nameInfo that properly uses the anonymous name.
1376 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall0953e762009-09-24 19:53:00 +00001377
John McCall5808ce42011-02-03 08:15:49 +00001378 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregorf5848322011-02-18 02:44:58 +00001379 EmptySS, field, foundDecl,
John McCall5808ce42011-02-03 08:15:49 +00001380 memberNameInfo).take();
1381 baseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +00001382
John McCall5808ce42011-02-03 08:15:49 +00001383 // FIXME: check qualified member access
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001384 }
1385
John McCall5808ce42011-02-03 08:15:49 +00001386 // In all cases, we should now skip the first declaration in the chain.
1387 ++FI;
1388
Douglas Gregorf5848322011-02-18 02:44:58 +00001389 while (FI != FEnd) {
1390 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCall5808ce42011-02-03 08:15:49 +00001391
1392 // FIXME: these are somewhat meaningless
1393 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1394 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall5808ce42011-02-03 08:15:49 +00001395
1396 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregorf5848322011-02-18 02:44:58 +00001397 (FI == FEnd? SS : EmptySS), field,
1398 foundDecl, memberNameInfo)
John McCall5808ce42011-02-03 08:15:49 +00001399 .take();
1400 }
1401
1402 return Owned(result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001403}
1404
Abramo Bagnara25777432010-08-11 22:01:17 +00001405/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001406/// possibly a list of template arguments.
1407///
1408/// If this produces template arguments, it is permitted to call
1409/// DecomposeTemplateName.
1410///
1411/// This actually loses a lot of source location information for
1412/// non-standard name kinds; we should consider preserving that in
1413/// some way.
1414static void DecomposeUnqualifiedId(Sema &SemaRef,
1415 const UnqualifiedId &Id,
1416 TemplateArgumentListInfo &Buffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00001417 DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00001418 const TemplateArgumentListInfo *&TemplateArgs) {
1419 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1420 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1421 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1422
1423 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1424 Id.TemplateId->getTemplateArgs(),
1425 Id.TemplateId->NumArgs);
1426 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1427 TemplateArgsPtr.release();
1428
John McCall2b5289b2010-08-23 07:28:44 +00001429 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001430 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1431 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001432 TemplateArgs = &Buffer;
1433 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001434 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001435 TemplateArgs = 0;
1436 }
1437}
1438
John McCallaa81e162009-12-01 22:10:20 +00001439/// Determines if the given class is provably not derived from all of
1440/// the prospective base classes.
1441static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1442 CXXRecordDecl *Record,
1443 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +00001444 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +00001445 return false;
1446
Douglas Gregor952b0172010-02-11 01:04:33 +00001447 RecordDecl *RD = Record->getDefinition();
John McCallb1b42562009-12-01 22:28:41 +00001448 if (!RD) return false;
1449 Record = cast<CXXRecordDecl>(RD);
1450
John McCallaa81e162009-12-01 22:10:20 +00001451 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1452 E = Record->bases_end(); I != E; ++I) {
1453 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1454 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1455 if (!BaseRT) return false;
1456
1457 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +00001458 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1459 return false;
1460 }
1461
1462 return true;
1463}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001464
John McCallaa81e162009-12-01 22:10:20 +00001465enum IMAKind {
1466 /// The reference is definitely not an instance member access.
1467 IMA_Static,
1468
1469 /// The reference may be an implicit instance member access.
1470 IMA_Mixed,
1471
1472 /// The reference may be to an instance member, but it is invalid if
1473 /// so, because the context is not an instance method.
1474 IMA_Mixed_StaticContext,
1475
1476 /// The reference may be to an instance member, but it is invalid if
1477 /// so, because the context is from an unrelated class.
1478 IMA_Mixed_Unrelated,
1479
1480 /// The reference is definitely an implicit instance member access.
1481 IMA_Instance,
1482
1483 /// The reference may be to an unresolved using declaration.
1484 IMA_Unresolved,
1485
1486 /// The reference may be to an unresolved using declaration and the
1487 /// context is not an instance method.
1488 IMA_Unresolved_StaticContext,
1489
John McCallaa81e162009-12-01 22:10:20 +00001490 /// All possible referrents are instance members and the current
1491 /// context is not an instance method.
1492 IMA_Error_StaticContext,
1493
1494 /// All possible referrents are instance members of an unrelated
1495 /// class.
1496 IMA_Error_Unrelated
1497};
1498
1499/// The given lookup names class member(s) and is not being used for
1500/// an address-of-member expression. Classify the type of access
1501/// according to whether it's possible that this reference names an
1502/// instance member. This is best-effort; it is okay to
1503/// conservatively answer "yes", in which case some errors will simply
1504/// not be caught until template-instantiation.
1505static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
Richard Smith7a614d82011-06-11 17:19:42 +00001506 Scope *CurScope,
John McCallaa81e162009-12-01 22:10:20 +00001507 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +00001508 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +00001509
John McCallea1471e2010-05-20 01:18:31 +00001510 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
Richard Smith7a614d82011-06-11 17:19:42 +00001511
John McCallaa81e162009-12-01 22:10:20 +00001512 bool isStaticContext =
John McCallea1471e2010-05-20 01:18:31 +00001513 (!isa<CXXMethodDecl>(DC) ||
1514 cast<CXXMethodDecl>(DC)->isStatic());
John McCallaa81e162009-12-01 22:10:20 +00001515
Richard Smith7a614d82011-06-11 17:19:42 +00001516 // C++0x [expr.prim]p4:
1517 // Otherwise, if a member-declarator declares a non-static data member
1518 // of a class X, the expression this is a prvalue of type "pointer to X"
1519 // within the optional brace-or-equal-initializer.
1520 if (CurScope->getFlags() & Scope::ThisScope)
1521 isStaticContext = false;
1522
John McCallaa81e162009-12-01 22:10:20 +00001523 if (R.isUnresolvableResult())
1524 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1525
1526 // Collect all the declaring classes of instance members we find.
1527 bool hasNonInstance = false;
Sebastian Redlf9780002010-11-26 16:28:07 +00001528 bool hasField = false;
John McCallaa81e162009-12-01 22:10:20 +00001529 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1530 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall161755a2010-04-06 21:38:20 +00001531 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00001532
John McCall161755a2010-04-06 21:38:20 +00001533 if (D->isCXXInstanceMember()) {
Sebastian Redlf9780002010-11-26 16:28:07 +00001534 if (dyn_cast<FieldDecl>(D))
1535 hasField = true;
1536
John McCallaa81e162009-12-01 22:10:20 +00001537 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCallaa81e162009-12-01 22:10:20 +00001538 Classes.insert(R->getCanonicalDecl());
1539 }
1540 else
1541 hasNonInstance = true;
1542 }
1543
1544 // If we didn't find any instance members, it can't be an implicit
1545 // member reference.
1546 if (Classes.empty())
1547 return IMA_Static;
1548
1549 // If the current context is not an instance method, it can't be
1550 // an implicit member reference.
Sebastian Redlf9780002010-11-26 16:28:07 +00001551 if (isStaticContext) {
1552 if (hasNonInstance)
1553 return IMA_Mixed_StaticContext;
1554
1555 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1556 // C++0x [expr.prim.general]p10:
1557 // An id-expression that denotes a non-static data member or non-static
1558 // member function of a class can only be used:
1559 // (...)
John McCallf85e1932011-06-15 23:02:42 +00001560 // - if that id-expression denotes a non-static data member and it
1561 // appears in an unevaluated operand.
1562 const Sema::ExpressionEvaluationContextRecord& record
1563 = SemaRef.ExprEvalContexts.back();
1564 bool isUnevaluatedExpression = (record.Context == Sema::Unevaluated);
Sebastian Redlf9780002010-11-26 16:28:07 +00001565 if (isUnevaluatedExpression)
1566 return IMA_Mixed_StaticContext;
1567 }
1568
1569 return IMA_Error_StaticContext;
1570 }
John McCallaa81e162009-12-01 22:10:20 +00001571
Richard Smith7a614d82011-06-11 17:19:42 +00001572 CXXRecordDecl *contextClass;
1573 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
1574 contextClass = MD->getParent()->getCanonicalDecl();
1575 else
1576 contextClass = cast<CXXRecordDecl>(DC);
Argyrios Kyrtzidis0d8dc462011-04-14 00:46:47 +00001577
1578 // [class.mfct.non-static]p3:
1579 // ...is used in the body of a non-static member function of class X,
1580 // if name lookup (3.4.1) resolves the name in the id-expression to a
1581 // non-static non-type member of some class C [...]
1582 // ...if C is not X or a base class of X, the class member access expression
1583 // is ill-formed.
1584 if (R.getNamingClass() &&
1585 contextClass != R.getNamingClass()->getCanonicalDecl() &&
1586 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
1587 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1588
John McCallaa81e162009-12-01 22:10:20 +00001589 // If we can prove that the current context is unrelated to all the
1590 // declaring classes, it can't be an implicit member reference (in
1591 // which case it's an error if any of those members are selected).
Argyrios Kyrtzidis0d8dc462011-04-14 00:46:47 +00001592 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
John McCallaa81e162009-12-01 22:10:20 +00001593 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1594
1595 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1596}
1597
1598/// Diagnose a reference to a field with no object available.
1599static void DiagnoseInstanceReference(Sema &SemaRef,
1600 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00001601 NamedDecl *rep,
1602 const DeclarationNameInfo &nameInfo) {
1603 SourceLocation Loc = nameInfo.getLoc();
John McCallaa81e162009-12-01 22:10:20 +00001604 SourceRange Range(Loc);
1605 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1606
John McCall5808ce42011-02-03 08:15:49 +00001607 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCallaa81e162009-12-01 22:10:20 +00001608 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1609 if (MD->isStatic()) {
1610 // "invalid use of member 'x' in static member function"
1611 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCall5808ce42011-02-03 08:15:49 +00001612 << Range << nameInfo.getName();
John McCallaa81e162009-12-01 22:10:20 +00001613 return;
1614 }
1615 }
1616
1617 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCall5808ce42011-02-03 08:15:49 +00001618 << nameInfo.getName() << Range;
John McCallaa81e162009-12-01 22:10:20 +00001619 return;
1620 }
1621
1622 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +00001623}
1624
John McCall578b69b2009-12-16 08:11:27 +00001625/// Diagnose an empty lookup.
1626///
1627/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001628bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1629 CorrectTypoContext CTC) {
John McCall578b69b2009-12-16 08:11:27 +00001630 DeclarationName Name = R.getLookupName();
1631
John McCall578b69b2009-12-16 08:11:27 +00001632 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001633 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001634 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1635 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001636 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001637 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001638 diagnostic_suggest = diag::err_undeclared_use_suggest;
1639 }
John McCall578b69b2009-12-16 08:11:27 +00001640
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001641 // If the original lookup was an unqualified lookup, fake an
1642 // unqualified lookup. This is useful when (for example) the
1643 // original lookup would not have found something because it was a
1644 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001645 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001646 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001647 if (isa<CXXRecordDecl>(DC)) {
1648 LookupQualifiedName(R, DC);
1649
1650 if (!R.empty()) {
1651 // Don't give errors about ambiguities in this lookup.
1652 R.suppressDiagnostics();
1653
1654 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1655 bool isInstance = CurMethod &&
1656 CurMethod->isInstance() &&
1657 DC == CurMethod->getParent();
1658
1659 // Give a code modification hint to insert 'this->'.
1660 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1661 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001662 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001663 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1664 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001665 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001666 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001667 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001668 Diag(R.getNameLoc(), diagnostic) << Name
1669 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1670 QualType DepThisType = DepMethod->getThisType(Context);
1671 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1672 R.getNameLoc(), DepThisType, false);
1673 TemplateArgumentListInfo TList;
1674 if (ULE->hasExplicitTemplateArgs())
1675 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001676
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001677 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001678 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001679 CXXDependentScopeMemberExpr *DepExpr =
1680 CXXDependentScopeMemberExpr::Create(
1681 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001682 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001683 R.getLookupNameInfo(), &TList);
1684 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001685 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001686 // FIXME: we should be able to handle this case too. It is correct
1687 // to add this-> here. This is a workaround for PR7947.
1688 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001689 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001690 } else {
John McCall578b69b2009-12-16 08:11:27 +00001691 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001692 }
John McCall578b69b2009-12-16 08:11:27 +00001693
1694 // Do we really want to note all of these?
1695 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1696 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1697
1698 // Tell the callee to try to recover.
1699 return false;
1700 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001701
1702 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001703 }
1704 }
1705
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001706 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001707 DeclarationName Corrected;
Daniel Dunbardc32cdf2010-06-02 15:46:52 +00001708 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001709 if (!R.empty()) {
1710 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1711 if (SS.isEmpty())
1712 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1713 << FixItHint::CreateReplacement(R.getNameLoc(),
1714 R.getLookupName().getAsString());
1715 else
1716 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1717 << Name << computeDeclContext(SS, false) << R.getLookupName()
1718 << SS.getRange()
1719 << FixItHint::CreateReplacement(R.getNameLoc(),
1720 R.getLookupName().getAsString());
1721 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1722 Diag(ND->getLocation(), diag::note_previous_decl)
1723 << ND->getDeclName();
1724
1725 // Tell the callee to try to recover.
1726 return false;
1727 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001728
Douglas Gregoraaf87162010-04-14 20:04:41 +00001729 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1730 // FIXME: If we ended up with a typo for a type name or
1731 // Objective-C class name, we're in trouble because the parser
1732 // is in the wrong place to recover. Suggest the typo
1733 // correction, but don't make it a fix-it since we're not going
1734 // to recover well anyway.
1735 if (SS.isEmpty())
1736 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1737 else
1738 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1739 << Name << computeDeclContext(SS, false) << R.getLookupName()
1740 << SS.getRange();
1741
1742 // Don't try to recover; it won't work.
1743 return true;
1744 }
1745 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001746 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001747 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001748 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +00001749 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001750 else
Douglas Gregord203a162010-01-01 00:15:04 +00001751 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001752 << Name << computeDeclContext(SS, false) << Corrected
1753 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001754 return true;
1755 }
Douglas Gregord203a162010-01-01 00:15:04 +00001756 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001757 }
1758
1759 // Emit a special diagnostic for failed member lookups.
1760 // FIXME: computing the declaration context might fail here (?)
1761 if (!SS.isEmpty()) {
1762 Diag(R.getNameLoc(), diag::err_no_member)
1763 << Name << computeDeclContext(SS, false)
1764 << SS.getRange();
1765 return true;
1766 }
1767
John McCall578b69b2009-12-16 08:11:27 +00001768 // Give up, we can't recover.
1769 Diag(R.getNameLoc(), diagnostic) << Name;
1770 return true;
1771}
1772
Douglas Gregorca45da02010-11-02 20:36:02 +00001773ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1774 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001775 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1776 if (!IDecl)
1777 return 0;
1778 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1779 if (!ClassImpDecl)
1780 return 0;
Douglas Gregorca45da02010-11-02 20:36:02 +00001781 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001782 if (!property)
1783 return 0;
1784 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregorca45da02010-11-02 20:36:02 +00001785 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1786 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001787 return 0;
1788 return property;
1789}
1790
Douglas Gregorca45da02010-11-02 20:36:02 +00001791bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1792 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1793 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1794 if (!IDecl)
1795 return false;
1796 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1797 if (!ClassImpDecl)
1798 return false;
1799 if (ObjCPropertyImplDecl *PIDecl
1800 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1801 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1802 PIDecl->getPropertyIvarDecl())
1803 return false;
1804
1805 return true;
1806}
1807
Douglas Gregor312eadb2011-04-24 05:37:28 +00001808ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1809 IdentifierInfo *II,
1810 SourceLocation NameLoc) {
1811 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001812 bool LookForIvars;
1813 if (Lookup.empty())
1814 LookForIvars = true;
1815 else if (CurMeth->isClassMethod())
1816 LookForIvars = false;
1817 else
1818 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahaniand0fbadd2011-01-26 00:57:01 +00001819 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1820 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001821 if (!LookForIvars)
1822 return 0;
1823
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001824 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1825 if (!IDecl)
1826 return 0;
1827 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001828 if (!ClassImpDecl)
1829 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001830 bool DynamicImplSeen = false;
Douglas Gregor312eadb2011-04-24 05:37:28 +00001831 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001832 if (!property)
1833 return 0;
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001834 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001835 DynamicImplSeen =
1836 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001837 // property implementation has a designated ivar. No need to assume a new
1838 // one.
1839 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1840 return 0;
1841 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001842 if (!DynamicImplSeen) {
Douglas Gregor312eadb2011-04-24 05:37:28 +00001843 QualType PropType = Context.getCanonicalType(property->getType());
1844 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001845 NameLoc, NameLoc,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001846 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian75049662010-12-15 23:29:04 +00001847 ObjCIvarDecl::Private,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001848 (Expr *)0, true);
1849 ClassImpDecl->addDecl(Ivar);
1850 IDecl->makeDeclVisibleInContext(Ivar, false);
1851 property->setPropertyIvarDecl(Ivar);
1852 return Ivar;
1853 }
1854 return 0;
1855}
1856
John McCall60d7b3a2010-08-24 06:29:42 +00001857ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001858 CXXScopeSpec &SS,
1859 UnqualifiedId &Id,
1860 bool HasTrailingLParen,
1861 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001862 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1863 "cannot be direct & operand and have a trailing lparen");
1864
1865 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001866 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001867
John McCall129e2df2009-11-30 22:42:35 +00001868 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001869
1870 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001871 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001872 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnara25777432010-08-11 22:01:17 +00001873 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001874
Abramo Bagnara25777432010-08-11 22:01:17 +00001875 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001876 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001877 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001878
John McCallf7a1a742009-11-24 19:00:30 +00001879 // C++ [temp.dep.expr]p3:
1880 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001881 // -- an identifier that was declared with a dependent type,
1882 // (note: handled after lookup)
1883 // -- a template-id that is dependent,
1884 // (note: handled in BuildTemplateIdExpr)
1885 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001886 // -- a nested-name-specifier that contains a class-name that
1887 // names a dependent type.
1888 // Determine whether this is a member of an unknown specialization;
1889 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001890 bool DependentID = false;
1891 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1892 Name.getCXXNameType()->isDependentType()) {
1893 DependentID = true;
1894 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001895 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001896 if (RequireCompleteDeclContext(SS, DC))
1897 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001898 } else {
1899 DependentID = true;
1900 }
1901 }
1902
Chris Lattner337e5502011-02-18 01:27:55 +00001903 if (DependentID)
Abramo Bagnara25777432010-08-11 22:01:17 +00001904 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001905 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001906
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001907 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001908 // Perform the required lookup.
Abramo Bagnara25777432010-08-11 22:01:17 +00001909 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001910 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001911 // Lookup the template name again to correctly establish the context in
1912 // which it was found. This is really unfortunate as we already did the
1913 // lookup to determine that it was a template name in the first place. If
1914 // this becomes a performance hit, we can work harder to preserve those
1915 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001916 bool MemberOfUnknownSpecialization;
1917 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1918 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001919
1920 if (MemberOfUnknownSpecialization ||
1921 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1922 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1923 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001924 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001925 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001926 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001928 // If the result might be in a dependent base class, this is a dependent
1929 // id-expression.
1930 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1931 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1932 TemplateArgs);
1933
John McCallf7a1a742009-11-24 19:00:30 +00001934 // If this reference is in an Objective-C method, then we need to do
1935 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001936 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001937 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001938 if (E.isInvalid())
1939 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001940
Chris Lattner337e5502011-02-18 01:27:55 +00001941 if (Expr *Ex = E.takeAs<Expr>())
1942 return Owned(Ex);
1943
1944 // Synthesize ivars lazily.
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001945 if (getLangOptions().ObjCDefaultSynthProperties &&
1946 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor312eadb2011-04-24 05:37:28 +00001947 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahaniande267602010-11-17 19:41:23 +00001948 if (const ObjCPropertyDecl *Property =
1949 canSynthesizeProvisionalIvar(II)) {
1950 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1951 Diag(Property->getLocation(), diag::note_property_declare);
1952 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001953 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1954 isAddressOfOperand);
Fariborz Jahaniande267602010-11-17 19:41:23 +00001955 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001956 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001957 // for further use, this must be set to false if in class method.
1958 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001959 }
Chris Lattner8a934232008-03-31 00:36:02 +00001960 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001961
John McCallf7a1a742009-11-24 19:00:30 +00001962 if (R.isAmbiguous())
1963 return ExprError();
1964
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001965 // Determine whether this name might be a candidate for
1966 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001967 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001968
John McCallf7a1a742009-11-24 19:00:30 +00001969 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001970 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001971 // in C90, extension in C99, forbidden in C++).
1972 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1973 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1974 if (D) R.addDecl(D);
1975 }
1976
1977 // If this name wasn't predeclared and if this is not a function
1978 // call, diagnose the problem.
1979 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001980 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001981 return ExprError();
1982
1983 assert(!R.empty() &&
1984 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001985
1986 // If we found an Objective-C instance variable, let
1987 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001988 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001989 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1990 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001991 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001992 assert(E.isInvalid() || E.get());
1993 return move(E);
1994 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001995 }
1996 }
Mike Stump1eb44332009-09-09 15:08:12 +00001997
John McCallf7a1a742009-11-24 19:00:30 +00001998 // This is guaranteed from this point on.
1999 assert(!R.empty() || ADL);
2000
John McCallaa81e162009-12-01 22:10:20 +00002001 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00002002 // C++ [class.mfct.non-static]p3:
2003 // When an id-expression that is not part of a class member access
2004 // syntax and not used to form a pointer to member is used in the
2005 // body of a non-static member function of class X, if name lookup
2006 // resolves the name in the id-expression to a non-static non-type
2007 // member of some class C, the id-expression is transformed into a
2008 // class member access expression using (*this) as the
2009 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00002010 //
2011 // But we don't actually need to do this for '&' operands if R
2012 // resolved to a function or overloaded function set, because the
2013 // expression is ill-formed if it actually works out to be a
2014 // non-static member function:
2015 //
2016 // C++ [expr.ref]p4:
2017 // Otherwise, if E1.E2 refers to a non-static member function. . .
2018 // [t]he expression can be used only as the left-hand operand of a
2019 // member function call.
2020 //
2021 // There are other safeguards against such uses, but it's important
2022 // to get this right here so that we don't end up making a
2023 // spuriously dependent expression if we're inside a dependent
2024 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00002025 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00002026 bool MightBeImplicitMember;
2027 if (!isAddressOfOperand)
2028 MightBeImplicitMember = true;
2029 else if (!SS.isEmpty())
2030 MightBeImplicitMember = false;
2031 else if (R.isOverloadedResult())
2032 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00002033 else if (R.isUnresolvableResult())
2034 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00002035 else
Francois Pichet87c2e122010-11-21 06:08:52 +00002036 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2037 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00002038
2039 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00002040 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00002041 }
2042
John McCallf7a1a742009-11-24 19:00:30 +00002043 if (TemplateArgs)
2044 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00002045
John McCallf7a1a742009-11-24 19:00:30 +00002046 return BuildDeclarationNameExpr(SS, R, ADL);
2047}
2048
John McCall3b4294e2009-12-16 12:17:52 +00002049/// Builds an expression which might be an implicit member expression.
John McCall60d7b3a2010-08-24 06:29:42 +00002050ExprResult
John McCall3b4294e2009-12-16 12:17:52 +00002051Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
2052 LookupResult &R,
2053 const TemplateArgumentListInfo *TemplateArgs) {
Richard Smith7a614d82011-06-11 17:19:42 +00002054 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
John McCall3b4294e2009-12-16 12:17:52 +00002055 case IMA_Instance:
2056 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
2057
John McCall3b4294e2009-12-16 12:17:52 +00002058 case IMA_Mixed:
2059 case IMA_Mixed_Unrelated:
2060 case IMA_Unresolved:
2061 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
2062
2063 case IMA_Static:
2064 case IMA_Mixed_StaticContext:
2065 case IMA_Unresolved_StaticContext:
2066 if (TemplateArgs)
2067 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
2068 return BuildDeclarationNameExpr(SS, R, false);
2069
2070 case IMA_Error_StaticContext:
2071 case IMA_Error_Unrelated:
John McCall5808ce42011-02-03 08:15:49 +00002072 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
2073 R.getLookupNameInfo());
John McCall3b4294e2009-12-16 12:17:52 +00002074 return ExprError();
2075 }
2076
2077 llvm_unreachable("unexpected instance member access kind");
2078 return ExprError();
2079}
2080
John McCall129e2df2009-11-30 22:42:35 +00002081/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2082/// declaration name, generally during template instantiation.
2083/// There's a large number of things which don't need to be done along
2084/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00002085ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002086Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002087 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00002088 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00002089 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00002090 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00002091
John McCall77bb1aa2010-05-01 00:40:08 +00002092 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00002093 return ExprError();
2094
Abramo Bagnara25777432010-08-11 22:01:17 +00002095 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00002096 LookupQualifiedName(R, DC);
2097
2098 if (R.isAmbiguous())
2099 return ExprError();
2100
2101 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002102 Diag(NameInfo.getLoc(), diag::err_no_member)
2103 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002104 return ExprError();
2105 }
2106
2107 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
2108}
2109
2110/// LookupInObjCMethod - The parser has read a name in, and Sema has
2111/// detected that we're currently inside an ObjC method. Perform some
2112/// additional lookup.
2113///
2114/// Ideally, most of this would be done by lookup, but there's
2115/// actually quite a lot of extra work involved.
2116///
2117/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00002118ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002119Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00002120 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00002121 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00002122 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002123
John McCallf7a1a742009-11-24 19:00:30 +00002124 // There are two cases to handle here. 1) scoped lookup could have failed,
2125 // in which case we should look for an ivar. 2) scoped lookup could have
2126 // found a decl, but that decl is outside the current instance method (i.e.
2127 // a global variable). In these two cases, we do a lookup for an ivar with
2128 // this name, if the lookup sucedes, we replace it our current decl.
2129
2130 // If we're in a class method, we don't normally want to look for
2131 // ivars. But if we don't find anything else, and there's an
2132 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00002133 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00002134
2135 bool LookForIvars;
2136 if (Lookup.empty())
2137 LookForIvars = true;
2138 else if (IsClassMethod)
2139 LookForIvars = false;
2140 else
2141 LookForIvars = (Lookup.isSingleResult() &&
2142 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00002143 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00002144 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00002145 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00002146 ObjCInterfaceDecl *ClassDeclared;
2147 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2148 // Diagnose using an ivar in a class method.
2149 if (IsClassMethod)
2150 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2151 << IV->getDeclName());
2152
2153 // If we're referencing an invalid decl, just return this as a silent
2154 // error node. The error diagnostic was already emitted on the decl.
2155 if (IV->isInvalidDecl())
2156 return ExprError();
2157
2158 // Check if referencing a field with __attribute__((deprecated)).
2159 if (DiagnoseUseOfDecl(IV, Loc))
2160 return ExprError();
2161
2162 // Diagnose the use of an ivar outside of the declaring class.
2163 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2164 ClassDeclared != IFace)
2165 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2166
2167 // FIXME: This should use a new expr for a direct reference, don't
2168 // turn this into Self->ivar, just return a BareIVarExpr or something.
2169 IdentifierInfo &II = Context.Idents.get("self");
2170 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002171 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00002172 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00002173 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00002174 SelfName, false, false);
2175 if (SelfExpr.isInvalid())
2176 return ExprError();
2177
John Wiegley429bb272011-04-08 18:41:53 +00002178 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2179 if (SelfExpr.isInvalid())
2180 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00002181
John McCallf7a1a742009-11-24 19:00:30 +00002182 MarkDeclarationReferenced(Loc, IV);
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00002183 Expr *base = SelfExpr.take();
2184 base = base->IgnoreParenImpCasts();
2185 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(base)) {
2186 const NamedDecl *ND = DE->getDecl();
2187 if (!isa<ImplicitParamDecl>(ND)) {
Fariborz Jahanianeefa76e2011-04-15 17:04:42 +00002188 // relax the rule such that it is allowed to have a shadow 'self'
2189 // where stand-alone ivar can be found in this 'self' object.
2190 // This is to match gcc's behavior.
2191 ObjCInterfaceDecl *selfIFace = 0;
2192 if (const ObjCObjectPointerType *OPT =
2193 base->getType()->getAsObjCInterfacePointerType())
2194 selfIFace = OPT->getInterfaceDecl();
2195 if (!selfIFace ||
2196 !selfIFace->lookupInstanceVariable(IV->getIdentifier())) {
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00002197 Diag(Loc, diag::error_implicit_ivar_access)
2198 << IV->getDeclName();
2199 Diag(ND->getLocation(), diag::note_declared_at);
2200 return ExprError();
2201 }
Fariborz Jahanianeefa76e2011-04-15 17:04:42 +00002202 }
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00002203 }
John McCallf7a1a742009-11-24 19:00:30 +00002204 return Owned(new (Context)
2205 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00002206 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00002207 }
Chris Lattneraec43db2010-04-12 05:10:17 +00002208 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00002209 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00002210 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00002211 ObjCInterfaceDecl *ClassDeclared;
2212 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2213 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2214 IFace == ClassDeclared)
2215 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2216 }
2217 }
2218
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002219 if (Lookup.empty() && II && AllowBuiltinCreation) {
2220 // FIXME. Consolidate this with similar code in LookupName.
2221 if (unsigned BuiltinID = II->getBuiltinID()) {
2222 if (!(getLangOptions().CPlusPlus &&
2223 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2224 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2225 S, Lookup.isForRedeclaration(),
2226 Lookup.getNameLoc());
2227 if (D) Lookup.addDecl(D);
2228 }
2229 }
2230 }
John McCallf7a1a742009-11-24 19:00:30 +00002231 // Sentinel value saying that we didn't do anything special.
2232 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002233}
John McCallba135432009-11-21 08:51:07 +00002234
John McCall6bb80172010-03-30 21:47:33 +00002235/// \brief Cast a base object to a member's actual type.
2236///
2237/// Logically this happens in three phases:
2238///
2239/// * First we cast from the base type to the naming class.
2240/// The naming class is the class into which we were looking
2241/// when we found the member; it's the qualifier type if a
2242/// qualifier was provided, and otherwise it's the base type.
2243///
2244/// * Next we cast from the naming class to the declaring class.
2245/// If the member we found was brought into a class's scope by
2246/// a using declaration, this is that class; otherwise it's
2247/// the class declaring the member.
2248///
2249/// * Finally we cast from the declaring class to the "true"
2250/// declaring class of the member. This conversion does not
2251/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002252ExprResult
2253Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002254 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002255 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002256 NamedDecl *Member) {
2257 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2258 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002259 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002260
Douglas Gregor5fccd362010-03-03 23:55:11 +00002261 QualType DestRecordType;
2262 QualType DestType;
2263 QualType FromRecordType;
2264 QualType FromType = From->getType();
2265 bool PointerConversions = false;
2266 if (isa<FieldDecl>(Member)) {
2267 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002268
Douglas Gregor5fccd362010-03-03 23:55:11 +00002269 if (FromType->getAs<PointerType>()) {
2270 DestType = Context.getPointerType(DestRecordType);
2271 FromRecordType = FromType->getPointeeType();
2272 PointerConversions = true;
2273 } else {
2274 DestType = DestRecordType;
2275 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002276 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002277 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2278 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002279 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002280
Douglas Gregor5fccd362010-03-03 23:55:11 +00002281 DestType = Method->getThisType(Context);
2282 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002283
Douglas Gregor5fccd362010-03-03 23:55:11 +00002284 if (FromType->getAs<PointerType>()) {
2285 FromRecordType = FromType->getPointeeType();
2286 PointerConversions = true;
2287 } else {
2288 FromRecordType = FromType;
2289 DestType = DestRecordType;
2290 }
2291 } else {
2292 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002293 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002294 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002295
Douglas Gregor5fccd362010-03-03 23:55:11 +00002296 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002297 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002298
Douglas Gregor5fccd362010-03-03 23:55:11 +00002299 // If the unqualified types are the same, no conversion is necessary.
2300 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002301 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002302
John McCall6bb80172010-03-30 21:47:33 +00002303 SourceRange FromRange = From->getSourceRange();
2304 SourceLocation FromLoc = FromRange.getBegin();
2305
John McCall5baba9d2010-08-25 10:28:54 +00002306 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00002307
Douglas Gregor5fccd362010-03-03 23:55:11 +00002308 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002309 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002310 // class name.
2311 //
2312 // If the member was a qualified name and the qualified referred to a
2313 // specific base subobject type, we'll cast to that intermediate type
2314 // first and then to the object in which the member is declared. That allows
2315 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2316 //
2317 // class Base { public: int x; };
2318 // class Derived1 : public Base { };
2319 // class Derived2 : public Base { };
2320 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2321 //
2322 // void VeryDerived::f() {
2323 // x = 17; // error: ambiguous base subobjects
2324 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2325 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002326 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002327 QualType QType = QualType(Qualifier->getAsType(), 0);
2328 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2329 assert(QType->isRecordType() && "lookup done with non-record type");
2330
2331 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2332
2333 // In C++98, the qualifier type doesn't actually have to be a base
2334 // type of the object type, in which case we just ignore it.
2335 // Otherwise build the appropriate casts.
2336 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002337 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002338 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002339 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002340 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002341
Douglas Gregor5fccd362010-03-03 23:55:11 +00002342 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002343 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002344 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2345 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002346
2347 FromType = QType;
2348 FromRecordType = QRecordType;
2349
2350 // If the qualifier type was the same as the destination type,
2351 // we're done.
2352 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002353 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002354 }
2355 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002356
John McCall6bb80172010-03-30 21:47:33 +00002357 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002358
John McCall6bb80172010-03-30 21:47:33 +00002359 // If we actually found the member through a using declaration, cast
2360 // down to the using declaration's type.
2361 //
2362 // Pointer equality is fine here because only one declaration of a
2363 // class ever has member declarations.
2364 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2365 assert(isa<UsingShadowDecl>(FoundDecl));
2366 QualType URecordType = Context.getTypeDeclType(
2367 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2368
2369 // We only need to do this if the naming-class to declaring-class
2370 // conversion is non-trivial.
2371 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2372 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002373 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002374 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002375 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002376 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002377
John McCall6bb80172010-03-30 21:47:33 +00002378 QualType UType = URecordType;
2379 if (PointerConversions)
2380 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002381 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2382 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002383 FromType = UType;
2384 FromRecordType = URecordType;
2385 }
2386
2387 // We don't do access control for the conversion from the
2388 // declaring class to the true declaring class.
2389 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002390 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002391
John McCallf871d0c2010-08-07 06:22:56 +00002392 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002393 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2394 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002395 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002396 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002397
John Wiegley429bb272011-04-08 18:41:53 +00002398 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2399 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002400}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002401
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002402/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00002403static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00002404 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00002405 DeclAccessPair FoundDecl,
Abramo Bagnara25777432010-08-11 22:01:17 +00002406 const DeclarationNameInfo &MemberNameInfo,
2407 QualType Ty,
John McCallf89e55a2010-11-18 06:31:45 +00002408 ExprValueKind VK, ExprObjectKind OK,
John McCallf7a1a742009-11-24 19:00:30 +00002409 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregor40d96a62011-02-28 21:54:11 +00002410 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnara25777432010-08-11 22:01:17 +00002411 Member, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002412 TemplateArgs, Ty, VK, OK);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002413}
2414
John McCalldfa1edb2010-11-23 20:48:44 +00002415static ExprResult
2416BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2417 const CXXScopeSpec &SS, FieldDecl *Field,
2418 DeclAccessPair FoundDecl,
2419 const DeclarationNameInfo &MemberNameInfo) {
2420 // x.a is an l-value if 'a' has a reference type. Otherwise:
2421 // x.a is an l-value/x-value/pr-value if the base is (and note
2422 // that *x is always an l-value), except that if the base isn't
2423 // an ordinary object then we must have an rvalue.
2424 ExprValueKind VK = VK_LValue;
2425 ExprObjectKind OK = OK_Ordinary;
2426 if (!IsArrow) {
2427 if (BaseExpr->getObjectKind() == OK_Ordinary)
2428 VK = BaseExpr->getValueKind();
2429 else
2430 VK = VK_RValue;
2431 }
2432 if (VK != VK_RValue && Field->isBitField())
2433 OK = OK_BitField;
2434
2435 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2436 QualType MemberType = Field->getType();
2437 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2438 MemberType = Ref->getPointeeType();
2439 VK = VK_LValue;
2440 } else {
2441 QualType BaseType = BaseExpr->getType();
2442 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2443
2444 Qualifiers BaseQuals = BaseType.getQualifiers();
2445
2446 // GC attributes are never picked up by members.
2447 BaseQuals.removeObjCGCAttr();
2448
2449 // CVR attributes from the base are picked up by members,
2450 // except that 'mutable' members don't pick up 'const'.
2451 if (Field->isMutable()) BaseQuals.removeConst();
2452
2453 Qualifiers MemberQuals
2454 = S.Context.getCanonicalType(MemberType).getQualifiers();
2455
2456 // TR 18037 does not allow fields to be declared with address spaces.
2457 assert(!MemberQuals.hasAddressSpace());
2458
2459 Qualifiers Combined = BaseQuals + MemberQuals;
2460 if (Combined != MemberQuals)
2461 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2462 }
2463
2464 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
John Wiegley429bb272011-04-08 18:41:53 +00002465 ExprResult Base =
2466 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2467 FoundDecl, Field);
2468 if (Base.isInvalid())
John McCalldfa1edb2010-11-23 20:48:44 +00002469 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00002470 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
John McCalldfa1edb2010-11-23 20:48:44 +00002471 Field, FoundDecl, MemberNameInfo,
2472 MemberType, VK, OK));
2473}
2474
John McCallaa81e162009-12-01 22:10:20 +00002475/// Builds an implicit member access expression. The current context
2476/// is known to be an instance method, and the given unqualified lookup
2477/// set is known to contain only instance members, at least one of which
2478/// is from an appropriate type.
John McCall60d7b3a2010-08-24 06:29:42 +00002479ExprResult
John McCallaa81e162009-12-01 22:10:20 +00002480Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2481 LookupResult &R,
2482 const TemplateArgumentListInfo *TemplateArgs,
2483 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00002484 assert(!R.empty() && !R.isAmbiguous());
2485
John McCall5808ce42011-02-03 08:15:49 +00002486 SourceLocation loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00002487
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002488 // We may have found a field within an anonymous union or struct
2489 // (C++ [class.union]).
John McCallf7a1a742009-11-24 19:00:30 +00002490 // FIXME: template-ids inside anonymous structs?
Francois Pichet87c2e122010-11-21 06:08:52 +00002491 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCall5808ce42011-02-03 08:15:49 +00002492 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet87c2e122010-11-21 06:08:52 +00002493
John McCall5808ce42011-02-03 08:15:49 +00002494 // If this is known to be an instance access, go ahead and build an
2495 // implicit 'this' expression now.
John McCallaa81e162009-12-01 22:10:20 +00002496 // 'this' expression now.
Richard Smith7a614d82011-06-11 17:19:42 +00002497 QualType ThisTy = getAndCaptureCurrentThisType();
2498 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
John McCall5808ce42011-02-03 08:15:49 +00002499
John McCall5808ce42011-02-03 08:15:49 +00002500 Expr *baseExpr = 0; // null signifies implicit access
John McCallaa81e162009-12-01 22:10:20 +00002501 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00002502 SourceLocation Loc = R.getNameLoc();
2503 if (SS.getRange().isValid())
2504 Loc = SS.getRange().getBegin();
Richard Smith7a614d82011-06-11 17:19:42 +00002505 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00002506 }
2507
Richard Smith7a614d82011-06-11 17:19:42 +00002508 return BuildMemberReferenceExpr(baseExpr, ThisTy,
John McCallaa81e162009-12-01 22:10:20 +00002509 /*OpLoc*/ SourceLocation(),
2510 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00002511 SS,
2512 /*FirstQualifierInScope*/ 0,
2513 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00002514}
2515
John McCallf7a1a742009-11-24 19:00:30 +00002516bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002517 const LookupResult &R,
2518 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002519 // Only when used directly as the postfix-expression of a call.
2520 if (!HasTrailingLParen)
2521 return false;
2522
2523 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002524 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002525 return false;
2526
2527 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002528 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002529 return false;
2530
2531 // Turn off ADL when we find certain kinds of declarations during
2532 // normal lookup:
2533 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2534 NamedDecl *D = *I;
2535
2536 // C++0x [basic.lookup.argdep]p3:
2537 // -- a declaration of a class member
2538 // Since using decls preserve this property, we check this on the
2539 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002540 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002541 return false;
2542
2543 // C++0x [basic.lookup.argdep]p3:
2544 // -- a block-scope function declaration that is not a
2545 // using-declaration
2546 // NOTE: we also trigger this for function templates (in fact, we
2547 // don't check the decl type at all, since all other decl types
2548 // turn off ADL anyway).
2549 if (isa<UsingShadowDecl>(D))
2550 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2551 else if (D->getDeclContext()->isFunctionOrMethod())
2552 return false;
2553
2554 // C++0x [basic.lookup.argdep]p3:
2555 // -- a declaration that is neither a function or a function
2556 // template
2557 // And also for builtin functions.
2558 if (isa<FunctionDecl>(D)) {
2559 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2560
2561 // But also builtin functions.
2562 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2563 return false;
2564 } else if (!isa<FunctionTemplateDecl>(D))
2565 return false;
2566 }
2567
2568 return true;
2569}
2570
2571
John McCallba135432009-11-21 08:51:07 +00002572/// Diagnoses obvious problems with the use of the given declaration
2573/// as an expression. This is only actually called for lookups that
2574/// were not overloaded, and it doesn't promise that the declaration
2575/// will in fact be used.
2576static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002577 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002578 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2579 return true;
2580 }
2581
2582 if (isa<ObjCInterfaceDecl>(D)) {
2583 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2584 return true;
2585 }
2586
2587 if (isa<NamespaceDecl>(D)) {
2588 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2589 return true;
2590 }
2591
2592 return false;
2593}
2594
John McCall60d7b3a2010-08-24 06:29:42 +00002595ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002596Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002597 LookupResult &R,
2598 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002599 // If this is a single, fully-resolved result and we don't need ADL,
2600 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002601 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002602 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2603 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002604
2605 // We only need to check the declaration if there's exactly one
2606 // result, because in the overloaded case the results can only be
2607 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002608 if (R.isSingleResult() &&
2609 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002610 return ExprError();
2611
John McCallc373d482010-01-27 01:50:18 +00002612 // Otherwise, just build an unresolved lookup expression. Suppress
2613 // any lookup-related diagnostics; we'll hash these out later, when
2614 // we've picked a target.
2615 R.suppressDiagnostics();
2616
John McCallba135432009-11-21 08:51:07 +00002617 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002618 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002619 SS.getWithLocInContext(Context),
2620 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002621 NeedsADL, R.isOverloadedResult(),
2622 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002623
2624 return Owned(ULE);
2625}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002626
John McCallba135432009-11-21 08:51:07 +00002627/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002628ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002629Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002630 const DeclarationNameInfo &NameInfo,
2631 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002632 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002633 assert(!isa<FunctionTemplateDecl>(D) &&
2634 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002635
Abramo Bagnara25777432010-08-11 22:01:17 +00002636 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002637 if (CheckDeclInExpr(*this, Loc, D))
2638 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002639
Douglas Gregor9af2f522009-12-01 16:58:18 +00002640 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2641 // Specifically diagnose references to class templates that are missing
2642 // a template argument list.
2643 Diag(Loc, diag::err_template_decl_ref)
2644 << Template << SS.getRange();
2645 Diag(Template->getLocation(), diag::note_template_decl_here);
2646 return ExprError();
2647 }
2648
2649 // Make sure that we're referring to a value.
2650 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2651 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002652 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002653 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002654 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002655 return ExprError();
2656 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002657
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002658 // Check whether this declaration can be used. Note that we suppress
2659 // this check when we're going to perform argument-dependent lookup
2660 // on this function name, because this might not be the function
2661 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002662 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002663 return ExprError();
2664
Steve Naroffdd972f22008-09-05 22:11:13 +00002665 // Only create DeclRefExpr's for valid Decl's.
2666 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002667 return ExprError();
2668
John McCall5808ce42011-02-03 08:15:49 +00002669 // Handle members of anonymous structs and unions. If we got here,
2670 // and the reference is to a class member indirect field, then this
2671 // must be the subject of a pointer-to-member expression.
2672 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2673 if (!indirectField->isCXXClassMember())
2674 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2675 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002676
Chris Lattner639e2d32008-10-20 05:16:36 +00002677 // If the identifier reference is inside a block, and it refers to a value
2678 // that is outside the block, create a BlockDeclRefExpr instead of a
2679 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2680 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002681 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002682 // We do not do this for things like enum constants, global variables, etc,
2683 // as they do not get snapshotted.
2684 //
John McCall6b5a61b2011-02-07 10:33:21 +00002685 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002686 case CR_Error:
2687 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002688
John McCall469a1eb2011-02-02 13:00:07 +00002689 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002690 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2691 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2692
2693 case CR_CaptureByRef:
2694 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2695 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002696
2697 case CR_NoCapture: {
2698 // If this reference is not in a block or if the referenced
2699 // variable is within the block, create a normal DeclRefExpr.
2700
2701 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002702 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002703
2704 switch (D->getKind()) {
2705 // Ignore all the non-ValueDecl kinds.
2706#define ABSTRACT_DECL(kind)
2707#define VALUE(type, base)
2708#define DECL(type, base) \
2709 case Decl::type:
2710#include "clang/AST/DeclNodes.inc"
2711 llvm_unreachable("invalid value decl kind");
2712 return ExprError();
2713
2714 // These shouldn't make it here.
2715 case Decl::ObjCAtDefsField:
2716 case Decl::ObjCIvar:
2717 llvm_unreachable("forming non-member reference to ivar?");
2718 return ExprError();
2719
2720 // Enum constants are always r-values and never references.
2721 // Unresolved using declarations are dependent.
2722 case Decl::EnumConstant:
2723 case Decl::UnresolvedUsingValue:
2724 valueKind = VK_RValue;
2725 break;
2726
2727 // Fields and indirect fields that got here must be for
2728 // pointer-to-member expressions; we just call them l-values for
2729 // internal consistency, because this subexpression doesn't really
2730 // exist in the high-level semantics.
2731 case Decl::Field:
2732 case Decl::IndirectField:
2733 assert(getLangOptions().CPlusPlus &&
2734 "building reference to field in C?");
2735
2736 // These can't have reference type in well-formed programs, but
2737 // for internal consistency we do this anyway.
2738 type = type.getNonReferenceType();
2739 valueKind = VK_LValue;
2740 break;
2741
2742 // Non-type template parameters are either l-values or r-values
2743 // depending on the type.
2744 case Decl::NonTypeTemplateParm: {
2745 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2746 type = reftype->getPointeeType();
2747 valueKind = VK_LValue; // even if the parameter is an r-value reference
2748 break;
2749 }
2750
2751 // For non-references, we need to strip qualifiers just in case
2752 // the template parameter was declared as 'const int' or whatever.
2753 valueKind = VK_RValue;
2754 type = type.getUnqualifiedType();
2755 break;
2756 }
2757
2758 case Decl::Var:
2759 // In C, "extern void blah;" is valid and is an r-value.
2760 if (!getLangOptions().CPlusPlus &&
2761 !type.hasQualifiers() &&
2762 type->isVoidType()) {
2763 valueKind = VK_RValue;
2764 break;
2765 }
2766 // fallthrough
2767
2768 case Decl::ImplicitParam:
2769 case Decl::ParmVar:
2770 // These are always l-values.
2771 valueKind = VK_LValue;
2772 type = type.getNonReferenceType();
2773 break;
2774
2775 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002776 const FunctionType *fty = type->castAs<FunctionType>();
2777
2778 // If we're referring to a function with an __unknown_anytype
2779 // result type, make the entire expression __unknown_anytype.
2780 if (fty->getResultType() == Context.UnknownAnyTy) {
2781 type = Context.UnknownAnyTy;
2782 valueKind = VK_RValue;
2783 break;
2784 }
2785
John McCall76a40212011-02-09 01:13:10 +00002786 // Functions are l-values in C++.
2787 if (getLangOptions().CPlusPlus) {
2788 valueKind = VK_LValue;
2789 break;
2790 }
2791
2792 // C99 DR 316 says that, if a function type comes from a
2793 // function definition (without a prototype), that type is only
2794 // used for checking compatibility. Therefore, when referencing
2795 // the function, we pretend that we don't have the full function
2796 // type.
John McCall755d8492011-04-12 00:42:48 +00002797 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2798 isa<FunctionProtoType>(fty))
2799 type = Context.getFunctionNoProtoType(fty->getResultType(),
2800 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002801
2802 // Functions are r-values in C.
2803 valueKind = VK_RValue;
2804 break;
2805 }
2806
2807 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002808 // If we're referring to a method with an __unknown_anytype
2809 // result type, make the entire expression __unknown_anytype.
2810 // This should only be possible with a type written directly.
2811 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2812 if (proto->getResultType() == Context.UnknownAnyTy) {
2813 type = Context.UnknownAnyTy;
2814 valueKind = VK_RValue;
2815 break;
2816 }
2817
John McCall76a40212011-02-09 01:13:10 +00002818 // C++ methods are l-values if static, r-values if non-static.
2819 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2820 valueKind = VK_LValue;
2821 break;
2822 }
2823 // fallthrough
2824
2825 case Decl::CXXConversion:
2826 case Decl::CXXDestructor:
2827 case Decl::CXXConstructor:
2828 valueKind = VK_RValue;
2829 break;
2830 }
2831
2832 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2833 }
2834
John McCall469a1eb2011-02-02 13:00:07 +00002835 }
John McCallf89e55a2010-11-18 06:31:45 +00002836
John McCall6b5a61b2011-02-07 10:33:21 +00002837 llvm_unreachable("unknown capture result");
2838 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002839}
2840
John McCall755d8492011-04-12 00:42:48 +00002841ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002842 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002843
Reid Spencer5f016e22007-07-11 17:01:13 +00002844 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002845 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002846 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2847 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2848 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002849 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002850
Chris Lattnerfa28b302008-01-12 08:14:25 +00002851 // Pre-defined identifiers are of type char[x], where x is the length of the
2852 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002853
Anders Carlsson3a082d82009-09-08 18:24:21 +00002854 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002855 if (!currentDecl && getCurBlock())
2856 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002857 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002858 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002859 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002860 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002861
Anders Carlsson773f3972009-09-11 01:22:35 +00002862 QualType ResTy;
2863 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2864 ResTy = Context.DependentTy;
2865 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002866 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002867
Anders Carlsson773f3972009-09-11 01:22:35 +00002868 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002869 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002870 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2871 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002872 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002873}
2874
John McCall60d7b3a2010-08-24 06:29:42 +00002875ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002876 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002877 bool Invalid = false;
2878 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2879 if (Invalid)
2880 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002881
Benjamin Kramerddeea562010-02-27 13:44:12 +00002882 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2883 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002884 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002885 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002886
Chris Lattnere8337df2009-12-30 21:19:39 +00002887 QualType Ty;
2888 if (!getLangOptions().CPlusPlus)
2889 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2890 else if (Literal.isWide())
2891 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002892 else if (Literal.isMultiChar())
2893 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002894 else
2895 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002896
Sebastian Redle91b3bc2009-01-20 22:23:13 +00002897 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2898 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00002899 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002900}
2901
John McCall60d7b3a2010-08-24 06:29:42 +00002902ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002903 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002904 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2905 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002906 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00002907 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002908 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002909 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002910 }
Ted Kremenek28396602009-01-13 23:19:12 +00002911
Reid Spencer5f016e22007-07-11 17:01:13 +00002912 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002913 // Add padding so that NumericLiteralParser can overread by one character.
2914 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002915 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002916
Reid Spencer5f016e22007-07-11 17:01:13 +00002917 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002918 bool Invalid = false;
2919 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2920 if (Invalid)
2921 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002922
Mike Stump1eb44332009-09-09 15:08:12 +00002923 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002924 Tok.getLocation(), PP);
2925 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002926 return ExprError();
2927
Chris Lattner5d661452007-08-26 03:42:43 +00002928 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002929
Chris Lattner5d661452007-08-26 03:42:43 +00002930 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002931 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002932 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002933 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002934 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002935 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002936 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002937 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002938
2939 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2940
John McCall94c939d2009-12-24 09:08:04 +00002941 using llvm::APFloat;
2942 APFloat Val(Format);
2943
2944 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002945
2946 // Overflow is always an error, but underflow is only an error if
2947 // we underflowed to zero (APFloat reports denormals as underflow).
2948 if ((result & APFloat::opOverflow) ||
2949 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002950 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002951 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002952 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002953 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002954 APFloat::getLargest(Format).toString(buffer);
2955 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002956 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002957 APFloat::getSmallest(Format).toString(buffer);
2958 }
2959
2960 Diag(Tok.getLocation(), diagnostic)
2961 << Ty
2962 << llvm::StringRef(buffer.data(), buffer.size());
2963 }
2964
2965 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002966 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002967
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002968 if (Ty == Context.DoubleTy) {
2969 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002970 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002971 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2972 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002973 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002974 }
2975 }
Chris Lattner5d661452007-08-26 03:42:43 +00002976 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002977 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002978 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002979 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002980
Neil Boothb9449512007-08-29 22:00:19 +00002981 // long long is a C99 feature.
2982 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002983 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002984 Diag(Tok.getLocation(), diag::ext_longlong);
2985
Reid Spencer5f016e22007-07-11 17:01:13 +00002986 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00002987 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002988
Reid Spencer5f016e22007-07-11 17:01:13 +00002989 if (Literal.GetIntegerValue(ResultVal)) {
2990 // If this value didn't fit into uintmax_t, warn and force to ull.
2991 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002992 Ty = Context.UnsignedLongLongTy;
2993 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002994 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002995 } else {
2996 // If this value fits into a ULL, try to figure out what else it fits into
2997 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002998
Reid Spencer5f016e22007-07-11 17:01:13 +00002999 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3000 // be an unsigned int.
3001 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3002
3003 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003004 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00003005 if (!Literal.isLong && !Literal.isLongLong) {
3006 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003007 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00003008
Reid Spencer5f016e22007-07-11 17:01:13 +00003009 // Does it fit in a unsigned int?
3010 if (ResultVal.isIntN(IntSize)) {
3011 // Does it fit in a signed int?
3012 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003013 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003014 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003015 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003016 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00003017 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003018 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003019
Reid Spencer5f016e22007-07-11 17:01:13 +00003020 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00003021 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003022 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00003023
Reid Spencer5f016e22007-07-11 17:01:13 +00003024 // Does it fit in a unsigned long?
3025 if (ResultVal.isIntN(LongSize)) {
3026 // Does it fit in a signed long?
3027 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003028 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003029 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003030 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003031 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00003032 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003033 }
3034
Reid Spencer5f016e22007-07-11 17:01:13 +00003035 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003036 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003037 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00003038
Reid Spencer5f016e22007-07-11 17:01:13 +00003039 // Does it fit in a unsigned long long?
3040 if (ResultVal.isIntN(LongLongSize)) {
3041 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00003042 // To be compatible with MSVC, hex integer literals ending with the
3043 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00003044 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3045 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00003046 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003047 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003048 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003049 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00003050 }
3051 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003052
Reid Spencer5f016e22007-07-11 17:01:13 +00003053 // If we still couldn't decide a type, we probably have something that
3054 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003055 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003056 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003057 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003058 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00003059 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003060
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003061 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003062 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00003063 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003064 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00003065 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003066
Chris Lattner5d661452007-08-26 03:42:43 +00003067 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3068 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00003069 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003070 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00003071
3072 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00003073}
3074
John McCall60d7b3a2010-08-24 06:29:42 +00003075ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00003076 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003077 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00003078 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00003079}
3080
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003081static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3082 SourceLocation Loc,
3083 SourceRange ArgRange) {
3084 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3085 // scalar or vector data type argument..."
3086 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3087 // type (C99 6.2.5p18) or void.
3088 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3089 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3090 << T << ArgRange;
3091 return true;
3092 }
3093
3094 assert((T->isVoidType() || !T->isIncompleteType()) &&
3095 "Scalar types should always be complete");
3096 return false;
3097}
3098
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003099static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3100 SourceLocation Loc,
3101 SourceRange ArgRange,
3102 UnaryExprOrTypeTrait TraitKind) {
3103 // C99 6.5.3.4p1:
3104 if (T->isFunctionType()) {
3105 // alignof(function) is allowed as an extension.
3106 if (TraitKind == UETT_SizeOf)
3107 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
3108 return false;
3109 }
3110
3111 // Allow sizeof(void)/alignof(void) as an extension.
3112 if (T->isVoidType()) {
3113 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
3114 return false;
3115 }
3116
3117 return true;
3118}
3119
3120static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3121 SourceLocation Loc,
3122 SourceRange ArgRange,
3123 UnaryExprOrTypeTrait TraitKind) {
3124 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
3125 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
3126 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3127 << T << (TraitKind == UETT_SizeOf)
3128 << ArgRange;
3129 return true;
3130 }
3131
3132 return false;
3133}
3134
Chandler Carruth9d342d02011-05-26 08:53:10 +00003135/// \brief Check the constrains on expression operands to unary type expression
3136/// and type traits.
3137///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003138/// Completes any types necessary and validates the constraints on the operand
3139/// expression. The logic mostly mirrors the type-based overload, but may modify
3140/// the expression as it completes the type for that expression through template
3141/// instantiation, etc.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003142bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
3143 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003144 QualType ExprTy = Op->getType();
3145
3146 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3147 // the result is the size of the referenced type."
3148 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3149 // result shall be the alignment of the referenced type."
3150 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3151 ExprTy = Ref->getPointeeType();
3152
3153 if (ExprKind == UETT_VecStep)
3154 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
3155 Op->getSourceRange());
3156
3157 // Whitelist some types as extensions
3158 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
3159 Op->getSourceRange(), ExprKind))
3160 return false;
3161
3162 if (RequireCompleteExprType(Op,
3163 PDiag(diag::err_sizeof_alignof_incomplete_type)
3164 << ExprKind << Op->getSourceRange(),
3165 std::make_pair(SourceLocation(), PDiag(0))))
3166 return true;
3167
3168 // Completeing the expression's type may have changed it.
3169 ExprTy = Op->getType();
3170 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3171 ExprTy = Ref->getPointeeType();
3172
3173 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
3174 Op->getSourceRange(), ExprKind))
3175 return true;
3176
Nico Webercf739922011-06-15 02:47:03 +00003177 if (ExprKind == UETT_SizeOf) {
3178 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
3179 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3180 QualType OType = PVD->getOriginalType();
3181 QualType Type = PVD->getType();
3182 if (Type->isPointerType() && OType->isArrayType()) {
3183 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
3184 << Type << OType;
3185 Diag(PVD->getLocation(), diag::note_declared_at);
3186 }
3187 }
3188 }
3189 }
3190
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003191 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00003192}
3193
3194/// \brief Check the constraints on operands to unary expression and type
3195/// traits.
3196///
3197/// This will complete any types necessary, and validate the various constraints
3198/// on those operands.
3199///
Reid Spencer5f016e22007-07-11 17:01:13 +00003200/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003201/// C99 6.3.2.1p[2-4] all state:
3202/// Except when it is the operand of the sizeof operator ...
3203///
3204/// C++ [expr.sizeof]p4
3205/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3206/// standard conversions are not applied to the operand of sizeof.
3207///
3208/// This policy is followed for all of the unary trait expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003209bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
3210 SourceLocation OpLoc,
3211 SourceRange ExprRange,
3212 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl28507842009-02-26 14:39:58 +00003213 if (exprType->isDependentType())
3214 return false;
3215
Sebastian Redl5d484e82009-11-23 17:18:46 +00003216 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3217 // the result is the size of the referenced type."
3218 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3219 // result shall be the alignment of the referenced type."
3220 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
3221 exprType = Ref->getPointeeType();
3222
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003223 if (ExprKind == UETT_VecStep)
3224 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003225
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003226 // Whitelist some types as extensions
3227 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
3228 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003229 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003230
Chris Lattner1efaa952009-04-24 00:30:45 +00003231 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00003232 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003233 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003234 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003235
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003236 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
3237 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003238 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003239
Chris Lattner1efaa952009-04-24 00:30:45 +00003240 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003241}
3242
Chandler Carruth9d342d02011-05-26 08:53:10 +00003243static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003244 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003245
Mike Stump1eb44332009-09-09 15:08:12 +00003246 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003247 if (isa<DeclRefExpr>(E))
3248 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003249
3250 // Cannot know anything else if the expression is dependent.
3251 if (E->isTypeDependent())
3252 return false;
3253
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003254 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003255 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3256 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003257 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003258 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003259
3260 // Alignment of a field access is always okay, so long as it isn't a
3261 // bit-field.
3262 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003263 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003264 return false;
3265
Chandler Carruth9d342d02011-05-26 08:53:10 +00003266 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003267}
3268
Chandler Carruth9d342d02011-05-26 08:53:10 +00003269bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003270 E = E->IgnoreParens();
3271
3272 // Cannot know anything else if the expression is dependent.
3273 if (E->isTypeDependent())
3274 return false;
3275
Chandler Carruth9d342d02011-05-26 08:53:10 +00003276 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003277}
3278
Douglas Gregorba498172009-03-13 21:01:28 +00003279/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003280ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003281Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3282 SourceLocation OpLoc,
3283 UnaryExprOrTypeTrait ExprKind,
3284 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003285 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003286 return ExprError();
3287
John McCalla93c9342009-12-07 02:54:59 +00003288 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003289
Douglas Gregorba498172009-03-13 21:01:28 +00003290 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003291 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003292 return ExprError();
3293
3294 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003295 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3296 Context.getSizeType(),
3297 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003298}
3299
3300/// \brief Build a sizeof or alignof expression given an expression
3301/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003302ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003303Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3304 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregorba498172009-03-13 21:01:28 +00003305 // Verify that the operand is valid.
3306 bool isInvalid = false;
3307 if (E->isTypeDependent()) {
3308 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003309 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003310 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003311 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003312 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003313 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003314 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003315 isInvalid = true;
John McCall2cd11fe2010-10-12 02:09:17 +00003316 } else if (E->getType()->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00003317 ExprResult PE = CheckPlaceholderExpr(E);
John McCall2cd11fe2010-10-12 02:09:17 +00003318 if (PE.isInvalid()) return ExprError();
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003319 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00003320 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003321 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003322 }
3323
3324 if (isInvalid)
3325 return ExprError();
3326
3327 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003328 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003329 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003330 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003331}
3332
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003333/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3334/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003335/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003336ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003337Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3338 UnaryExprOrTypeTrait ExprKind, bool isType,
3339 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003340 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003341 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003342
Sebastian Redl05189992008-11-11 17:56:53 +00003343 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00003344 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003345 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003346 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003347 }
Sebastian Redl05189992008-11-11 17:56:53 +00003348
Douglas Gregorba498172009-03-13 21:01:28 +00003349 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003350 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00003351 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003352}
3353
John Wiegley429bb272011-04-08 18:41:53 +00003354static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall09431682010-11-18 19:01:18 +00003355 bool isReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003356 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003357 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003358
John McCallf6a16482010-12-04 03:47:34 +00003359 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003360 if (V.get()->getObjectKind() != OK_Ordinary) {
3361 V = S.DefaultLvalueConversion(V.take());
3362 if (V.isInvalid())
3363 return QualType();
3364 }
John McCallf6a16482010-12-04 03:47:34 +00003365
Chris Lattnercc26ed72007-08-26 05:39:26 +00003366 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003367 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003368 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003369
Chris Lattnercc26ed72007-08-26 05:39:26 +00003370 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003371 if (V.get()->getType()->isArithmeticType())
3372 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003373
John McCall2cd11fe2010-10-12 02:09:17 +00003374 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003375 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003376 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003377 if (PR.get() != V.get()) {
3378 V = move(PR);
John McCall09431682010-11-18 19:01:18 +00003379 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003380 }
3381
Chris Lattnercc26ed72007-08-26 05:39:26 +00003382 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003383 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00003384 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003385 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003386}
3387
3388
Reid Spencer5f016e22007-07-11 17:01:13 +00003389
John McCall60d7b3a2010-08-24 06:29:42 +00003390ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003391Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003392 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003393 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003394 switch (Kind) {
3395 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003396 case tok::plusplus: Opc = UO_PostInc; break;
3397 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003398 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003399
John McCall9ae2f072010-08-23 23:25:46 +00003400 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003401}
3402
John McCall09431682010-11-18 19:01:18 +00003403/// Expressions of certain arbitrary types are forbidden by C from
3404/// having l-value type. These are:
3405/// - 'void', but not qualified void
3406/// - function types
3407///
3408/// The exact rule here is C99 6.3.2.1:
3409/// An lvalue is an expression with an object type or an incomplete
3410/// type other than void.
3411static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
3412 return ((T->isVoidType() && !T.hasQualifiers()) ||
3413 T->isFunctionType());
3414}
3415
John McCall60d7b3a2010-08-24 06:29:42 +00003416ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003417Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3418 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003419 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003420 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003421 if (Result.isInvalid()) return ExprError();
3422 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003423
John McCall9ae2f072010-08-23 23:25:46 +00003424 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003425
Douglas Gregor337c6b92008-11-19 17:17:41 +00003426 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003427 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003428 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003429 Context.DependentTy,
3430 VK_LValue, OK_Ordinary,
3431 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003432 }
3433
Mike Stump1eb44332009-09-09 15:08:12 +00003434 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003435 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003436 LHSExp->getType()->isEnumeralType() ||
3437 RHSExp->getType()->isRecordType() ||
3438 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00003439 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003440 }
3441
John McCall9ae2f072010-08-23 23:25:46 +00003442 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003443}
3444
3445
John McCall60d7b3a2010-08-24 06:29:42 +00003446ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003447Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3448 Expr *Idx, SourceLocation RLoc) {
3449 Expr *LHSExp = Base;
3450 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003451
Chris Lattner12d9ff62007-07-16 00:14:47 +00003452 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003453 if (!LHSExp->getType()->getAs<VectorType>()) {
3454 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3455 if (Result.isInvalid())
3456 return ExprError();
3457 LHSExp = Result.take();
3458 }
3459 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3460 if (Result.isInvalid())
3461 return ExprError();
3462 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003463
Chris Lattner12d9ff62007-07-16 00:14:47 +00003464 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003465 ExprValueKind VK = VK_LValue;
3466 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003467
Reid Spencer5f016e22007-07-11 17:01:13 +00003468 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003469 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003470 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003471 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003472 Expr *BaseExpr, *IndexExpr;
3473 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003474 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3475 BaseExpr = LHSExp;
3476 IndexExpr = RHSExp;
3477 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003478 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003479 BaseExpr = LHSExp;
3480 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003481 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003482 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003483 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003484 BaseExpr = RHSExp;
3485 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003486 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003487 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003488 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003489 BaseExpr = LHSExp;
3490 IndexExpr = RHSExp;
3491 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003492 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003493 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003494 // Handle the uncommon case of "123[Ptr]".
3495 BaseExpr = RHSExp;
3496 IndexExpr = LHSExp;
3497 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003498 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003499 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003500 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003501 VK = LHSExp->getValueKind();
3502 if (VK != VK_RValue)
3503 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003504
Chris Lattner12d9ff62007-07-16 00:14:47 +00003505 // FIXME: need to deal with const...
3506 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003507 } else if (LHSTy->isArrayType()) {
3508 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003509 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003510 // wasn't promoted because of the C90 rule that doesn't
3511 // allow promoting non-lvalue arrays. Warn, then
3512 // force the promotion here.
3513 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3514 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003515 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3516 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003517 LHSTy = LHSExp->getType();
3518
3519 BaseExpr = LHSExp;
3520 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003521 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003522 } else if (RHSTy->isArrayType()) {
3523 // Same as previous, except for 123[f().a] case
3524 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3525 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003526 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3527 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003528 RHSTy = RHSExp->getType();
3529
3530 BaseExpr = RHSExp;
3531 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003532 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003533 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003534 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3535 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003536 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003537 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003538 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003539 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3540 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003541
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003542 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003543 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3544 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003545 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3546
Douglas Gregore7450f52009-03-24 19:52:54 +00003547 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003548 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3549 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003550 // incomplete types are not object types.
3551 if (ResultType->isFunctionType()) {
3552 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3553 << ResultType << BaseExpr->getSourceRange();
3554 return ExprError();
3555 }
Mike Stump1eb44332009-09-09 15:08:12 +00003556
Abramo Bagnara46358452010-09-13 06:50:07 +00003557 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3558 // GNU extension: subscripting on pointer to void
3559 Diag(LLoc, diag::ext_gnu_void_ptr)
3560 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003561
3562 // C forbids expressions of unqualified void type from being l-values.
3563 // See IsCForbiddenLValueType.
3564 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003565 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003566 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003567 PDiag(diag::err_subscript_incomplete_type)
3568 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003569 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003570
Chris Lattner1efaa952009-04-24 00:30:45 +00003571 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003572 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003573 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3574 << ResultType << BaseExpr->getSourceRange();
3575 return ExprError();
3576 }
Mike Stump1eb44332009-09-09 15:08:12 +00003577
John McCall09431682010-11-18 19:01:18 +00003578 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3579 !IsCForbiddenLValueType(Context, ResultType));
3580
Mike Stumpeed9cac2009-02-19 03:04:26 +00003581 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003582 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003583}
3584
John McCall09431682010-11-18 19:01:18 +00003585/// Check an ext-vector component access expression.
3586///
3587/// VK should be set in advance to the value kind of the base
3588/// expression.
3589static QualType
3590CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3591 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003592 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00003593 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3594 // see FIXME there.
3595 //
3596 // FIXME: This logic can be greatly simplified by splitting it along
3597 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00003598 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00003599
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003600 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00003601 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003602
Mike Stumpeed9cac2009-02-19 03:04:26 +00003603 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00003604 // special names that indicate a subset of exactly half the elements are
3605 // to be selected.
3606 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003607
Nate Begeman353417a2009-01-18 01:47:54 +00003608 // This flag determines whether or not CompName has an 's' char prefix,
3609 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00003610 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00003611
John McCall09431682010-11-18 19:01:18 +00003612 bool HasRepeated = false;
3613 bool HasIndex[16] = {};
3614
3615 int Idx;
3616
Nate Begeman8a997642008-05-09 06:41:27 +00003617 // Check that we've found one of the special components, or that the component
3618 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003619 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00003620 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3621 HalvingSwizzle = true;
John McCall09431682010-11-18 19:01:18 +00003622 } else if (!HexSwizzle &&
3623 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3624 do {
3625 if (HasIndex[Idx]) HasRepeated = true;
3626 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003627 compStr++;
John McCall09431682010-11-18 19:01:18 +00003628 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3629 } else {
3630 if (HexSwizzle) compStr++;
3631 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3632 if (HasIndex[Idx]) HasRepeated = true;
3633 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003634 compStr++;
John McCall09431682010-11-18 19:01:18 +00003635 }
Chris Lattner88dca042007-08-02 22:33:49 +00003636 }
Nate Begeman353417a2009-01-18 01:47:54 +00003637
Mike Stumpeed9cac2009-02-19 03:04:26 +00003638 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003639 // We didn't get to the end of the string. This means the component names
3640 // didn't come from the same set *or* we encountered an illegal name.
John McCall09431682010-11-18 19:01:18 +00003641 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00003642 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003643 return QualType();
3644 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003645
Nate Begeman353417a2009-01-18 01:47:54 +00003646 // Ensure no component accessor exceeds the width of the vector type it
3647 // operates on.
3648 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00003649 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003650
3651 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003652 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00003653
3654 while (*compStr) {
3655 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall09431682010-11-18 19:01:18 +00003656 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begeman353417a2009-01-18 01:47:54 +00003657 << baseType << SourceRange(CompLoc);
3658 return QualType();
3659 }
3660 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003661 }
Nate Begeman8a997642008-05-09 06:41:27 +00003662
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003663 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003664 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003665 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00003666 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00003667 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00003668 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00003669 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00003670 if (HexSwizzle)
3671 CompSize--;
3672
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003673 if (CompSize == 1)
3674 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003675
John McCall09431682010-11-18 19:01:18 +00003676 if (HasRepeated) VK = VK_RValue;
3677
3678 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003679 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00003680 // diagostics look bad. We want extended vector types to appear built-in.
John McCall09431682010-11-18 19:01:18 +00003681 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3682 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3683 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00003684 }
3685 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003686}
3687
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003688static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003689 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003690 const Selector &Sel,
3691 ASTContext &Context) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003692 if (Member)
3693 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3694 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003695 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003696 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00003697
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003698 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3699 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003700 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3701 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003702 return D;
3703 }
3704 return 0;
3705}
3706
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003707static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3708 IdentifierInfo *Member,
3709 const Selector &Sel,
3710 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003711 // Check protocols on qualified interfaces.
3712 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003713 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003714 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003715 if (Member)
3716 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3717 GDecl = PD;
3718 break;
3719 }
3720 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003721 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003722 GDecl = OMD;
3723 break;
3724 }
3725 }
3726 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003727 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003728 E = QIdTy->qual_end(); I != E; ++I) {
3729 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003730 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3731 Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003732 if (GDecl)
3733 return GDecl;
3734 }
3735 }
3736 return GDecl;
3737}
Chris Lattner76a642f2009-02-15 22:43:40 +00003738
John McCall60d7b3a2010-08-24 06:29:42 +00003739ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003740Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCallaa81e162009-12-01 22:10:20 +00003741 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003742 const CXXScopeSpec &SS,
3743 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003744 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003745 const TemplateArgumentListInfo *TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00003746 // Even in dependent contexts, try to diagnose base expressions with
3747 // obviously wrong types, e.g.:
3748 //
3749 // T* t;
3750 // t.f;
3751 //
3752 // In Obj-C++, however, the above expression is valid, since it could be
3753 // accessing the 'f' property if T is an Obj-C interface. The extra check
3754 // allows this, while still reporting an error if T is a struct pointer.
3755 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00003756 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00003757 if (PT && (!getLangOptions().ObjC1 ||
3758 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00003759 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnara25777432010-08-11 22:01:17 +00003760 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00003761 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00003762 return ExprError();
3763 }
3764 }
3765
Abramo Bagnara25777432010-08-11 22:01:17 +00003766 assert(BaseType->isDependentType() ||
3767 NameInfo.getName().isDependentName() ||
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003768 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00003769
3770 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3771 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00003772 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003773 IsArrow, OpLoc,
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003774 SS.getWithLocInContext(Context),
John McCall129e2df2009-11-30 22:42:35 +00003775 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003776 NameInfo, TemplateArgs));
John McCall129e2df2009-11-30 22:42:35 +00003777}
3778
3779/// We know that the given qualified member reference points only to
3780/// declarations which do not belong to the static type of the base
3781/// expression. Diagnose the problem.
3782static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3783 Expr *BaseExpr,
3784 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003785 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00003786 NamedDecl *rep,
3787 const DeclarationNameInfo &nameInfo) {
John McCall2f841ba2009-12-02 03:53:29 +00003788 // If this is an implicit member access, use a different set of
3789 // diagnostics.
3790 if (!BaseExpr)
John McCall5808ce42011-02-03 08:15:49 +00003791 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003792
John McCall5808ce42011-02-03 08:15:49 +00003793 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3794 << SS.getRange() << rep << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00003795}
3796
3797// Check whether the declarations we found through a nested-name
3798// specifier in a member expression are actually members of the base
3799// type. The restriction here is:
3800//
3801// C++ [expr.ref]p2:
3802// ... In these cases, the id-expression shall name a
3803// member of the class or of one of its base classes.
3804//
3805// So it's perfectly legitimate for the nested-name specifier to name
3806// an unrelated class, and for us to find an overload set including
3807// decls from classes which are not superclasses, as long as the decl
3808// we actually pick through overload resolution is from a superclass.
3809bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3810 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003811 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003812 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00003813 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3814 if (!BaseRT) {
3815 // We can't check this yet because the base type is still
3816 // dependent.
3817 assert(BaseType->isDependentType());
3818 return false;
3819 }
3820 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00003821
3822 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00003823 // If this is an implicit member reference and we find a
3824 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00003825 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00003826 return false;
John McCall129e2df2009-11-30 22:42:35 +00003827
John McCallaa81e162009-12-01 22:10:20 +00003828 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman02463762010-07-27 20:51:02 +00003829 DeclContext *DC = (*I)->getDeclContext();
3830 while (DC->isTransparentContext())
3831 DC = DC->getParent();
John McCallaa81e162009-12-01 22:10:20 +00003832
Douglas Gregor9d4bb942010-07-28 22:27:52 +00003833 if (!DC->isRecord())
3834 continue;
3835
John McCallaa81e162009-12-01 22:10:20 +00003836 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman02463762010-07-27 20:51:02 +00003837 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCallaa81e162009-12-01 22:10:20 +00003838
3839 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3840 return false;
3841 }
3842
John McCall5808ce42011-02-03 08:15:49 +00003843 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3844 R.getRepresentativeDecl(),
3845 R.getLookupNameInfo());
John McCallaa81e162009-12-01 22:10:20 +00003846 return true;
3847}
3848
3849static bool
3850LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3851 SourceRange BaseRange, const RecordType *RTy,
John McCallad00b772010-06-16 08:42:20 +00003852 SourceLocation OpLoc, CXXScopeSpec &SS,
3853 bool HasTemplateArgs) {
John McCallaa81e162009-12-01 22:10:20 +00003854 RecordDecl *RDecl = RTy->getDecl();
3855 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003856 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00003857 << BaseRange))
3858 return true;
3859
John McCallad00b772010-06-16 08:42:20 +00003860 if (HasTemplateArgs) {
3861 // LookupTemplateName doesn't expect these both to exist simultaneously.
3862 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3863
3864 bool MOUS;
3865 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3866 return false;
3867 }
3868
John McCallaa81e162009-12-01 22:10:20 +00003869 DeclContext *DC = RDecl;
3870 if (SS.isSet()) {
3871 // If the member name was a qualified-id, look into the
3872 // nested-name-specifier.
3873 DC = SemaRef.computeDeclContext(SS, false);
3874
John McCall77bb1aa2010-05-01 00:40:08 +00003875 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCall2f841ba2009-12-02 03:53:29 +00003876 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3877 << SS.getRange() << DC;
3878 return true;
3879 }
3880
John McCallaa81e162009-12-01 22:10:20 +00003881 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003882
John McCallaa81e162009-12-01 22:10:20 +00003883 if (!isa<TypeDecl>(DC)) {
3884 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3885 << DC << SS.getRange();
3886 return true;
John McCall129e2df2009-11-30 22:42:35 +00003887 }
3888 }
3889
John McCallaa81e162009-12-01 22:10:20 +00003890 // The record definition is complete, now look up the member.
3891 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00003892
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003893 if (!R.empty())
3894 return false;
3895
3896 // We didn't find anything with the given name, so try to correct
3897 // for typos.
3898 DeclarationName Name = R.getLookupName();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003899 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00003900 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003901 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3902 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3903 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003904 << FixItHint::CreateReplacement(R.getNameLoc(),
3905 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003906 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3907 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3908 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003909 return false;
3910 } else {
3911 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003912 R.setLookupName(Name);
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003913 }
3914
John McCall129e2df2009-11-30 22:42:35 +00003915 return false;
3916}
3917
John McCall60d7b3a2010-08-24 06:29:42 +00003918ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003919Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003920 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003921 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003922 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003923 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003924 const TemplateArgumentListInfo *TemplateArgs) {
John McCall2f841ba2009-12-02 03:53:29 +00003925 if (BaseType->isDependentType() ||
3926 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall9ae2f072010-08-23 23:25:46 +00003927 return ActOnDependentMemberExpr(Base, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003928 IsArrow, OpLoc,
3929 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003930 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003931
Abramo Bagnara25777432010-08-11 22:01:17 +00003932 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00003933
John McCallaa81e162009-12-01 22:10:20 +00003934 // Implicit member accesses.
3935 if (!Base) {
3936 QualType RecordTy = BaseType;
3937 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3938 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3939 RecordTy->getAs<RecordType>(),
John McCallad00b772010-06-16 08:42:20 +00003940 OpLoc, SS, TemplateArgs != 0))
John McCallaa81e162009-12-01 22:10:20 +00003941 return ExprError();
3942
3943 // Explicit member accesses.
3944 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003945 ExprResult BaseResult = Owned(Base);
John McCall60d7b3a2010-08-24 06:29:42 +00003946 ExprResult Result =
John Wiegley429bb272011-04-08 18:41:53 +00003947 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCalld226f652010-08-21 09:40:31 +00003948 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCallaa81e162009-12-01 22:10:20 +00003949
John Wiegley429bb272011-04-08 18:41:53 +00003950 if (BaseResult.isInvalid())
3951 return ExprError();
3952 Base = BaseResult.take();
3953
John McCallaa81e162009-12-01 22:10:20 +00003954 if (Result.isInvalid()) {
3955 Owned(Base);
3956 return ExprError();
3957 }
3958
3959 if (Result.get())
3960 return move(Result);
Sebastian Redlf3e63372010-05-07 09:25:11 +00003961
3962 // LookupMemberExpr can modify Base, and thus change BaseType
3963 BaseType = Base->getType();
John McCall129e2df2009-11-30 22:42:35 +00003964 }
3965
John McCall9ae2f072010-08-23 23:25:46 +00003966 return BuildMemberReferenceExpr(Base, BaseType,
John McCallc2233c52010-01-15 08:34:02 +00003967 OpLoc, IsArrow, SS, FirstQualifierInScope,
3968 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003969}
3970
John McCall60d7b3a2010-08-24 06:29:42 +00003971ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003972Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCallaa81e162009-12-01 22:10:20 +00003973 SourceLocation OpLoc, bool IsArrow,
3974 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00003975 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00003976 LookupResult &R,
Douglas Gregor06a9f362010-05-01 20:49:11 +00003977 const TemplateArgumentListInfo *TemplateArgs,
3978 bool SuppressQualifierCheck) {
John McCallaa81e162009-12-01 22:10:20 +00003979 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00003980 if (IsArrow) {
3981 assert(BaseType->isPointerType());
3982 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3983 }
John McCall161755a2010-04-06 21:38:20 +00003984 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00003985
Abramo Bagnara25777432010-08-11 22:01:17 +00003986 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3987 DeclarationName MemberName = MemberNameInfo.getName();
3988 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall129e2df2009-11-30 22:42:35 +00003989
3990 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00003991 return ExprError();
3992
John McCall129e2df2009-11-30 22:42:35 +00003993 if (R.empty()) {
3994 // Rederive where we looked up.
3995 DeclContext *DC = (SS.isSet()
3996 ? computeDeclContext(SS, false)
3997 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00003998
John McCall129e2df2009-11-30 22:42:35 +00003999 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00004000 << MemberName << DC
4001 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00004002 return ExprError();
4003 }
4004
John McCallc2233c52010-01-15 08:34:02 +00004005 // Diagnose lookups that find only declarations from a non-base
4006 // type. This is possible for either qualified lookups (which may
4007 // have been qualified with an unrelated type) or implicit member
4008 // expressions (which were found with unqualified lookup and thus
4009 // may have come from an enclosing scope). Note that it's okay for
4010 // lookup to find declarations from a non-base type as long as those
4011 // aren't the ones picked by overload resolution.
4012 if ((SS.isSet() || !BaseExpr ||
4013 (isa<CXXThisExpr>(BaseExpr) &&
4014 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00004015 !SuppressQualifierCheck &&
John McCallc2233c52010-01-15 08:34:02 +00004016 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00004017 return ExprError();
4018
4019 // Construct an unresolved result if we in fact got an unresolved
4020 // result.
4021 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallc373d482010-01-27 01:50:18 +00004022 // Suppress any lookup-related diagnostics; we'll do these when we
4023 // pick a member.
4024 R.suppressDiagnostics();
4025
John McCall129e2df2009-11-30 22:42:35 +00004026 UnresolvedMemberExpr *MemExpr
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00004027 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00004028 BaseExpr, BaseExprType,
4029 IsArrow, OpLoc,
Douglas Gregor4c9be892011-02-28 20:01:57 +00004030 SS.getWithLocInContext(Context),
Abramo Bagnara25777432010-08-11 22:01:17 +00004031 MemberNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00004032 TemplateArgs, R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00004033
4034 return Owned(MemExpr);
4035 }
4036
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004037 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00004038 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00004039 NamedDecl *MemberDecl = R.getFoundDecl();
4040
4041 // FIXME: diagnose the presence of template arguments now.
4042
4043 // If the decl being referenced had an error, return an error for this
4044 // sub-expr without emitting another error, in order to avoid cascading
4045 // error cases.
4046 if (MemberDecl->isInvalidDecl())
4047 return ExprError();
4048
John McCallaa81e162009-12-01 22:10:20 +00004049 // Handle the implicit-member-access case.
4050 if (!BaseExpr) {
4051 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00004052 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnara25777432010-08-11 22:01:17 +00004053 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCallaa81e162009-12-01 22:10:20 +00004054
Douglas Gregor828a1972010-01-07 23:12:05 +00004055 SourceLocation Loc = R.getNameLoc();
4056 if (SS.getRange().isValid())
4057 Loc = SS.getRange().getBegin();
4058 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00004059 }
4060
John McCall129e2df2009-11-30 22:42:35 +00004061 bool ShouldCheckUse = true;
4062 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
4063 // Don't diagnose the use of a virtual member function unless it's
4064 // explicitly qualified.
4065 if (MD->isVirtual() && !SS.isSet())
4066 ShouldCheckUse = false;
4067 }
4068
4069 // Check the use of this member.
4070 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
4071 Owned(BaseExpr);
4072 return ExprError();
4073 }
4074
John McCallf6a16482010-12-04 03:47:34 +00004075 // Perform a property load on the base regardless of whether we
4076 // actually need it for the declaration.
John Wiegley429bb272011-04-08 18:41:53 +00004077 if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
4078 ExprResult Result = ConvertPropertyForRValue(BaseExpr);
4079 if (Result.isInvalid())
4080 return ExprError();
4081 BaseExpr = Result.take();
4082 }
John McCallf6a16482010-12-04 03:47:34 +00004083
John McCalldfa1edb2010-11-23 20:48:44 +00004084 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
4085 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
4086 SS, FD, FoundDecl, MemberNameInfo);
John McCall129e2df2009-11-30 22:42:35 +00004087
Francois Pichet87c2e122010-11-21 06:08:52 +00004088 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
4089 // We may have found a field within an anonymous union or struct
4090 // (C++ [class.union]).
John McCall5808ce42011-02-03 08:15:49 +00004091 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCallf6a16482010-12-04 03:47:34 +00004092 BaseExpr, OpLoc);
Francois Pichet87c2e122010-11-21 06:08:52 +00004093
John McCall129e2df2009-11-30 22:42:35 +00004094 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
4095 MarkDeclarationReferenced(MemberLoc, Var);
4096 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00004097 Var, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00004098 Var->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00004099 VK_LValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00004100 }
4101
John McCallf89e55a2010-11-18 06:31:45 +00004102 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall864c0412011-04-26 20:42:42 +00004103 ExprValueKind valueKind;
4104 QualType type;
4105 if (MemberFn->isInstance()) {
4106 valueKind = VK_RValue;
4107 type = Context.BoundMemberTy;
4108 } else {
4109 valueKind = VK_LValue;
4110 type = MemberFn->getType();
4111 }
4112
John McCall129e2df2009-11-30 22:42:35 +00004113 MarkDeclarationReferenced(MemberLoc, MemberDecl);
4114 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00004115 MemberFn, FoundDecl, MemberNameInfo,
John McCall864c0412011-04-26 20:42:42 +00004116 type, valueKind, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00004117 }
John McCallf89e55a2010-11-18 06:31:45 +00004118 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall129e2df2009-11-30 22:42:35 +00004119
4120 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
4121 MarkDeclarationReferenced(MemberLoc, MemberDecl);
4122 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00004123 Enum, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00004124 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00004125 }
4126
4127 Owned(BaseExpr);
4128
Douglas Gregorb0fd4832010-04-25 20:55:08 +00004129 // We found something that we didn't expect. Complain.
John McCall129e2df2009-11-30 22:42:35 +00004130 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnara25777432010-08-11 22:01:17 +00004131 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregorb0fd4832010-04-25 20:55:08 +00004132 << MemberName << BaseType << int(IsArrow);
4133 else
4134 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
4135 << MemberName << BaseType << int(IsArrow);
John McCall129e2df2009-11-30 22:42:35 +00004136
Douglas Gregorb0fd4832010-04-25 20:55:08 +00004137 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
4138 << MemberName;
Douglas Gregor2b147f02010-04-25 21:15:30 +00004139 R.suppressDiagnostics();
Douglas Gregorb0fd4832010-04-25 20:55:08 +00004140 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00004141}
4142
John McCall028d3972010-12-15 16:46:44 +00004143/// Given that normal member access failed on the given expression,
4144/// and given that the expression's type involves builtin-id or
4145/// builtin-Class, decide whether substituting in the redefinition
4146/// types would be profitable. The redefinition type is whatever
4147/// this translation unit tried to typedef to id/Class; we store
4148/// it to the side and then re-use it in places like this.
John Wiegley429bb272011-04-08 18:41:53 +00004149static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
John McCall028d3972010-12-15 16:46:44 +00004150 const ObjCObjectPointerType *opty
John Wiegley429bb272011-04-08 18:41:53 +00004151 = base.get()->getType()->getAs<ObjCObjectPointerType>();
John McCall028d3972010-12-15 16:46:44 +00004152 if (!opty) return false;
4153
4154 const ObjCObjectType *ty = opty->getObjectType();
4155
4156 QualType redef;
4157 if (ty->isObjCId()) {
4158 redef = S.Context.ObjCIdRedefinitionType;
4159 } else if (ty->isObjCClass()) {
4160 redef = S.Context.ObjCClassRedefinitionType;
4161 } else {
4162 return false;
4163 }
4164
4165 // Do the substitution as long as the redefinition type isn't just a
4166 // possibly-qualified pointer to builtin-id or builtin-Class again.
4167 opty = redef->getAs<ObjCObjectPointerType>();
4168 if (opty && !opty->getObjectType()->getInterface() != 0)
4169 return false;
4170
John Wiegley429bb272011-04-08 18:41:53 +00004171 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
John McCall028d3972010-12-15 16:46:44 +00004172 return true;
4173}
4174
John McCall129e2df2009-11-30 22:42:35 +00004175/// Look up the given member of the given non-type-dependent
4176/// expression. This can return in one of two ways:
4177/// * If it returns a sentinel null-but-valid result, the caller will
4178/// assume that lookup was performed and the results written into
4179/// the provided structure. It will take over from there.
4180/// * Otherwise, the returned expression will be produced in place of
4181/// an ordinary member expression.
4182///
4183/// The ObjCImpDecl bit is a gross hack that will need to be properly
4184/// fixed for ObjC++.
John McCall60d7b3a2010-08-24 06:29:42 +00004185ExprResult
John Wiegley429bb272011-04-08 18:41:53 +00004186Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00004187 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004188 CXXScopeSpec &SS,
John McCalld226f652010-08-21 09:40:31 +00004189 Decl *ObjCImpDecl, bool HasTemplateArgs) {
John Wiegley429bb272011-04-08 18:41:53 +00004190 assert(BaseExpr.get() && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00004191
Steve Naroff3cc4af82007-12-16 21:42:28 +00004192 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00004193 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Sebastian Redl0eb23302009-01-19 00:08:26 +00004194
John Wiegley429bb272011-04-08 18:41:53 +00004195 if (IsArrow) {
4196 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4197 if (BaseExpr.isInvalid())
4198 return ExprError();
4199 }
4200
4201 QualType BaseType = BaseExpr.get()->getType();
John McCall129e2df2009-11-30 22:42:35 +00004202 assert(!BaseType->isDependentType());
4203
4204 DeclarationName MemberName = R.getLookupName();
4205 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00004206
John McCall028d3972010-12-15 16:46:44 +00004207 // For later type-checking purposes, turn arrow accesses into dot
4208 // accesses. The only access type we support that doesn't follow
4209 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
4210 // and those never use arrows, so this is unaffected.
4211 if (IsArrow) {
4212 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4213 BaseType = Ptr->getPointeeType();
4214 else if (const ObjCObjectPointerType *Ptr
4215 = BaseType->getAs<ObjCObjectPointerType>())
4216 BaseType = Ptr->getPointeeType();
4217 else if (BaseType->isRecordType()) {
4218 // Recover from arrow accesses to records, e.g.:
4219 // struct MyRecord foo;
4220 // foo->bar
4221 // This is actually well-formed in C++ if MyRecord has an
4222 // overloaded operator->, but that should have been dealt with
4223 // by now.
4224 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley429bb272011-04-08 18:41:53 +00004225 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
John McCall028d3972010-12-15 16:46:44 +00004226 << FixItHint::CreateReplacement(OpLoc, ".");
4227 IsArrow = false;
John McCall864c0412011-04-26 20:42:42 +00004228 } else if (BaseType == Context.BoundMemberTy) {
4229 goto fail;
John McCall028d3972010-12-15 16:46:44 +00004230 } else {
4231 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
John Wiegley429bb272011-04-08 18:41:53 +00004232 << BaseType << BaseExpr.get()->getSourceRange();
John McCall028d3972010-12-15 16:46:44 +00004233 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00004234 }
4235 }
4236
John McCall028d3972010-12-15 16:46:44 +00004237 // Handle field access to simple records.
4238 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John Wiegley429bb272011-04-08 18:41:53 +00004239 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
John McCall028d3972010-12-15 16:46:44 +00004240 RTy, OpLoc, SS, HasTemplateArgs))
4241 return ExprError();
4242
4243 // Returning valid-but-null is how we indicate to the caller that
4244 // the lookup result was filled in.
4245 return Owned((Expr*) 0);
David Chisnall0f436562009-08-17 16:35:33 +00004246 }
John McCall129e2df2009-11-30 22:42:35 +00004247
John McCall028d3972010-12-15 16:46:44 +00004248 // Handle ivar access to Objective-C objects.
4249 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004250 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall028d3972010-12-15 16:46:44 +00004251
4252 // There are three cases for the base type:
4253 // - builtin id (qualified or unqualified)
4254 // - builtin Class (qualified or unqualified)
4255 // - an interface
4256 ObjCInterfaceDecl *IDecl = OTy->getInterface();
4257 if (!IDecl) {
John McCallf85e1932011-06-15 23:02:42 +00004258 if (getLangOptions().ObjCAutoRefCount &&
4259 (OTy->isObjCId() || OTy->isObjCClass()))
4260 goto fail;
John McCall028d3972010-12-15 16:46:44 +00004261 // There's an implicit 'isa' ivar on all objects.
4262 // But we only actually find it this way on objects of type 'id',
4263 // apparently.
4264 if (OTy->isObjCId() && Member->isStr("isa"))
John Wiegley429bb272011-04-08 18:41:53 +00004265 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
John McCall028d3972010-12-15 16:46:44 +00004266 Context.getObjCClassType()));
4267
4268 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4269 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4270 ObjCImpDecl, HasTemplateArgs);
4271 goto fail;
4272 }
4273
4274 ObjCInterfaceDecl *ClassDeclared;
4275 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
4276
4277 if (!IV) {
4278 // Attempt to correct for typos in ivar names.
4279 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
4280 LookupMemberName);
4281 if (CorrectTypo(Res, 0, 0, IDecl, false,
4282 IsArrow ? CTC_ObjCIvarLookup
4283 : CTC_ObjCPropertyLookup) &&
4284 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
4285 Diag(R.getNameLoc(),
4286 diag::err_typecheck_member_reference_ivar_suggest)
4287 << IDecl->getDeclName() << MemberName << IV->getDeclName()
4288 << FixItHint::CreateReplacement(R.getNameLoc(),
4289 IV->getNameAsString());
4290 Diag(IV->getLocation(), diag::note_previous_decl)
4291 << IV->getDeclName();
4292 } else {
4293 Res.clear();
4294 Res.setLookupName(Member);
4295
4296 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
4297 << IDecl->getDeclName() << MemberName
John Wiegley429bb272011-04-08 18:41:53 +00004298 << BaseExpr.get()->getSourceRange();
John McCall028d3972010-12-15 16:46:44 +00004299 return ExprError();
4300 }
4301 }
4302
4303 // If the decl being referenced had an error, return an error for this
4304 // sub-expr without emitting another error, in order to avoid cascading
4305 // error cases.
4306 if (IV->isInvalidDecl())
4307 return ExprError();
4308
4309 // Check whether we can reference this field.
4310 if (DiagnoseUseOfDecl(IV, MemberLoc))
4311 return ExprError();
4312 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
4313 IV->getAccessControl() != ObjCIvarDecl::Package) {
4314 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
4315 if (ObjCMethodDecl *MD = getCurMethodDecl())
4316 ClassOfMethodDecl = MD->getClassInterface();
4317 else if (ObjCImpDecl && getCurFunctionDecl()) {
4318 // Case of a c-function declared inside an objc implementation.
4319 // FIXME: For a c-style function nested inside an objc implementation
4320 // class, there is no implementation context available, so we pass
4321 // down the context as argument to this routine. Ideally, this context
4322 // need be passed down in the AST node and somehow calculated from the
4323 // AST for a function decl.
4324 if (ObjCImplementationDecl *IMPD =
4325 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
4326 ClassOfMethodDecl = IMPD->getClassInterface();
4327 else if (ObjCCategoryImplDecl* CatImplClass =
4328 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
4329 ClassOfMethodDecl = CatImplClass->getClassInterface();
4330 }
4331
4332 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
4333 if (ClassDeclared != IDecl ||
4334 ClassOfMethodDecl != ClassDeclared)
4335 Diag(MemberLoc, diag::error_private_ivar_access)
4336 << IV->getDeclName();
4337 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
4338 // @protected
4339 Diag(MemberLoc, diag::error_protected_ivar_access)
4340 << IV->getDeclName();
4341 }
Fariborz Jahanianb1f7d242011-06-16 17:29:56 +00004342 if (getLangOptions().ObjCAutoRefCount) {
4343 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
4344 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
4345 if (UO->getOpcode() == UO_Deref)
4346 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
4347
4348 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
4349 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4350 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
4351 }
John McCall028d3972010-12-15 16:46:44 +00004352
4353 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
John Wiegley429bb272011-04-08 18:41:53 +00004354 MemberLoc, BaseExpr.take(),
John McCall028d3972010-12-15 16:46:44 +00004355 IsArrow));
4356 }
4357
4358 // Objective-C property access.
4359 const ObjCObjectPointerType *OPT;
4360 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
4361 // This actually uses the base as an r-value.
John Wiegley429bb272011-04-08 18:41:53 +00004362 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4363 if (BaseExpr.isInvalid())
4364 return ExprError();
4365
4366 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
John McCall028d3972010-12-15 16:46:44 +00004367
4368 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4369
4370 const ObjCObjectType *OT = OPT->getObjectType();
4371
4372 // id, with and without qualifiers.
4373 if (OT->isObjCId()) {
4374 // Check protocols on qualified interfaces.
4375 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
4376 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
4377 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
4378 // Check the use of this declaration
4379 if (DiagnoseUseOfDecl(PD, MemberLoc))
4380 return ExprError();
4381
Douglas Gregor926df6c2011-06-11 01:09:30 +00004382 QualType T = PD->getType();
4383 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
4384 T = getMessageSendResultType(BaseType, Getter, false, false);
4385
4386 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCall028d3972010-12-15 16:46:44 +00004387 VK_LValue,
4388 OK_ObjCProperty,
4389 MemberLoc,
John Wiegley429bb272011-04-08 18:41:53 +00004390 BaseExpr.take()));
John McCall028d3972010-12-15 16:46:44 +00004391 }
4392
4393 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
4394 // Check the use of this method.
4395 if (DiagnoseUseOfDecl(OMD, MemberLoc))
4396 return ExprError();
4397 Selector SetterSel =
4398 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4399 PP.getSelectorTable(), Member);
4400 ObjCMethodDecl *SMD = 0;
4401 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
4402 SetterSel, Context))
4403 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor926df6c2011-06-11 01:09:30 +00004404 QualType PType = getMessageSendResultType(BaseType, OMD, false,
4405 false);
John McCall028d3972010-12-15 16:46:44 +00004406
4407 ExprValueKind VK = VK_LValue;
4408 if (!getLangOptions().CPlusPlus &&
4409 IsCForbiddenLValueType(Context, PType))
4410 VK = VK_RValue;
4411 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4412
4413 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
4414 VK, OK,
John Wiegley429bb272011-04-08 18:41:53 +00004415 MemberLoc, BaseExpr.take()));
John McCall028d3972010-12-15 16:46:44 +00004416 }
4417 }
Fariborz Jahanian4eb7f692011-03-15 17:27:48 +00004418 // Use of id.member can only be for a property reference. Do not
4419 // use the 'id' redefinition in this case.
4420 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall028d3972010-12-15 16:46:44 +00004421 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4422 ObjCImpDecl, HasTemplateArgs);
4423
4424 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4425 << MemberName << BaseType);
4426 }
4427
4428 // 'Class', unqualified only.
4429 if (OT->isObjCClass()) {
4430 // Only works in a method declaration (??!).
4431 ObjCMethodDecl *MD = getCurMethodDecl();
4432 if (!MD) {
4433 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4434 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4435 ObjCImpDecl, HasTemplateArgs);
4436
4437 goto fail;
4438 }
4439
4440 // Also must look for a getter name which uses property syntax.
4441 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004442 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4443 ObjCMethodDecl *Getter;
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004444 if ((Getter = IFace->lookupClassMethod(Sel))) {
4445 // Check the use of this method.
4446 if (DiagnoseUseOfDecl(Getter, MemberLoc))
4447 return ExprError();
John McCall028d3972010-12-15 16:46:44 +00004448 } else
Fariborz Jahanian74b27562010-12-03 23:37:08 +00004449 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004450 // If we found a getter then this may be a valid dot-reference, we
4451 // will look for the matching setter, in case it is needed.
4452 Selector SetterSel =
John McCall028d3972010-12-15 16:46:44 +00004453 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4454 PP.getSelectorTable(), Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004455 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
4456 if (!Setter) {
4457 // If this reference is in an @implementation, also check for 'private'
4458 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00004459 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004460 }
4461 // Look through local category implementations associated with the class.
4462 if (!Setter)
4463 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004464
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004465 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
4466 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004467
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004468 if (Getter || Setter) {
4469 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004470
John McCall09431682010-11-18 19:01:18 +00004471 ExprValueKind VK = VK_LValue;
4472 if (Getter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00004473 PType = getMessageSendResultType(QualType(OT, 0), Getter, true,
4474 false);
John McCall09431682010-11-18 19:01:18 +00004475 if (!getLangOptions().CPlusPlus &&
4476 IsCForbiddenLValueType(Context, PType))
4477 VK = VK_RValue;
4478 } else {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004479 // Get the expression type from Setter's incoming parameter.
4480 PType = (*(Setter->param_end() -1))->getType();
John McCall09431682010-11-18 19:01:18 +00004481 }
4482 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4483
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004484 // FIXME: we must check that the setter has property type.
John McCall12f78a62010-12-02 01:19:52 +00004485 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4486 PType, VK, OK,
John Wiegley429bb272011-04-08 18:41:53 +00004487 MemberLoc, BaseExpr.take()));
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004488 }
John McCall028d3972010-12-15 16:46:44 +00004489
4490 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4491 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4492 ObjCImpDecl, HasTemplateArgs);
4493
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004494 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall028d3972010-12-15 16:46:44 +00004495 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00004496 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004497
John McCall028d3972010-12-15 16:46:44 +00004498 // Normal property access.
John Wiegley429bb272011-04-08 18:41:53 +00004499 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
John McCall028d3972010-12-15 16:46:44 +00004500 SourceLocation(), QualType(), false);
Steve Naroff14108da2009-07-10 23:34:53 +00004501 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004502
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004503 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00004504 if (BaseType->isExtVectorType()) {
John McCall5e3c67b2010-12-15 04:42:30 +00004505 // FIXME: this expr should store IsArrow.
Anders Carlsson8f28f992009-08-26 18:25:21 +00004506 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John Wiegley429bb272011-04-08 18:41:53 +00004507 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
John McCall09431682010-11-18 19:01:18 +00004508 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4509 Member, MemberLoc);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004510 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004511 return ExprError();
John McCall09431682010-11-18 19:01:18 +00004512
John Wiegley429bb272011-04-08 18:41:53 +00004513 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
John McCall09431682010-11-18 19:01:18 +00004514 *Member, MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004515 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004516
John McCall028d3972010-12-15 16:46:44 +00004517 // Adjust builtin-sel to the appropriate redefinition type if that's
4518 // not just a pointer to builtin-sel again.
4519 if (IsArrow &&
4520 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4521 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004522 BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
4523 CK_BitCast);
John McCall028d3972010-12-15 16:46:44 +00004524 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4525 ObjCImpDecl, HasTemplateArgs);
4526 }
4527
4528 // Failure cases.
4529 fail:
4530
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004531 // Recover from dot accesses to pointers, e.g.:
4532 // type *foo;
4533 // foo.bar
4534 // This is actually well-formed in two cases:
4535 // - 'type' is an Objective C type
4536 // - 'bar' is a pseudo-destructor name which happens to refer to
4537 // the appropriate pointer type
John McCall028d3972010-12-15 16:46:44 +00004538 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004539 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4540 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall028d3972010-12-15 16:46:44 +00004541 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley429bb272011-04-08 18:41:53 +00004542 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004543 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall028d3972010-12-15 16:46:44 +00004544
4545 // Recurse as an -> access.
4546 IsArrow = true;
4547 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4548 ObjCImpDecl, HasTemplateArgs);
4549 }
John McCall028d3972010-12-15 16:46:44 +00004550 }
4551
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004552 // If the user is trying to apply -> or . to a function name, it's probably
4553 // because they forgot parentheses to call that function.
Matt Beaumont-Gayc9366ba2011-05-04 22:10:40 +00004554 QualType ZeroArgCallTy;
4555 UnresolvedSet<4> Overloads;
4556 if (isExprCallable(*BaseExpr.get(), ZeroArgCallTy, Overloads)) {
4557 if (ZeroArgCallTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +00004558 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gayc9366ba2011-05-04 22:10:40 +00004559 << (Overloads.size() > 1) << 0 << BaseExpr.get()->getSourceRange();
4560 UnresolvedSet<2> PlausibleOverloads;
4561 for (OverloadExpr::decls_iterator It = Overloads.begin(),
4562 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
4563 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
4564 QualType OverloadResultTy = OverloadDecl->getResultType();
4565 if ((!IsArrow && OverloadResultTy->isRecordType()) ||
4566 (IsArrow && OverloadResultTy->isPointerType() &&
4567 OverloadResultTy->getPointeeType()->isRecordType()))
4568 PlausibleOverloads.addDecl(It.getDecl());
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004569 }
Matt Beaumont-Gayc9366ba2011-05-04 22:10:40 +00004570 NoteOverloads(PlausibleOverloads, BaseExpr.get()->getExprLoc());
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004571 return ExprError();
4572 }
Matt Beaumont-Gayc9366ba2011-05-04 22:10:40 +00004573 if ((!IsArrow && ZeroArgCallTy->isRecordType()) ||
4574 (IsArrow && ZeroArgCallTy->isPointerType() &&
4575 ZeroArgCallTy->getPointeeType()->isRecordType())) {
4576 // At this point, we know BaseExpr looks like it's potentially callable
4577 // with 0 arguments, and that it returns something of a reasonable type,
4578 // so we can emit a fixit and carry on pretending that BaseExpr was
4579 // actually a CallExpr.
4580 SourceLocation ParenInsertionLoc =
4581 PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
4582 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
4583 << (Overloads.size() > 1) << 1 << BaseExpr.get()->getSourceRange()
4584 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4585 // FIXME: Try this before emitting the fixit, and suppress diagnostics
4586 // while doing so.
4587 ExprResult NewBase =
4588 ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
4589 MultiExprArg(*this, 0, 0),
4590 ParenInsertionLoc.getFileLocWithOffset(1));
4591 if (NewBase.isInvalid())
4592 return ExprError();
4593 BaseExpr = NewBase;
4594 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
4595 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4596 ObjCImpDecl, HasTemplateArgs);
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004597 }
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004598 }
4599
Douglas Gregor214f31a2009-03-27 06:00:30 +00004600 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
John Wiegley429bb272011-04-08 18:41:53 +00004601 << BaseType << BaseExpr.get()->getSourceRange();
Douglas Gregor214f31a2009-03-27 06:00:30 +00004602
Douglas Gregor214f31a2009-03-27 06:00:30 +00004603 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00004604}
4605
John McCall129e2df2009-11-30 22:42:35 +00004606/// The main callback when the parser finds something like
4607/// expression . [nested-name-specifier] identifier
4608/// expression -> [nested-name-specifier] identifier
4609/// where 'identifier' encompasses a fairly broad spectrum of
4610/// possibilities, including destructor and operator references.
4611///
4612/// \param OpKind either tok::arrow or tok::period
4613/// \param HasTrailingLParen whether the next token is '(', which
4614/// is used to diagnose mis-uses of special members that can
4615/// only be called
4616/// \param ObjCImpDecl the current ObjC @implementation decl;
4617/// this is an ugly hack around the fact that ObjC @implementations
4618/// aren't properly put in the context chain
John McCall60d7b3a2010-08-24 06:29:42 +00004619ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall5e3c67b2010-12-15 04:42:30 +00004620 SourceLocation OpLoc,
4621 tok::TokenKind OpKind,
4622 CXXScopeSpec &SS,
4623 UnqualifiedId &Id,
4624 Decl *ObjCImpDecl,
4625 bool HasTrailingLParen) {
John McCall129e2df2009-11-30 22:42:35 +00004626 if (SS.isSet() && SS.isInvalid())
4627 return ExprError();
4628
Francois Pichetdbee3412011-01-18 05:04:39 +00004629 // Warn about the explicit constructor calls Microsoft extension.
4630 if (getLangOptions().Microsoft &&
4631 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4632 Diag(Id.getSourceRange().getBegin(),
4633 diag::ext_ms_explicit_constructor_call);
4634
John McCall129e2df2009-11-30 22:42:35 +00004635 TemplateArgumentListInfo TemplateArgsBuffer;
4636
4637 // Decompose the name into its component parts.
Abramo Bagnara25777432010-08-11 22:01:17 +00004638 DeclarationNameInfo NameInfo;
John McCall129e2df2009-11-30 22:42:35 +00004639 const TemplateArgumentListInfo *TemplateArgs;
4640 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00004641 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004642
Abramo Bagnara25777432010-08-11 22:01:17 +00004643 DeclarationName Name = NameInfo.getName();
John McCall129e2df2009-11-30 22:42:35 +00004644 bool IsArrow = (OpKind == tok::arrow);
4645
4646 NamedDecl *FirstQualifierInScope
4647 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4648 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4649
4650 // This is a postfix expression, so get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004651 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004652 if (Result.isInvalid()) return ExprError();
4653 Base = Result.take();
John McCall129e2df2009-11-30 22:42:35 +00004654
Douglas Gregor01e56ae2010-04-12 20:54:26 +00004655 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4656 isDependentScopeSpecifier(SS)) {
John McCall9ae2f072010-08-23 23:25:46 +00004657 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00004658 IsArrow, OpLoc,
4659 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00004660 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004661 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00004662 LookupResult R(*this, NameInfo, LookupMemberName);
John Wiegley429bb272011-04-08 18:41:53 +00004663 ExprResult BaseResult = Owned(Base);
4664 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCallad00b772010-06-16 08:42:20 +00004665 SS, ObjCImpDecl, TemplateArgs != 0);
John Wiegley429bb272011-04-08 18:41:53 +00004666 if (BaseResult.isInvalid())
4667 return ExprError();
4668 Base = BaseResult.take();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004669
John McCallad00b772010-06-16 08:42:20 +00004670 if (Result.isInvalid()) {
4671 Owned(Base);
4672 return ExprError();
4673 }
John McCall129e2df2009-11-30 22:42:35 +00004674
John McCallad00b772010-06-16 08:42:20 +00004675 if (Result.get()) {
4676 // The only way a reference to a destructor can be used is to
4677 // immediately call it, which falls into this case. If the
4678 // next token is not a '(', produce a diagnostic and build the
4679 // call now.
4680 if (!HasTrailingLParen &&
4681 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCall9ae2f072010-08-23 23:25:46 +00004682 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall129e2df2009-11-30 22:42:35 +00004683
John McCallad00b772010-06-16 08:42:20 +00004684 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00004685 }
4686
John McCall9ae2f072010-08-23 23:25:46 +00004687 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00004688 OpLoc, IsArrow, SS, FirstQualifierInScope,
4689 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004690 }
4691
4692 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00004693}
4694
John McCall60d7b3a2010-08-24 06:29:42 +00004695ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00004696 FunctionDecl *FD,
4697 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00004698 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004699 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00004700 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00004701 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004702 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00004703 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004704 return ExprError();
4705 }
4706
4707 if (Param->hasUninstantiatedDefaultArg()) {
4708 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00004709
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004710 // Instantiate the expression.
4711 MultiLevelTemplateArgumentList ArgList
4712 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00004713
Nico Weber08e41a62010-11-29 18:19:25 +00004714 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004715 = ArgList.getInnermost();
4716 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4717 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004718
Nico Weber08e41a62010-11-29 18:19:25 +00004719 ExprResult Result;
4720 {
4721 // C++ [dcl.fct.default]p5:
4722 // The names in the [default argument] expression are bound, and
4723 // the semantic constraints are checked, at the point where the
4724 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00004725 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00004726 Result = SubstExpr(UninstExpr, ArgList);
4727 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004728 if (Result.isInvalid())
4729 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004730
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004731 // Check the expression as an initializer for the parameter.
4732 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004733 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004734 InitializationKind Kind
4735 = InitializationKind::CreateCopy(Param->getLocation(),
4736 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4737 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00004738
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004739 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4740 Result = InitSeq.Perform(*this, Entity, Kind,
4741 MultiExprArg(*this, &ResultE, 1));
4742 if (Result.isInvalid())
4743 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004744
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004745 // Build the default argument expression.
4746 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4747 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004748 }
4749
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004750 // If the default expression creates temporaries, we need to
4751 // push them to the current stack of expression temporaries so they'll
4752 // be properly destroyed.
4753 // FIXME: We should really be rebuilding the default argument with new
4754 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00004755 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4756 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4757 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4758 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4759 ExprTemporaries.push_back(Temporary);
John McCallf85e1932011-06-15 23:02:42 +00004760 ExprNeedsCleanups = true;
Douglas Gregor5833b0b2010-09-14 22:55:20 +00004761 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004762
4763 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00004764 // Just mark all of the declarations in this potentially-evaluated expression
4765 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004766 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00004767 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004768}
4769
Douglas Gregor88a35142008-12-22 05:46:06 +00004770/// ConvertArgumentsForCall - Converts the arguments specified in
4771/// Args/NumArgs to the parameter types of the function FDecl with
4772/// function prototype Proto. Call is the call expression itself, and
4773/// Fn is the function expression. For a C++ member function, this
4774/// routine does not attempt to convert the object argument. Returns
4775/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004776bool
4777Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00004778 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00004779 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00004780 Expr **Args, unsigned NumArgs,
4781 SourceLocation RParenLoc) {
John McCall8e10f3b2011-02-26 05:39:39 +00004782 // Bail out early if calling a builtin with custom typechecking.
4783 // We don't need to do this in the
4784 if (FDecl)
4785 if (unsigned ID = FDecl->getBuiltinID())
4786 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4787 return false;
4788
Mike Stumpeed9cac2009-02-19 03:04:26 +00004789 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00004790 // assignment, to the types of the corresponding parameter, ...
4791 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004792 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004793
Douglas Gregor88a35142008-12-22 05:46:06 +00004794 // If too few arguments are available (and we don't have default
4795 // arguments for the remaining parameters), don't make the call.
4796 if (NumArgs < NumArgsInProto) {
4797 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4798 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004799 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00004800 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004801 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00004802 }
4803
4804 // If too many are passed and not variadic, error on the extras and drop
4805 // them.
4806 if (NumArgs > NumArgsInProto) {
4807 if (!Proto->isVariadic()) {
4808 Diag(Args[NumArgsInProto]->getLocStart(),
4809 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004810 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00004811 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00004812 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4813 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00004814
4815 // Emit the location of the prototype.
4816 if (FDecl && !FDecl->getBuiltinID())
4817 Diag(FDecl->getLocStart(),
4818 diag::note_typecheck_call_too_many_args)
4819 << FDecl;
4820
Douglas Gregor88a35142008-12-22 05:46:06 +00004821 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004822 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004823 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004824 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004825 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004826 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004827 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004828 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4829 if (Fn->getType()->isBlockPointerType())
4830 CallType = VariadicBlock; // Block
4831 else if (isa<MemberExpr>(Fn))
4832 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004833 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004834 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004835 if (Invalid)
4836 return true;
4837 unsigned TotalNumArgs = AllArgs.size();
4838 for (unsigned i = 0; i < TotalNumArgs; ++i)
4839 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004840
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004841 return false;
4842}
Mike Stumpeed9cac2009-02-19 03:04:26 +00004843
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004844bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4845 FunctionDecl *FDecl,
4846 const FunctionProtoType *Proto,
4847 unsigned FirstProtoArg,
4848 Expr **Args, unsigned NumArgs,
4849 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004850 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004851 unsigned NumArgsInProto = Proto->getNumArgs();
4852 unsigned NumArgsToCheck = NumArgs;
4853 bool Invalid = false;
4854 if (NumArgs != NumArgsInProto)
4855 // Use default arguments for missing arguments
4856 NumArgsToCheck = NumArgsInProto;
4857 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00004858 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004859 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004860 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004861
Douglas Gregor88a35142008-12-22 05:46:06 +00004862 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004863 if (ArgIx < NumArgs) {
4864 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004865
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004866 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4867 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004868 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004869 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004870 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004871
Douglas Gregora188ff22009-12-22 16:09:06 +00004872 // Pass the argument
4873 ParmVarDecl *Param = 0;
4874 if (FDecl && i < FDecl->getNumParams())
4875 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00004876
Douglas Gregora188ff22009-12-22 16:09:06 +00004877 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004878 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00004879 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
4880 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00004881 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00004882 SourceLocation(),
4883 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00004884 if (ArgE.isInvalid())
4885 return true;
4886
4887 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004888 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00004889 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004890
John McCall60d7b3a2010-08-24 06:29:42 +00004891 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004892 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004893 if (ArgExpr.isInvalid())
4894 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004895
Anders Carlsson56c5e332009-08-25 03:49:14 +00004896 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004897 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004898 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004899 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004900
Douglas Gregor88a35142008-12-22 05:46:06 +00004901 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004902 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00004903
4904 // Assume that extern "C" functions with variadic arguments that
4905 // return __unknown_anytype aren't *really* variadic.
4906 if (Proto->getResultType() == Context.UnknownAnyTy &&
4907 FDecl && FDecl->isExternC()) {
4908 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4909 ExprResult arg;
4910 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
4911 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
4912 else
4913 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4914 Invalid |= arg.isInvalid();
4915 AllArgs.push_back(arg.take());
4916 }
4917
4918 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4919 } else {
4920 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4921 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4922 Invalid |= Arg.isInvalid();
4923 AllArgs.push_back(Arg.take());
4924 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004925 }
4926 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004927 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00004928}
4929
John McCall755d8492011-04-12 00:42:48 +00004930/// Given a function expression of unknown-any type, try to rebuild it
4931/// to have a function type.
4932static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4933
Steve Narofff69936d2007-09-16 03:34:24 +00004934/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00004935/// This provides the location of the left/right parens and a list of comma
4936/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00004937ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004938Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004939 MultiExprArg args, SourceLocation RParenLoc,
4940 Expr *ExecConfig) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00004941 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00004942
4943 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004944 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00004945 if (Result.isInvalid()) return ExprError();
4946 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00004947
John McCall9ae2f072010-08-23 23:25:46 +00004948 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004949
Douglas Gregor88a35142008-12-22 05:46:06 +00004950 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00004951 // If this is a pseudo-destructor expression, build the call immediately.
4952 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4953 if (NumArgs > 0) {
4954 // Pseudo-destructor calls should not have any arguments.
4955 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00004956 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00004957 SourceRange(Args[0]->getLocStart(),
4958 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00004959
Douglas Gregora71d8192009-09-04 17:36:40 +00004960 NumArgs = 0;
4961 }
Mike Stump1eb44332009-09-09 15:08:12 +00004962
Douglas Gregora71d8192009-09-04 17:36:40 +00004963 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00004964 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00004965 }
Mike Stump1eb44332009-09-09 15:08:12 +00004966
Douglas Gregor17330012009-02-04 15:01:18 +00004967 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004968 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00004969 // FIXME: Will need to cache the results of name lookup (including ADL) in
4970 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00004971 bool Dependent = false;
4972 if (Fn->isTypeDependent())
4973 Dependent = true;
4974 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4975 Dependent = true;
4976
Peter Collingbournee08ce652011-02-09 21:07:24 +00004977 if (Dependent) {
4978 if (ExecConfig) {
4979 return Owned(new (Context) CUDAKernelCallExpr(
4980 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4981 Context.DependentTy, VK_RValue, RParenLoc));
4982 } else {
4983 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4984 Context.DependentTy, VK_RValue,
4985 RParenLoc));
4986 }
4987 }
Douglas Gregor17330012009-02-04 15:01:18 +00004988
4989 // Determine whether this is a call to an object (C++ [over.call.object]).
4990 if (Fn->getType()->isRecordType())
4991 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004992 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00004993
John McCall755d8492011-04-12 00:42:48 +00004994 if (Fn->getType() == Context.UnknownAnyTy) {
4995 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4996 if (result.isInvalid()) return ExprError();
4997 Fn = result.take();
4998 }
4999
John McCall864c0412011-04-26 20:42:42 +00005000 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00005001 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00005002 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00005003 }
John McCall864c0412011-04-26 20:42:42 +00005004 }
John McCall129e2df2009-11-30 22:42:35 +00005005
John McCall864c0412011-04-26 20:42:42 +00005006 // Check for overloaded calls. This can happen even in C due to extensions.
5007 if (Fn->getType() == Context.OverloadTy) {
5008 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5009
5010 // We aren't supposed to apply this logic if there's an '&' involved.
5011 if (!find.IsAddressOfOperand) {
5012 OverloadExpr *ovl = find.Expression;
5013 if (isa<UnresolvedLookupExpr>(ovl)) {
5014 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
5015 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
5016 RParenLoc, ExecConfig);
5017 } else {
John McCallaa81e162009-12-01 22:10:20 +00005018 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00005019 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00005020 }
5021 }
Douglas Gregor88a35142008-12-22 05:46:06 +00005022 }
5023
Douglas Gregorfa047642009-02-04 00:32:51 +00005024 // If we're directly calling a function, get the appropriate declaration.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005025
Eli Friedmanefa42f72009-12-26 03:35:45 +00005026 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00005027
John McCall3b4294e2009-12-16 12:17:52 +00005028 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00005029 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
5030 if (UnOp->getOpcode() == UO_AddrOf)
5031 NakedFn = UnOp->getSubExpr()->IgnoreParens();
5032
John McCall3b4294e2009-12-16 12:17:52 +00005033 if (isa<DeclRefExpr>(NakedFn))
5034 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00005035 else if (isa<MemberExpr>(NakedFn))
5036 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00005037
Peter Collingbournee08ce652011-02-09 21:07:24 +00005038 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
5039 ExecConfig);
5040}
5041
5042ExprResult
5043Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5044 MultiExprArg execConfig, SourceLocation GGGLoc) {
5045 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
5046 if (!ConfigDecl)
5047 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
5048 << "cudaConfigureCall");
5049 QualType ConfigQTy = ConfigDecl->getType();
5050
5051 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
5052 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
5053
5054 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00005055}
5056
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005057/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5058///
5059/// __builtin_astype( value, dst type )
5060///
5061ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
5062 SourceLocation BuiltinLoc,
5063 SourceLocation RParenLoc) {
5064 ExprValueKind VK = VK_RValue;
5065 ExprObjectKind OK = OK_Ordinary;
5066 QualType DstTy = GetTypeFromParser(destty);
5067 QualType SrcTy = expr->getType();
5068 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5069 return ExprError(Diag(BuiltinLoc,
5070 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00005071 << DstTy
5072 << SrcTy
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005073 << expr->getSourceRange());
5074 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc, RParenLoc));
5075}
5076
John McCall3b4294e2009-12-16 12:17:52 +00005077/// BuildResolvedCallExpr - Build a call to a resolved expression,
5078/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00005079/// unary-convert to an expression of function-pointer or
5080/// block-pointer type.
5081///
5082/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00005083ExprResult
John McCallaa81e162009-12-01 22:10:20 +00005084Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5085 SourceLocation LParenLoc,
5086 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00005087 SourceLocation RParenLoc,
5088 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00005089 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5090
Chris Lattner04421082008-04-08 04:40:51 +00005091 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00005092 ExprResult Result = UsualUnaryConversions(Fn);
5093 if (Result.isInvalid())
5094 return ExprError();
5095 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00005096
Chris Lattner925e60d2007-12-28 05:29:59 +00005097 // Make the call expr early, before semantic checks. This guarantees cleanup
5098 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00005099 CallExpr *TheCall;
5100 if (Config) {
5101 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5102 cast<CallExpr>(Config),
5103 Args, NumArgs,
5104 Context.BoolTy,
5105 VK_RValue,
5106 RParenLoc);
5107 } else {
5108 TheCall = new (Context) CallExpr(Context, Fn,
5109 Args, NumArgs,
5110 Context.BoolTy,
5111 VK_RValue,
5112 RParenLoc);
5113 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00005114
John McCall8e10f3b2011-02-26 05:39:39 +00005115 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5116
5117 // Bail out early if calling a builtin with custom typechecking.
5118 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5119 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
5120
John McCall1de4d4e2011-04-07 08:22:57 +00005121 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00005122 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00005123 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00005124 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5125 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00005126 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00005127 if (FuncT == 0)
5128 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5129 << Fn->getType() << Fn->getSourceRange());
5130 } else if (const BlockPointerType *BPT =
5131 Fn->getType()->getAs<BlockPointerType>()) {
5132 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5133 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00005134 // Handle calls to expressions of unknown-any type.
5135 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00005136 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00005137 if (rewrite.isInvalid()) return ExprError();
5138 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00005139 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00005140 goto retry;
5141 }
5142
Sebastian Redl0eb23302009-01-19 00:08:26 +00005143 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5144 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00005145 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00005146
Peter Collingbourne0423fc62011-02-23 01:53:29 +00005147 if (getLangOptions().CUDA) {
5148 if (Config) {
5149 // CUDA: Kernel calls must be to global functions
5150 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5151 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5152 << FDecl->getName() << Fn->getSourceRange());
5153
5154 // CUDA: Kernel function must have 'void' return type
5155 if (!FuncT->getResultType()->isVoidType())
5156 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5157 << Fn->getType() << Fn->getSourceRange());
5158 }
5159 }
5160
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00005161 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005162 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00005163 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00005164 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00005165 return ExprError();
5166
Chris Lattner925e60d2007-12-28 05:29:59 +00005167 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00005168 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00005169 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00005170
Douglas Gregor72564e72009-02-26 23:50:07 +00005171 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00005172 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005173 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00005174 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00005175 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00005176 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00005177
Douglas Gregor74734d52009-04-02 15:37:10 +00005178 if (FDecl) {
5179 // Check if we have too few/too many template arguments, based
5180 // on our knowledge of the function definition.
5181 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00005182 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00005183 const FunctionProtoType *Proto
5184 = Def->getType()->getAs<FunctionProtoType>();
5185 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00005186 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5187 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00005188 }
Douglas Gregor46542412010-10-25 20:39:23 +00005189
5190 // If the function we're calling isn't a function prototype, but we have
5191 // a function prototype from a prior declaratiom, use that prototype.
5192 if (!FDecl->hasPrototype())
5193 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00005194 }
5195
Steve Naroffb291ab62007-08-28 23:30:39 +00005196 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00005197 for (unsigned i = 0; i != NumArgs; i++) {
5198 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00005199
5200 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00005201 InitializedEntity Entity
5202 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00005203 Proto->getArgType(i),
5204 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00005205 ExprResult ArgE = PerformCopyInitialization(Entity,
5206 SourceLocation(),
5207 Owned(Arg));
5208 if (ArgE.isInvalid())
5209 return true;
5210
5211 Arg = ArgE.takeAs<Expr>();
5212
5213 } else {
John Wiegley429bb272011-04-08 18:41:53 +00005214 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5215
5216 if (ArgE.isInvalid())
5217 return true;
5218
5219 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00005220 }
5221
Douglas Gregor0700bbf2010-10-26 05:45:40 +00005222 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
5223 Arg->getType(),
5224 PDiag(diag::err_call_incomplete_argument)
5225 << Arg->getSourceRange()))
5226 return ExprError();
5227
Chris Lattner925e60d2007-12-28 05:29:59 +00005228 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00005229 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005230 }
Chris Lattner925e60d2007-12-28 05:29:59 +00005231
Douglas Gregor88a35142008-12-22 05:46:06 +00005232 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5233 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005234 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5235 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00005236
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00005237 // Check for sentinels
5238 if (NDecl)
5239 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00005240
Chris Lattner59907c42007-08-10 20:18:51 +00005241 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00005242 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00005243 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00005244 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00005245
John McCall8e10f3b2011-02-26 05:39:39 +00005246 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00005247 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00005248 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00005249 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00005250 return ExprError();
5251 }
Chris Lattner59907c42007-08-10 20:18:51 +00005252
John McCall9ae2f072010-08-23 23:25:46 +00005253 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00005254}
5255
John McCall60d7b3a2010-08-24 06:29:42 +00005256ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005257Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005258 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00005259 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00005260 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00005261 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00005262
5263 TypeSourceInfo *TInfo;
5264 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5265 if (!TInfo)
5266 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5267
John McCall9ae2f072010-08-23 23:25:46 +00005268 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00005269}
5270
John McCall60d7b3a2010-08-24 06:29:42 +00005271ExprResult
John McCall42f56b52010-01-18 19:35:47 +00005272Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00005273 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00005274 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00005275
Eli Friedman6223c222008-05-20 05:22:08 +00005276 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00005277 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5278 PDiag(diag::err_illegal_decl_array_incomplete_type)
5279 << SourceRange(LParenLoc,
5280 literalExpr->getSourceRange().getEnd())))
5281 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00005282 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005283 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5284 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00005285 } else if (!literalType->isDependentType() &&
5286 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00005287 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005288 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00005289 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005290 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00005291
Douglas Gregor99a2e602009-12-16 01:38:02 +00005292 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00005293 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005294 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00005295 = InitializationKind::CreateCStyleCast(LParenLoc,
5296 SourceRange(LParenLoc, RParenLoc));
Eli Friedman08544622009-12-22 02:35:53 +00005297 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00005298 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00005299 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00005300 &literalType);
5301 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005302 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00005303 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00005304
Chris Lattner371f2582008-12-04 23:50:19 +00005305 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00005306 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00005307 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005308 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00005309 }
Eli Friedman08544622009-12-22 02:35:53 +00005310
John McCallf89e55a2010-11-18 06:31:45 +00005311 // In C, compound literals are l-values for some reason.
5312 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
5313
Douglas Gregor751ec9b2011-06-17 04:59:12 +00005314 return MaybeBindToTemporary(
5315 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5316 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00005317}
5318
John McCall60d7b3a2010-08-24 06:29:42 +00005319ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005320Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005321 SourceLocation RBraceLoc) {
5322 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00005323 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00005324
Steve Naroff08d92e42007-09-15 18:49:24 +00005325 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00005326 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005327
Ted Kremenek709210f2010-04-13 23:39:13 +00005328 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
5329 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00005330 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005331 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00005332}
5333
John McCallf3ea8cf2010-11-14 08:17:51 +00005334/// Prepares for a scalar cast, performing all the necessary stages
5335/// except the final cast and returning the kind required.
John Wiegley429bb272011-04-08 18:41:53 +00005336static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00005337 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5338 // Also, callers should have filtered out the invalid cases with
5339 // pointers. Everything else should be possible.
5340
John Wiegley429bb272011-04-08 18:41:53 +00005341 QualType SrcTy = Src.get()->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00005342 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00005343 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00005344
John McCalldaa8e4e2010-11-15 09:13:47 +00005345 switch (SrcTy->getScalarTypeKind()) {
5346 case Type::STK_MemberPointer:
5347 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005348
John McCalldaa8e4e2010-11-15 09:13:47 +00005349 case Type::STK_Pointer:
5350 switch (DestTy->getScalarTypeKind()) {
5351 case Type::STK_Pointer:
5352 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00005353 CK_AnyPointerToObjCPointerCast :
5354 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005355 case Type::STK_Bool:
5356 return CK_PointerToBoolean;
5357 case Type::STK_Integral:
5358 return CK_PointerToIntegral;
5359 case Type::STK_Floating:
5360 case Type::STK_FloatingComplex:
5361 case Type::STK_IntegralComplex:
5362 case Type::STK_MemberPointer:
5363 llvm_unreachable("illegal cast from pointer");
5364 }
5365 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005366
John McCalldaa8e4e2010-11-15 09:13:47 +00005367 case Type::STK_Bool: // casting from bool is like casting from an integer
5368 case Type::STK_Integral:
5369 switch (DestTy->getScalarTypeKind()) {
5370 case Type::STK_Pointer:
John Wiegley429bb272011-04-08 18:41:53 +00005371 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00005372 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00005373 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005374 case Type::STK_Bool:
5375 return CK_IntegralToBoolean;
5376 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00005377 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005378 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00005379 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00005380 case Type::STK_IntegralComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005381 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5382 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00005383 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005384 case Type::STK_FloatingComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005385 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5386 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00005387 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005388 case Type::STK_MemberPointer:
5389 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005390 }
5391 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005392
John McCalldaa8e4e2010-11-15 09:13:47 +00005393 case Type::STK_Floating:
5394 switch (DestTy->getScalarTypeKind()) {
5395 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00005396 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005397 case Type::STK_Bool:
5398 return CK_FloatingToBoolean;
5399 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00005400 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00005401 case Type::STK_FloatingComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005402 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5403 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00005404 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005405 case Type::STK_IntegralComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005406 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5407 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00005408 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005409 case Type::STK_Pointer:
5410 llvm_unreachable("valid float->pointer cast?");
5411 case Type::STK_MemberPointer:
5412 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005413 }
5414 break;
5415
John McCalldaa8e4e2010-11-15 09:13:47 +00005416 case Type::STK_FloatingComplex:
5417 switch (DestTy->getScalarTypeKind()) {
5418 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005419 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005420 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005421 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00005422 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005423 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005424 if (S.Context.hasSameType(ET, DestTy))
5425 return CK_FloatingComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00005426 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00005427 return CK_FloatingCast;
5428 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005429 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00005430 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00005431 case Type::STK_Integral:
John Wiegley429bb272011-04-08 18:41:53 +00005432 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5433 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00005434 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00005435 case Type::STK_Pointer:
5436 llvm_unreachable("valid complex float->pointer cast?");
5437 case Type::STK_MemberPointer:
5438 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005439 }
5440 break;
5441
John McCalldaa8e4e2010-11-15 09:13:47 +00005442 case Type::STK_IntegralComplex:
5443 switch (DestTy->getScalarTypeKind()) {
5444 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005445 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005446 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005447 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00005448 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005449 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005450 if (S.Context.hasSameType(ET, DestTy))
5451 return CK_IntegralComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00005452 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00005453 return CK_IntegralCast;
5454 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005455 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00005456 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00005457 case Type::STK_Floating:
John Wiegley429bb272011-04-08 18:41:53 +00005458 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5459 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00005460 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00005461 case Type::STK_Pointer:
5462 llvm_unreachable("valid complex int->pointer cast?");
5463 case Type::STK_MemberPointer:
5464 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005465 }
5466 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00005467 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005468
John McCallf3ea8cf2010-11-14 08:17:51 +00005469 llvm_unreachable("Unhandled scalar cast");
5470 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00005471}
5472
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005473/// CheckCastTypes - Check type constraints for casting between types.
John McCallf85e1932011-06-15 23:02:42 +00005474ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
5475 QualType castType, Expr *castExpr,
5476 CastKind& Kind, ExprValueKind &VK,
John Wiegley429bb272011-04-08 18:41:53 +00005477 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall1de4d4e2011-04-07 08:22:57 +00005478 if (castExpr->getType() == Context.UnknownAnyTy)
5479 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5480
Sebastian Redl9cc11e72009-07-25 15:41:38 +00005481 if (getLangOptions().CPlusPlus)
John McCallf85e1932011-06-15 23:02:42 +00005482 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor40749ee2010-11-03 00:35:38 +00005483 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00005484 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005485 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00005486
John McCallfb8721c2011-04-10 19:13:55 +00005487 assert(!castExpr->getType()->isPlaceholderType());
5488
John McCallf89e55a2010-11-18 06:31:45 +00005489 // We only support r-value casts in C.
5490 VK = VK_RValue;
5491
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005492 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5493 // type needs to be scalar.
5494 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00005495 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley429bb272011-04-08 18:41:53 +00005496 ExprResult castExprRes = IgnoredValueConversions(castExpr);
5497 if (castExprRes.isInvalid())
5498 return ExprError();
5499 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00005500
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005501 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00005502 Kind = CK_ToVoid;
John Wiegley429bb272011-04-08 18:41:53 +00005503 return Owned(castExpr);
Anders Carlssonebeaf202009-10-16 02:35:04 +00005504 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005505
John Wiegley429bb272011-04-08 18:41:53 +00005506 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
5507 if (castExprRes.isInvalid())
5508 return ExprError();
5509 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00005510
Eli Friedman8d438082010-07-17 20:43:49 +00005511 if (RequireCompleteType(TyR.getBegin(), castType,
5512 diag::err_typecheck_cast_to_incomplete))
John Wiegley429bb272011-04-08 18:41:53 +00005513 return ExprError();
Eli Friedman8d438082010-07-17 20:43:49 +00005514
Anders Carlssonebeaf202009-10-16 02:35:04 +00005515 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00005516 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005517 (castType->isStructureType() || castType->isUnionType())) {
5518 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005519 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005520 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5521 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005522 Kind = CK_NoOp;
John Wiegley429bb272011-04-08 18:41:53 +00005523 return Owned(castExpr);
Anders Carlssonc3516322009-10-16 02:48:28 +00005524 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005525
Anders Carlssonc3516322009-10-16 02:48:28 +00005526 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005527 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00005528 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005529 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005530 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005531 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005532 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00005533 castExpr->getType()) &&
5534 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005535 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5536 << castExpr->getSourceRange();
5537 break;
5538 }
5539 }
John Wiegley429bb272011-04-08 18:41:53 +00005540 if (Field == FieldEnd) {
5541 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005542 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005543 return ExprError();
5544 }
John McCall2de56d12010-08-25 11:45:40 +00005545 Kind = CK_ToUnion;
John Wiegley429bb272011-04-08 18:41:53 +00005546 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005547 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005548
Anders Carlssonc3516322009-10-16 02:48:28 +00005549 // Reject any other conversions to non-scalar types.
John Wiegley429bb272011-04-08 18:41:53 +00005550 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlssonc3516322009-10-16 02:48:28 +00005551 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005552 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00005553 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005554
John McCallf3ea8cf2010-11-14 08:17:51 +00005555 // The type we're casting to is known to be a scalar or vector.
5556
5557 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005558 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00005559 !castExpr->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005560 Diag(castExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005561 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00005562 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005563 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00005564 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005565
5566 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00005567 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005568
Anton Yartsevd06fea82011-03-27 09:32:40 +00005569 if (castType->isVectorType()) {
5570 if (castType->getAs<VectorType>()->getVectorKind() ==
5571 VectorType::AltiVecVector &&
5572 (castExpr->getType()->isIntegerType() ||
5573 castExpr->getType()->isFloatingType())) {
5574 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00005575 return Owned(castExpr);
5576 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
5577 return ExprError();
Anton Yartsevd06fea82011-03-27 09:32:40 +00005578 } else
John Wiegley429bb272011-04-08 18:41:53 +00005579 return Owned(castExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00005580 }
John Wiegley429bb272011-04-08 18:41:53 +00005581 if (castExpr->getType()->isVectorType()) {
5582 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
5583 return ExprError();
5584 else
5585 return Owned(castExpr);
5586 }
Anders Carlssonc3516322009-10-16 02:48:28 +00005587
John McCallf3ea8cf2010-11-14 08:17:51 +00005588 // The source and target types are both scalars, i.e.
5589 // - arithmetic types (fundamental, enum, and complex)
5590 // - all kinds of pointers
5591 // Note that member pointers were filtered out with C++, above.
5592
John Wiegley429bb272011-04-08 18:41:53 +00005593 if (isa<ObjCSelectorExpr>(castExpr)) {
5594 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5595 return ExprError();
5596 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005597
John McCallf3ea8cf2010-11-14 08:17:51 +00005598 // If either type is a pointer, the other type has to be either an
5599 // integer or a pointer.
John McCallf85e1932011-06-15 23:02:42 +00005600 QualType castExprType = castExpr->getType();
Anders Carlssonc3516322009-10-16 02:48:28 +00005601 if (!castType->isArithmeticType()) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005602 if (!castExprType->isIntegralType(Context) &&
John Wiegley429bb272011-04-08 18:41:53 +00005603 castExprType->isArithmeticType()) {
5604 Diag(castExpr->getLocStart(),
5605 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00005606 << castExprType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005607 return ExprError();
5608 }
Eli Friedman41826bb2009-05-01 02:23:58 +00005609 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005610 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
5611 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00005612 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005613 return ExprError();
5614 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005615 }
Anders Carlsson82debc72009-10-18 18:12:03 +00005616
John McCallf85e1932011-06-15 23:02:42 +00005617 if (getLangOptions().ObjCAutoRefCount) {
5618 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
5619 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
5620 castType, castExpr, CCK_CStyleCast);
5621
5622 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
5623 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
5624 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
5625 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
5626 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
5627 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
5628 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
5629 Diag(castExpr->getLocStart(),
5630 diag::err_typecheck_incompatible_lifetime)
5631 << castExprType << castType << AA_Casting
5632 << castExpr->getSourceRange();
5633
5634 return ExprError();
5635 }
5636 }
5637 }
5638 }
5639
John Wiegley429bb272011-04-08 18:41:53 +00005640 castExprRes = Owned(castExpr);
5641 Kind = PrepareScalarCast(*this, castExprRes, castType);
5642 if (castExprRes.isInvalid())
5643 return ExprError();
5644 castExpr = castExprRes.take();
John McCallb7f4ffe2010-08-12 21:44:57 +00005645
John McCallf3ea8cf2010-11-14 08:17:51 +00005646 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00005647 CheckCastAlign(castExpr, castType, TyR);
5648
John Wiegley429bb272011-04-08 18:41:53 +00005649 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005650}
5651
Anders Carlssonc3516322009-10-16 02:48:28 +00005652bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00005653 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00005654 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005655
Anders Carlssona64db8f2007-11-27 05:51:55 +00005656 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00005657 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00005658 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00005659 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00005660 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005661 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00005662 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005663 } else
5664 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005665 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00005666 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005667
John McCall2de56d12010-08-25 11:45:40 +00005668 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005669 return false;
5670}
5671
John Wiegley429bb272011-04-08 18:41:53 +00005672ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5673 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00005674 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005675
Anders Carlsson16a89042009-10-16 05:23:41 +00005676 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005677
Nate Begeman9b10da62009-06-27 22:05:55 +00005678 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5679 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00005680 if (SrcTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005681 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
5682 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00005683 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00005684 return ExprError();
5685 }
John McCall2de56d12010-08-25 11:45:40 +00005686 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00005687 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00005688 }
5689
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005690 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00005691 // conversion will take place first from scalar to elt type, and then
5692 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005693 if (SrcTy->isPointerType())
5694 return Diag(R.getBegin(),
5695 diag::err_invalid_conversion_between_vector_and_scalar)
5696 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00005697
5698 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00005699 ExprResult CastExprRes = Owned(CastExpr);
5700 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
5701 if (CastExprRes.isInvalid())
5702 return ExprError();
5703 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005704
John McCall2de56d12010-08-25 11:45:40 +00005705 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00005706 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00005707}
5708
John McCall60d7b3a2010-08-24 06:29:42 +00005709ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005710Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005711 SourceLocation RParenLoc, Expr *castExpr) {
5712 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005713 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00005714
John McCall9d125032010-01-15 18:39:57 +00005715 TypeSourceInfo *castTInfo;
5716 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5717 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00005718 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00005719
Nate Begeman2ef13e52009-08-10 23:49:36 +00005720 // If the Expr being casted is a ParenListExpr, handle it specially.
5721 if (isa<ParenListExpr>(castExpr))
John McCall9ae2f072010-08-23 23:25:46 +00005722 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCall42f56b52010-01-18 19:35:47 +00005723 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00005724
John McCall9ae2f072010-08-23 23:25:46 +00005725 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00005726}
5727
John McCall60d7b3a2010-08-24 06:29:42 +00005728ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00005729Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005730 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005731 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00005732 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00005733 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +00005734 ExprResult CastResult =
John McCallf85e1932011-06-15 23:02:42 +00005735 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
5736 castExpr, Kind, VK, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +00005737 if (CastResult.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005738 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00005739 castExpr = CastResult.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +00005740
John McCallf871d0c2010-08-07 06:22:56 +00005741 return Owned(CStyleCastExpr::Create(Context,
John Wiegley429bb272011-04-08 18:41:53 +00005742 Ty->getType().getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +00005743 VK, Kind, castExpr, &BasePath, Ty,
John McCallf871d0c2010-08-07 06:22:56 +00005744 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005745}
5746
Nate Begeman2ef13e52009-08-10 23:49:36 +00005747/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5748/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005749ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005750Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005751 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5752 if (!E)
5753 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00005754
John McCall60d7b3a2010-08-24 06:29:42 +00005755 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00005756
Nate Begeman2ef13e52009-08-10 23:49:36 +00005757 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00005758 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5759 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00005760
John McCall9ae2f072010-08-23 23:25:46 +00005761 if (Result.isInvalid()) return ExprError();
5762
5763 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005764}
5765
John McCall60d7b3a2010-08-24 06:29:42 +00005766ExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00005767Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00005768 SourceLocation RParenLoc, Expr *Op,
John McCall42f56b52010-01-18 19:35:47 +00005769 TypeSourceInfo *TInfo) {
John McCall9ae2f072010-08-23 23:25:46 +00005770 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCall42f56b52010-01-18 19:35:47 +00005771 QualType Ty = TInfo->getType();
Anton Yartsevd06fea82011-03-27 09:32:40 +00005772 bool isVectorLiteral = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005773
Anton Yartsevd06fea82011-03-27 09:32:40 +00005774 // Check for an altivec or OpenCL literal,
John Thompson8bb59a82010-06-30 22:55:51 +00005775 // i.e. all the elements are integer constants.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005776 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5777 if (PE->getNumExprs() == 0) {
5778 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5779 return ExprError();
5780 }
John Thompson8bb59a82010-06-30 22:55:51 +00005781 if (PE->getNumExprs() == 1) {
5782 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsevd06fea82011-03-27 09:32:40 +00005783 isVectorLiteral = true;
John Thompson8bb59a82010-06-30 22:55:51 +00005784 }
5785 else
Anton Yartsevd06fea82011-03-27 09:32:40 +00005786 isVectorLiteral = true;
John Thompson8bb59a82010-06-30 22:55:51 +00005787 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00005788
Anton Yartsevd06fea82011-03-27 09:32:40 +00005789 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson8bb59a82010-06-30 22:55:51 +00005790 // then handle it as such.
Anton Yartsevd06fea82011-03-27 09:32:40 +00005791 if (isVectorLiteral) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005792 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsevd06fea82011-03-27 09:32:40 +00005793 // '(...)' form of vector initialization in AltiVec: the number of
5794 // initializers must be one or must match the size of the vector.
5795 // If a single value is specified in the initializer then it will be
5796 // replicated to all the components of the vector
5797 if (Ty->getAs<VectorType>()->getVectorKind() ==
5798 VectorType::AltiVecVector) {
5799 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5800 // The number of initializers must be one or must match the size of the
5801 // vector. If a single value is specified in the initializer then it will
5802 // be replicated to all the components of the vector
5803 if (PE->getNumExprs() == 1) {
5804 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00005805 ExprResult Literal = Owned(PE->getExpr(0));
5806 Literal = ImpCastExprToType(Literal.take(), ElemTy,
5807 PrepareScalarCast(*this, Literal, ElemTy));
5808 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
Anton Yartsevd06fea82011-03-27 09:32:40 +00005809 }
5810 else if (PE->getNumExprs() < numElems) {
5811 Diag(PE->getExprLoc(),
5812 diag::err_incorrect_number_of_vector_initializers);
5813 return ExprError();
5814 }
5815 else
5816 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5817 initExprs.push_back(PE->getExpr(i));
5818 }
5819 else
5820 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5821 initExprs.push_back(PE->getExpr(i));
Nate Begeman2ef13e52009-08-10 23:49:36 +00005822
5823 // FIXME: This means that pretty-printing the final AST will produce curly
5824 // braces instead of the original commas.
Ted Kremenek709210f2010-04-13 23:39:13 +00005825 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5826 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00005827 initExprs.size(), RParenLoc);
5828 E->setType(Ty);
John McCall9ae2f072010-08-23 23:25:46 +00005829 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005830 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005831 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00005832 // sequence of BinOp comma operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005833 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCall9ae2f072010-08-23 23:25:46 +00005834 if (Result.isInvalid()) return ExprError();
5835 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005836 }
5837}
5838
John McCall60d7b3a2010-08-24 06:29:42 +00005839ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00005840 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005841 MultiExprArg Val,
John McCallb3d87482010-08-24 05:47:05 +00005842 ParsedType TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005843 unsigned nexprs = Val.size();
5844 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005845 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5846 Expr *expr;
5847 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5848 expr = new (Context) ParenExpr(L, R, exprs[0]);
5849 else
5850 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005851 return Owned(expr);
5852}
5853
Chandler Carruth82214a82011-02-18 23:54:50 +00005854/// \brief Emit a specialized diagnostic when one expression is a null pointer
5855/// constant and the other is not a pointer.
5856bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5857 SourceLocation QuestionLoc) {
5858 Expr *NullExpr = LHS;
5859 Expr *NonPointerExpr = RHS;
5860 Expr::NullPointerConstantKind NullKind =
5861 NullExpr->isNullPointerConstant(Context,
5862 Expr::NPC_ValueDependentIsNotNull);
5863
5864 if (NullKind == Expr::NPCK_NotNull) {
5865 NullExpr = RHS;
5866 NonPointerExpr = LHS;
5867 NullKind =
5868 NullExpr->isNullPointerConstant(Context,
5869 Expr::NPC_ValueDependentIsNotNull);
5870 }
5871
5872 if (NullKind == Expr::NPCK_NotNull)
5873 return false;
5874
5875 if (NullKind == Expr::NPCK_ZeroInteger) {
5876 // In this case, check to make sure that we got here from a "NULL"
5877 // string in the source code.
5878 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00005879 SourceLocation loc = NullExpr->getExprLoc();
5880 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00005881 return false;
5882 }
5883
5884 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5885 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5886 << NonPointerExpr->getType() << DiagType
5887 << NonPointerExpr->getSourceRange();
5888 return true;
5889}
5890
Sebastian Redl28507842009-02-26 14:39:58 +00005891/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5892/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00005893/// C99 6.5.15
John Wiegley429bb272011-04-08 18:41:53 +00005894QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005895 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00005896 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00005897
John McCallfb8721c2011-04-10 19:13:55 +00005898 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00005899 if (!lhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00005900 LHS = move(lhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005901
John McCallfb8721c2011-04-10 19:13:55 +00005902 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00005903 if (!rhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00005904 RHS = move(rhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005905
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005906 // C++ is sufficiently different to merit its own checker.
5907 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00005908 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00005909
5910 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005911 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005912
John Wiegley429bb272011-04-08 18:41:53 +00005913 Cond = UsualUnaryConversions(Cond.take());
5914 if (Cond.isInvalid())
5915 return QualType();
5916 LHS = UsualUnaryConversions(LHS.take());
5917 if (LHS.isInvalid())
5918 return QualType();
5919 RHS = UsualUnaryConversions(RHS.take());
5920 if (RHS.isInvalid())
5921 return QualType();
5922
5923 QualType CondTy = Cond.get()->getType();
5924 QualType LHSTy = LHS.get()->getType();
5925 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005926
Reid Spencer5f016e22007-07-11 17:01:13 +00005927 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005928 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begeman6155d732010-09-20 22:41:17 +00005929 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5930 // Throw an error if its not either.
5931 if (getLangOptions().OpenCL) {
5932 if (!CondTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005933 Diag(Cond.get()->getLocStart(),
Nate Begeman6155d732010-09-20 22:41:17 +00005934 diag::err_typecheck_cond_expect_scalar_or_vector)
5935 << CondTy;
5936 return QualType();
5937 }
5938 }
5939 else {
John Wiegley429bb272011-04-08 18:41:53 +00005940 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005941 << CondTy;
5942 return QualType();
5943 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005944 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005945
Chris Lattner70d67a92008-01-06 22:42:25 +00005946 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005947 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5948 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00005949
Nate Begeman6155d732010-09-20 22:41:17 +00005950 // OpenCL: If the condition is a vector, and both operands are scalar,
5951 // attempt to implicity convert them to the vector type to act like the
5952 // built in select.
5953 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5954 // Both operands should be of scalar type.
5955 if (!LHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005956 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005957 << CondTy;
5958 return QualType();
5959 }
5960 if (!RHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005961 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005962 << CondTy;
5963 return QualType();
5964 }
5965 // Implicity convert these scalars to the type of the condition.
John Wiegley429bb272011-04-08 18:41:53 +00005966 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5967 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begeman6155d732010-09-20 22:41:17 +00005968 }
5969
Chris Lattner70d67a92008-01-06 22:42:25 +00005970 // If both operands have arithmetic type, do the usual arithmetic conversions
5971 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005972 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5973 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00005974 if (LHS.isInvalid() || RHS.isInvalid())
5975 return QualType();
5976 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005977 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005978
Chris Lattner70d67a92008-01-06 22:42:25 +00005979 // If both operands are the same structure or union type, the result is that
5980 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005981 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5982 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005983 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005984 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005985 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005986 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005987 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005988 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005989
Chris Lattner70d67a92008-01-06 22:42:25 +00005990 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005991 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005992 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5993 if (!LHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00005994 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5995 << RHS.get()->getSourceRange();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005996 if (!RHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00005997 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5998 << LHS.get()->getSourceRange();
5999 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
6000 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00006001 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00006002 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00006003 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6004 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006005 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley429bb272011-04-08 18:41:53 +00006006 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00006007 // promote the null to a pointer.
John Wiegley429bb272011-04-08 18:41:53 +00006008 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00006009 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00006010 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006011 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley429bb272011-04-08 18:41:53 +00006012 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6013 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00006014 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00006015 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006016
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006017 // All objective-c pointer type analysis is done here.
6018 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6019 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00006020 if (LHS.isInvalid() || RHS.isInvalid())
6021 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006022 if (!compositeType.isNull())
6023 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006024
6025
Steve Naroff7154a772009-07-01 14:36:47 +00006026 // Handle block pointer types.
6027 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
6028 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6029 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6030 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00006031 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
6032 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00006033 return destType;
6034 }
6035 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00006036 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00006037 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00006038 }
Steve Naroff7154a772009-07-01 14:36:47 +00006039 // We have 2 block pointer types.
6040 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6041 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00006042 return LHSTy;
6043 }
Steve Naroff7154a772009-07-01 14:36:47 +00006044 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00006045 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
6046 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006047
Steve Naroff7154a772009-07-01 14:36:47 +00006048 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
6049 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00006050 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00006051 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00006052 // In this situation, we assume void* type. No especially good
6053 // reason, but this is what gcc does, and we do have to pick
6054 // to get a consistent AST.
6055 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00006056 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6057 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00006058 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006059 }
Steve Naroff7154a772009-07-01 14:36:47 +00006060 // The block pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00006061 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
6062 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00006063 return LHSTy;
6064 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006065
Steve Naroff7154a772009-07-01 14:36:47 +00006066 // Check constraints for C object pointers types (C99 6.5.15p3,6).
6067 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
6068 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00006069 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6070 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00006071
6072 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6073 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6074 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00006075 QualType destPointee
6076 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00006077 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00006078 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00006079 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00006080 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00006081 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00006082 return destType;
6083 }
6084 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00006085 QualType destPointee
6086 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00006087 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00006088 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00006089 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00006090 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00006091 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00006092 return destType;
6093 }
6094
6095 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6096 // Two identical pointer types are always compatible.
6097 return LHSTy;
6098 }
6099 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
6100 rhptee.getUnqualifiedType())) {
6101 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00006102 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00006103 // In this situation, we assume void* type. No especially good
6104 // reason, but this is what gcc does, and we do have to pick
6105 // to get a consistent AST.
6106 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00006107 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6108 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00006109 return incompatTy;
6110 }
6111 // The pointer types are compatible.
6112 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
6113 // differently qualified versions of compatible types, the result type is
6114 // a pointer to an appropriately qualified version of the *composite*
6115 // type.
6116 // FIXME: Need to calculate the composite type.
6117 // FIXME: Need to add qualifiers
John Wiegley429bb272011-04-08 18:41:53 +00006118 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
6119 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00006120 return LHSTy;
6121 }
Mike Stump1eb44332009-09-09 15:08:12 +00006122
John McCall404cd162010-11-13 01:35:44 +00006123 // GCC compatibility: soften pointer/integer mismatch. Note that
6124 // null pointers have been filtered out by this point.
Steve Naroff7154a772009-07-01 14:36:47 +00006125 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
6126 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley429bb272011-04-08 18:41:53 +00006127 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6128 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00006129 return RHSTy;
6130 }
6131 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
6132 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley429bb272011-04-08 18:41:53 +00006133 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6134 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00006135 return LHSTy;
6136 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00006137
Chandler Carruth82214a82011-02-18 23:54:50 +00006138 // Emit a better diagnostic if one of the expressions is a null pointer
6139 // constant and the other is not a pointer type. In this case, the user most
6140 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00006141 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00006142 return QualType();
6143
Chris Lattner70d67a92008-01-06 22:42:25 +00006144 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00006145 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00006146 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006147 return QualType();
6148}
6149
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006150/// FindCompositeObjCPointerType - Helper method to find composite type of
6151/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00006152QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006153 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00006154 QualType LHSTy = LHS.get()->getType();
6155 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006156
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006157 // Handle things like Class and struct objc_class*. Here we case the result
6158 // to the pseudo-builtin, because that will be implicitly cast back to the
6159 // redefinition type if an attempt is made to access its fields.
6160 if (LHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006161 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006162 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006163 return LHSTy;
6164 }
6165 if (RHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006166 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006167 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006168 return RHSTy;
6169 }
6170 // And the same for struct objc_object* / id
6171 if (LHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006172 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006173 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006174 return LHSTy;
6175 }
6176 if (RHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006177 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006178 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006179 return RHSTy;
6180 }
6181 // And the same for struct objc_selector* / SEL
6182 if (Context.isObjCSelType(LHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00006183 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006184 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006185 return LHSTy;
6186 }
6187 if (Context.isObjCSelType(RHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00006188 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006189 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006190 return RHSTy;
6191 }
6192 // Check constraints for Objective-C object pointers types.
6193 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006194
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006195 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6196 // Two identical object pointer types are always compatible.
6197 return LHSTy;
6198 }
6199 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
6200 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
6201 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006202
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006203 // If both operands are interfaces and either operand can be
6204 // assigned to the other, use that type as the composite
6205 // type. This allows
6206 // xxx ? (A*) a : (B*) b
6207 // where B is a subclass of A.
6208 //
6209 // Additionally, as for assignment, if either type is 'id'
6210 // allow silent coercion. Finally, if the types are
6211 // incompatible then make sure to use 'id' as the composite
6212 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006213
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006214 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6215 // It could return the composite type.
6216 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6217 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6218 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6219 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6220 } else if ((LHSTy->isObjCQualifiedIdType() ||
6221 RHSTy->isObjCQualifiedIdType()) &&
6222 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6223 // Need to handle "id<xx>" explicitly.
6224 // GCC allows qualified id and any Objective-C type to devolve to
6225 // id. Currently localizing to here until clear this should be
6226 // part of ObjCQualifiedIdTypesAreCompatible.
6227 compositeType = Context.getObjCIdType();
6228 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6229 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006230 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006231 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
6232 ;
6233 else {
6234 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6235 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00006236 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006237 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00006238 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6239 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006240 return incompatTy;
6241 }
6242 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00006243 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
6244 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006245 return compositeType;
6246 }
6247 // Check Objective-C object pointer types and 'void *'
6248 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6249 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6250 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6251 QualType destPointee
6252 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6253 QualType destType = Context.getPointerType(destPointee);
6254 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00006255 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006256 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00006257 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006258 return destType;
6259 }
6260 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6261 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6262 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6263 QualType destPointee
6264 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6265 QualType destType = Context.getPointerType(destPointee);
6266 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00006267 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006268 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00006269 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006270 return destType;
6271 }
6272 return QualType();
6273}
6274
Chandler Carruthf0b60d62011-06-16 01:05:14 +00006275/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006276/// ParenRange in parentheses.
6277static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00006278 const PartialDiagnostic &Note,
6279 SourceRange ParenRange) {
6280 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6281 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6282 EndLoc.isValid()) {
6283 Self.Diag(Loc, Note)
6284 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6285 << FixItHint::CreateInsertion(EndLoc, ")");
6286 } else {
6287 // We can't display the parentheses, so just show the bare note.
6288 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006289 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006290}
6291
6292static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6293 return Opc >= BO_Mul && Opc <= BO_Shr;
6294}
6295
Hans Wennborg2f072b42011-06-09 17:06:51 +00006296/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6297/// expression, either using a built-in or overloaded operator,
6298/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
6299static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6300 Expr **RHS) {
6301 E = E->IgnoreParenImpCasts();
6302 E = E->IgnoreConversionOperator();
6303 E = E->IgnoreParenImpCasts();
6304
6305 // Built-in binary operator.
6306 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6307 if (IsArithmeticOp(OP->getOpcode())) {
6308 *Opcode = OP->getOpcode();
6309 *RHS = OP->getRHS();
6310 return true;
6311 }
6312 }
6313
6314 // Overloaded operator.
6315 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6316 if (Call->getNumArgs() != 2)
6317 return false;
6318
6319 // Make sure this is really a binary operator that is safe to pass into
6320 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6321 OverloadedOperatorKind OO = Call->getOperator();
6322 if (OO < OO_Plus || OO > OO_Arrow)
6323 return false;
6324
6325 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6326 if (IsArithmeticOp(OpKind)) {
6327 *Opcode = OpKind;
6328 *RHS = Call->getArg(1);
6329 return true;
6330 }
6331 }
6332
6333 return false;
6334}
6335
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006336static bool IsLogicOp(BinaryOperatorKind Opc) {
6337 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
6338}
6339
Hans Wennborg2f072b42011-06-09 17:06:51 +00006340/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6341/// or is a logical expression such as (x==y) which has int type, but is
6342/// commonly interpreted as boolean.
6343static bool ExprLooksBoolean(Expr *E) {
6344 E = E->IgnoreParenImpCasts();
6345
6346 if (E->getType()->isBooleanType())
6347 return true;
6348 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6349 return IsLogicOp(OP->getOpcode());
6350 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6351 return OP->getOpcode() == UO_LNot;
6352
6353 return false;
6354}
6355
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006356/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6357/// and binary operator are mixed in a way that suggests the programmer assumed
6358/// the conditional operator has higher precedence, for example:
6359/// "int x = a + someBinaryCondition ? 1 : 2".
6360static void DiagnoseConditionalPrecedence(Sema &Self,
6361 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00006362 Expr *Condition,
6363 Expr *LHS,
6364 Expr *RHS) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00006365 BinaryOperatorKind CondOpcode;
6366 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006367
Chandler Carruth43bc78d2011-06-16 01:05:08 +00006368 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00006369 return;
6370 if (!ExprLooksBoolean(CondRHS))
6371 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006372
Hans Wennborg2f072b42011-06-09 17:06:51 +00006373 // The condition is an arithmetic binary expression, with a right-
6374 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006375
Chandler Carruthf0b60d62011-06-16 01:05:14 +00006376 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00006377 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00006378 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006379
Chandler Carruthf0b60d62011-06-16 01:05:14 +00006380 SuggestParentheses(Self, OpLoc,
6381 Self.PDiag(diag::note_precedence_conditional_silence)
6382 << BinaryOperator::getOpcodeStr(CondOpcode),
6383 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006384
Chandler Carruthf0b60d62011-06-16 01:05:14 +00006385 SuggestParentheses(Self, OpLoc,
6386 Self.PDiag(diag::note_precedence_conditional_first),
6387 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006388}
6389
Steve Narofff69936d2007-09-16 03:34:24 +00006390/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00006391/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00006392ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00006393 SourceLocation ColonLoc,
6394 Expr *CondExpr, Expr *LHSExpr,
6395 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00006396 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6397 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00006398 OpaqueValueExpr *opaqueValue = 0;
6399 Expr *commonExpr = 0;
6400 if (LHSExpr == 0) {
6401 commonExpr = CondExpr;
6402
6403 // We usually want to apply unary conversions *before* saving, except
6404 // in the special case of a C++ l-value conditional.
6405 if (!(getLangOptions().CPlusPlus
6406 && !commonExpr->isTypeDependent()
6407 && commonExpr->getValueKind() == RHSExpr->getValueKind()
6408 && commonExpr->isGLValue()
6409 && commonExpr->isOrdinaryOrBitFieldObject()
6410 && RHSExpr->isOrdinaryOrBitFieldObject()
6411 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00006412 ExprResult commonRes = UsualUnaryConversions(commonExpr);
6413 if (commonRes.isInvalid())
6414 return ExprError();
6415 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00006416 }
6417
6418 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6419 commonExpr->getType(),
6420 commonExpr->getValueKind(),
6421 commonExpr->getObjectKind());
6422 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00006423 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006424
John McCallf89e55a2010-11-18 06:31:45 +00006425 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00006426 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00006427 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
6428 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00006429 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00006430 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6431 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006432 return ExprError();
6433
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006434 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6435 RHS.get());
6436
John McCall56ca35d2011-02-17 10:25:35 +00006437 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00006438 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
6439 LHS.take(), ColonLoc,
6440 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00006441
6442 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00006443 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
6444 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00006445}
6446
John McCalle4be87e2011-01-31 23:13:11 +00006447// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00006448// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00006449// routine is it effectively iqnores the qualifiers on the top level pointee.
6450// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6451// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00006452static Sema::AssignConvertType
6453checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6454 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6455 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006456
Reid Spencer5f016e22007-07-11 17:01:13 +00006457 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00006458 const Type *lhptee, *rhptee;
6459 Qualifiers lhq, rhq;
6460 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
6461 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006462
John McCalle4be87e2011-01-31 23:13:11 +00006463 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006464
6465 // C99 6.5.16.1p1: This following citation is common to constraints
6466 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6467 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00006468 Qualifiers lq;
6469
John McCallf85e1932011-06-15 23:02:42 +00006470 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6471 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6472 lhq.compatiblyIncludesObjCLifetime(rhq)) {
6473 // Ignore lifetime for further calculation.
6474 lhq.removeObjCLifetime();
6475 rhq.removeObjCLifetime();
6476 }
6477
John McCall86c05f32011-02-01 00:10:29 +00006478 if (!lhq.compatiblyIncludes(rhq)) {
6479 // Treat address-space mismatches as fatal. TODO: address subspaces
6480 if (lhq.getAddressSpace() != rhq.getAddressSpace())
6481 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6482
John McCallf85e1932011-06-15 23:02:42 +00006483 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00006484 // and from void*.
John McCallf85e1932011-06-15 23:02:42 +00006485 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
6486 .compatiblyIncludes(
6487 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall22348732011-03-26 02:56:45 +00006488 && (lhptee->isVoidType() || rhptee->isVoidType()))
6489 ; // keep old
6490
John McCallf85e1932011-06-15 23:02:42 +00006491 // Treat lifetime mismatches as fatal.
6492 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6493 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6494
John McCall86c05f32011-02-01 00:10:29 +00006495 // For GCC compatibility, other qualifier mismatches are treated
6496 // as still compatible in C.
6497 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6498 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006499
Mike Stumpeed9cac2009-02-19 03:04:26 +00006500 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6501 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00006502 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006503 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00006504 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00006505 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006506
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006507 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00006508 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00006509 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006510 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006511
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006512 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00006513 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00006514 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006515
6516 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00006517 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00006518 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006519 }
John McCall86c05f32011-02-01 00:10:29 +00006520
Mike Stumpeed9cac2009-02-19 03:04:26 +00006521 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00006522 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00006523 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6524 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006525 // Check if the pointee types are compatible ignoring the sign.
6526 // We explicitly check for char so that we catch "char" vs
6527 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00006528 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00006529 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00006530 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00006531 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006532
Chris Lattner6a2b9262009-10-17 20:33:28 +00006533 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00006534 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00006535 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00006536 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00006537
John McCall86c05f32011-02-01 00:10:29 +00006538 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006539 // Types are compatible ignoring the sign. Qualifier incompatibility
6540 // takes priority over sign incompatibility because the sign
6541 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00006542 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006543 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00006544
John McCalle4be87e2011-01-31 23:13:11 +00006545 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006546 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006547
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006548 // If we are a multi-level pointer, it's possible that our issue is simply
6549 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6550 // the eventual target type is the same and the pointers have the same
6551 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00006552 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006553 do {
John McCall86c05f32011-02-01 00:10:29 +00006554 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6555 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00006556 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006557
John McCall86c05f32011-02-01 00:10:29 +00006558 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00006559 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006560 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006561
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006562 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00006563 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006564 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00006565 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006566}
6567
John McCalle4be87e2011-01-31 23:13:11 +00006568/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00006569/// block pointer types are compatible or whether a block and normal pointer
6570/// are compatible. It is more restrict than comparing two function pointer
6571// types.
John McCalle4be87e2011-01-31 23:13:11 +00006572static Sema::AssignConvertType
6573checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
6574 QualType rhsType) {
6575 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6576 assert(rhsType.isCanonical() && "RHS not canonicalized!");
6577
Steve Naroff1c7d0672008-09-04 15:10:53 +00006578 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006579
Steve Naroff1c7d0672008-09-04 15:10:53 +00006580 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00006581 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
6582 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006583
John McCalle4be87e2011-01-31 23:13:11 +00006584 // In C++, the types have to match exactly.
6585 if (S.getLangOptions().CPlusPlus)
6586 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006587
John McCalle4be87e2011-01-31 23:13:11 +00006588 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006589
Steve Naroff1c7d0672008-09-04 15:10:53 +00006590 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00006591 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6592 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006593
John McCalle4be87e2011-01-31 23:13:11 +00006594 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6595 return Sema::IncompatibleBlockPointer;
6596
Steve Naroff1c7d0672008-09-04 15:10:53 +00006597 return ConvTy;
6598}
6599
John McCalle4be87e2011-01-31 23:13:11 +00006600/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006601/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00006602static Sema::AssignConvertType
6603checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6604 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6605 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6606
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006607 if (lhsType->isObjCBuiltinType()) {
6608 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00006609 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6610 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00006611 return Sema::IncompatiblePointer;
6612 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006613 }
6614 if (rhsType->isObjCBuiltinType()) {
6615 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00006616 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6617 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00006618 return Sema::IncompatiblePointer;
6619 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006620 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006621 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006622 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006623 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006624 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006625
John McCalle4be87e2011-01-31 23:13:11 +00006626 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6627 return Sema::CompatiblePointerDiscardsQualifiers;
6628
6629 if (S.Context.typesAreCompatible(lhsType, rhsType))
6630 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006631 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00006632 return Sema::IncompatibleObjCQualifiedId;
6633 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006634}
6635
John McCall1c23e912010-11-16 02:32:08 +00006636Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00006637Sema::CheckAssignmentConstraints(SourceLocation Loc,
6638 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00006639 // Fake up an opaque expression. We don't actually care about what
6640 // cast operations are required, so if CheckAssignmentConstraints
6641 // adds casts to this they'll be wasted, but fortunately that doesn't
6642 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00006643 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00006644 ExprResult rhsPtr = &rhs;
John McCall1c23e912010-11-16 02:32:08 +00006645 CastKind K = CK_Invalid;
6646
6647 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6648}
6649
Mike Stumpeed9cac2009-02-19 03:04:26 +00006650/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6651/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00006652/// pointers. Here are some objectionable examples that GCC considers warnings:
6653///
6654/// int a, *pint;
6655/// short *pshort;
6656/// struct foo *pfoo;
6657///
6658/// pint = pshort; // warning: assignment from incompatible pointer type
6659/// a = pint; // warning: assignment makes integer from pointer without a cast
6660/// pint = a; // warning: assignment makes pointer from integer without a cast
6661/// pint = pfoo; // warning: assignment from incompatible pointer type
6662///
6663/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00006664/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00006665///
John McCalldaa8e4e2010-11-15 09:13:47 +00006666/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00006667Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006668Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00006669 CastKind &Kind) {
John Wiegley429bb272011-04-08 18:41:53 +00006670 QualType rhsType = rhs.get()->getType();
John McCall1c23e912010-11-16 02:32:08 +00006671
Chris Lattnerfc144e22008-01-04 23:18:45 +00006672 // Get canonical types. We're not formatting these types, just comparing
6673 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00006674 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6675 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006676
John McCallb6cfa242011-01-31 22:28:28 +00006677 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00006678 if (lhsType == rhsType) {
6679 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00006680 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00006681 }
6682
Douglas Gregor9d293df2008-10-28 00:22:11 +00006683 // If the left-hand side is a reference type, then we are in a
6684 // (rare!) case where we've allowed the use of references in C,
6685 // e.g., as a parameter type in a built-in function. In this case,
6686 // just make sure that the type referenced is compatible with the
6687 // right-hand side type. The caller is responsible for adjusting
6688 // lhsType so that the resulting expression does not have reference
6689 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00006690 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006691 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6692 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00006693 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006694 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00006695 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00006696 }
John McCallb6cfa242011-01-31 22:28:28 +00006697
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006698 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6699 // to the same ExtVector type.
6700 if (lhsType->isExtVectorType()) {
6701 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00006702 return Incompatible;
6703 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00006704 // CK_VectorSplat does T -> vector T, so first cast to the
6705 // element type.
6706 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6707 if (elType != rhsType) {
6708 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley429bb272011-04-08 18:41:53 +00006709 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00006710 }
6711 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006712 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006713 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006714 }
Mike Stump1eb44332009-09-09 15:08:12 +00006715
John McCallb6cfa242011-01-31 22:28:28 +00006716 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00006717 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00006718 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00006719 // Allow assignments of an AltiVec vector type to an equivalent GCC
6720 // vector type and vice versa
6721 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6722 Kind = CK_BitCast;
6723 return Compatible;
6724 }
6725
Douglas Gregor255210e2010-08-06 10:14:59 +00006726 // If we are allowing lax vector conversions, and LHS and RHS are both
6727 // vectors, the total size only needs to be the same. This is a bitcast;
6728 // no bits are changed but the result type is different.
6729 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00006730 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00006731 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006732 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00006733 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00006734 }
6735 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006736 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006737
John McCallb6cfa242011-01-31 22:28:28 +00006738 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00006739 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00006740 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00006741 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00006742 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006743 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006744
John McCallb6cfa242011-01-31 22:28:28 +00006745 // Conversions to normal pointers.
6746 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6747 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00006748 if (isa<PointerType>(rhsType)) {
6749 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006750 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006751 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006752
John McCallb6cfa242011-01-31 22:28:28 +00006753 // int -> T*
6754 if (rhsType->isIntegerType()) {
6755 Kind = CK_IntegralToPointer; // FIXME: null?
6756 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006757 }
John McCallb6cfa242011-01-31 22:28:28 +00006758
6759 // C pointers are not compatible with ObjC object pointers,
6760 // with two exceptions:
6761 if (isa<ObjCObjectPointerType>(rhsType)) {
6762 // - conversions to void*
6763 if (lhsPointer->getPointeeType()->isVoidType()) {
6764 Kind = CK_AnyPointerToObjCPointerCast;
6765 return Compatible;
6766 }
6767
6768 // - conversions from 'Class' to the redefinition type
6769 if (rhsType->isObjCClassType() &&
6770 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006771 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006772 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006773 }
Steve Naroffb4406862008-09-29 18:10:17 +00006774
John McCallb6cfa242011-01-31 22:28:28 +00006775 Kind = CK_BitCast;
6776 return IncompatiblePointer;
6777 }
6778
6779 // U^ -> void*
6780 if (rhsType->getAs<BlockPointerType>()) {
6781 if (lhsPointer->getPointeeType()->isVoidType()) {
6782 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006783 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006784 }
Steve Naroffb4406862008-09-29 18:10:17 +00006785 }
John McCallb6cfa242011-01-31 22:28:28 +00006786
Steve Naroff1c7d0672008-09-04 15:10:53 +00006787 return Incompatible;
6788 }
6789
John McCallb6cfa242011-01-31 22:28:28 +00006790 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00006791 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006792 // U^ -> T^
6793 if (rhsType->isBlockPointerType()) {
6794 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00006795 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006796 }
6797
6798 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006799 if (rhsType->isIntegerType()) {
6800 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00006801 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006802 }
6803
John McCallb6cfa242011-01-31 22:28:28 +00006804 // id -> T^
6805 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6806 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006807 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006808 }
Steve Naroffb4406862008-09-29 18:10:17 +00006809
John McCallb6cfa242011-01-31 22:28:28 +00006810 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006811 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00006812 if (RHSPT->getPointeeType()->isVoidType()) {
6813 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006814 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006815 }
John McCalldaa8e4e2010-11-15 09:13:47 +00006816
Chris Lattnerfc144e22008-01-04 23:18:45 +00006817 return Incompatible;
6818 }
6819
John McCallb6cfa242011-01-31 22:28:28 +00006820 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00006821 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006822 // A* -> B*
6823 if (rhsType->isObjCObjectPointerType()) {
6824 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006825 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006826 }
6827
6828 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00006829 if (rhsType->isIntegerType()) {
6830 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00006831 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006832 }
6833
John McCallb6cfa242011-01-31 22:28:28 +00006834 // In general, C pointers are not compatible with ObjC object pointers,
6835 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00006836 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006837 // - conversions from 'void*'
6838 if (rhsType->isVoidPointerType()) {
6839 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006840 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006841 }
6842
6843 // - conversions to 'Class' from its redefinition type
6844 if (lhsType->isObjCClassType() &&
6845 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6846 Kind = CK_BitCast;
6847 return Compatible;
6848 }
6849
6850 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006851 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006852 }
John McCallb6cfa242011-01-31 22:28:28 +00006853
6854 // T^ -> A*
6855 if (rhsType->isBlockPointerType()) {
6856 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00006857 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006858 }
6859
Steve Naroff14108da2009-07-10 23:34:53 +00006860 return Incompatible;
6861 }
John McCallb6cfa242011-01-31 22:28:28 +00006862
6863 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00006864 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006865 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006866 if (lhsType == Context.BoolTy) {
6867 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006868 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006869 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006870
John McCallb6cfa242011-01-31 22:28:28 +00006871 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006872 if (lhsType->isIntegerType()) {
6873 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006874 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006875 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006876
Chris Lattnerfc144e22008-01-04 23:18:45 +00006877 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00006878 }
John McCallb6cfa242011-01-31 22:28:28 +00006879
6880 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00006881 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006882 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006883 if (lhsType == Context.BoolTy) {
6884 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00006885 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006886 }
Steve Naroff14108da2009-07-10 23:34:53 +00006887
John McCallb6cfa242011-01-31 22:28:28 +00006888 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006889 if (lhsType->isIntegerType()) {
6890 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00006891 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006892 }
6893
Steve Naroff14108da2009-07-10 23:34:53 +00006894 return Incompatible;
6895 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006896
John McCallb6cfa242011-01-31 22:28:28 +00006897 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00006898 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006899 if (Context.typesAreCompatible(lhsType, rhsType)) {
6900 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00006901 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006902 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006903 }
John McCallb6cfa242011-01-31 22:28:28 +00006904
Reid Spencer5f016e22007-07-11 17:01:13 +00006905 return Incompatible;
6906}
6907
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006908/// \brief Constructs a transparent union from an expression that is
6909/// used to initialize the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00006910static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006911 QualType UnionType, FieldDecl *Field) {
6912 // Build an initializer list that designates the appropriate member
6913 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00006914 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00006915 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00006916 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006917 SourceLocation());
6918 Initializer->setType(UnionType);
6919 Initializer->setInitializedFieldInUnion(Field);
6920
6921 // Build a compound literal constructing a value of the transparent
6922 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00006923 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00006924 EResult = S.Owned(
6925 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6926 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006927}
6928
6929Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006930Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
6931 QualType FromType = rExpr.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006932
Mike Stump1eb44332009-09-09 15:08:12 +00006933 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006934 // transparent_union GCC extension.
6935 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006936 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006937 return Incompatible;
6938
6939 // The field to initialize within the transparent union.
6940 RecordDecl *UD = UT->getDecl();
6941 FieldDecl *InitField = 0;
6942 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006943 for (RecordDecl::field_iterator it = UD->field_begin(),
6944 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006945 it != itend; ++it) {
6946 if (it->getType()->isPointerType()) {
6947 // If the transparent union contains a pointer type, we allow:
6948 // 1) void pointer
6949 // 2) null pointer constant
6950 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00006951 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006952 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006953 InitField = *it;
6954 break;
6955 }
Mike Stump1eb44332009-09-09 15:08:12 +00006956
John Wiegley429bb272011-04-08 18:41:53 +00006957 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006958 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006959 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006960 InitField = *it;
6961 break;
6962 }
6963 }
6964
John McCalldaa8e4e2010-11-15 09:13:47 +00006965 CastKind Kind = CK_Invalid;
John Wiegley429bb272011-04-08 18:41:53 +00006966 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006967 == Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +00006968 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006969 InitField = *it;
6970 break;
6971 }
6972 }
6973
6974 if (!InitField)
6975 return Incompatible;
6976
John Wiegley429bb272011-04-08 18:41:53 +00006977 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006978 return Compatible;
6979}
6980
Chris Lattner5cf216b2008-01-04 18:04:52 +00006981Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006982Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00006983 if (getLangOptions().CPlusPlus) {
6984 if (!lhsType->isRecordType()) {
6985 // C++ 5.17p3: If the left operand is not of class type, the
6986 // expression is implicitly converted (C++ 4) to the
6987 // cv-unqualified type of the left operand.
John Wiegley429bb272011-04-08 18:41:53 +00006988 ExprResult Res = PerformImplicitConversion(rExpr.get(),
6989 lhsType.getUnqualifiedType(),
6990 AA_Assigning);
6991 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00006992 return Incompatible;
John Wiegley429bb272011-04-08 18:41:53 +00006993 rExpr = move(Res);
Chris Lattner2c4463f2009-04-12 09:02:39 +00006994 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00006995 }
6996
6997 // FIXME: Currently, we fall through and treat C++ classes like C
6998 // structures.
John McCallf6a16482010-12-04 03:47:34 +00006999 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00007000
Steve Naroff529a4ad2007-11-27 17:58:44 +00007001 // C99 6.5.16.1p1: the left operand is a pointer and the right is
7002 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00007003 if ((lhsType->isPointerType() ||
7004 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00007005 lhsType->isBlockPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00007006 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007007 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00007008 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00007009 return Compatible;
7010 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007011
Chris Lattner943140e2007-10-16 02:55:40 +00007012 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00007013 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00007014 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00007015 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00007016 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00007017 // Suppress this for references: C++ 8.5.3p5.
John Wiegley429bb272011-04-08 18:41:53 +00007018 if (!lhsType->isReferenceType()) {
7019 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
7020 if (rExpr.isInvalid())
7021 return Incompatible;
7022 }
Steve Narofff1120de2007-08-24 22:33:52 +00007023
John McCalldaa8e4e2010-11-15 09:13:47 +00007024 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007025 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00007026 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007027
Steve Narofff1120de2007-08-24 22:33:52 +00007028 // C99 6.5.16.1p2: The value of the right operand is converted to the
7029 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00007030 // CheckAssignmentConstraints allows the left-hand side to be a reference,
7031 // so that we can use references in built-in functions even in C.
7032 // The getNonReferenceType() call makes sure that the resulting expression
7033 // does not have reference type.
John Wiegley429bb272011-04-08 18:41:53 +00007034 if (result != Incompatible && rExpr.get()->getType() != lhsType)
7035 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00007036 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00007037}
7038
John Wiegley429bb272011-04-08 18:41:53 +00007039QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007040 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley429bb272011-04-08 18:41:53 +00007041 << lex.get()->getType() << rex.get()->getType()
7042 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00007043 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007044}
7045
John Wiegley429bb272011-04-08 18:41:53 +00007046QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00007047 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00007048 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00007049 QualType lhsType =
John Wiegley429bb272011-04-08 18:41:53 +00007050 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattnerb77792e2008-07-26 22:17:49 +00007051 QualType rhsType =
John Wiegley429bb272011-04-08 18:41:53 +00007052 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007053
Nate Begemanbe2341d2008-07-14 18:02:46 +00007054 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00007055 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00007056 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00007057
Nate Begemanbe2341d2008-07-14 18:02:46 +00007058 // Handle the case of a vector & extvector type of the same size and element
7059 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00007060 if (getLangOptions().LaxVectorConversions) {
John McCall183700f2009-09-21 23:43:11 +00007061 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth629f9e42010-08-30 07:36:24 +00007062 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007063 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00007064 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregor26bcf672010-05-19 03:21:00 +00007065 if (lhsType->isExtVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00007066 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00007067 return lhsType;
7068 }
7069
John Wiegley429bb272011-04-08 18:41:53 +00007070 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00007071 return rhsType;
Eric Christophere84f9eb2010-08-26 00:42:16 +00007072 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
7073 // If we are allowing lax vector conversions, and LHS and RHS are both
7074 // vectors, the total size only needs to be the same. This is a
7075 // bitcast; no bits are changed but the result type is different.
John Wiegley429bb272011-04-08 18:41:53 +00007076 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Eric Christophere84f9eb2010-08-26 00:42:16 +00007077 return lhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00007078 }
Eric Christophere84f9eb2010-08-26 00:42:16 +00007079 }
Chandler Carruth629f9e42010-08-30 07:36:24 +00007080 }
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00007081 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007082
Douglas Gregor255210e2010-08-06 10:14:59 +00007083 // Handle the case of equivalent AltiVec and GCC vector types
7084 if (lhsType->isVectorType() && rhsType->isVectorType() &&
7085 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John Wiegley429bb272011-04-08 18:41:53 +00007086 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00007087 return rhsType;
7088 }
7089
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00007090 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
7091 // swap back (so that we don't reverse the inputs to a subtract, for instance.
7092 bool swapped = false;
7093 if (rhsType->isExtVectorType()) {
7094 swapped = true;
7095 std::swap(rex, lex);
7096 std::swap(rhsType, lhsType);
7097 }
Mike Stump1eb44332009-09-09 15:08:12 +00007098
Nate Begemandde25982009-06-28 19:12:57 +00007099 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00007100 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00007101 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00007102 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00007103 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
7104 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00007105 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00007106 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00007107 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00007108 if (swapped) std::swap(rex, lex);
7109 return lhsType;
7110 }
7111 }
7112 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
7113 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00007114 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
7115 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00007116 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00007117 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00007118 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00007119 if (swapped) std::swap(rex, lex);
7120 return lhsType;
7121 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00007122 }
7123 }
Mike Stump1eb44332009-09-09 15:08:12 +00007124
Nate Begemandde25982009-06-28 19:12:57 +00007125 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007126 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley429bb272011-04-08 18:41:53 +00007127 << lex.get()->getType() << rex.get()->getType()
7128 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007129 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00007130}
7131
Chris Lattner7ef655a2010-01-12 21:23:57 +00007132QualType Sema::CheckMultiplyDivideOperands(
John Wiegley429bb272011-04-08 18:41:53 +00007133 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
7134 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007135 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007136
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007137 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00007138 if (lex.isInvalid() || rex.isInvalid())
7139 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007140
John Wiegley429bb272011-04-08 18:41:53 +00007141 if (!lex.get()->getType()->isArithmeticType() ||
7142 !rex.get()->getType()->isArithmeticType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00007143 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007144
Chris Lattner7ef655a2010-01-12 21:23:57 +00007145 // Check for division by zero.
7146 if (isDiv &&
John Wiegley429bb272011-04-08 18:41:53 +00007147 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
7148 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
7149 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007150
Chris Lattner7ef655a2010-01-12 21:23:57 +00007151 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00007152}
7153
Chris Lattner7ef655a2010-01-12 21:23:57 +00007154QualType Sema::CheckRemainderOperands(
John Wiegley429bb272011-04-08 18:41:53 +00007155 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7156 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7157 if (lex.get()->getType()->hasIntegerRepresentation() &&
7158 rex.get()->getType()->hasIntegerRepresentation())
Daniel Dunbar523aa602009-01-05 22:55:36 +00007159 return CheckVectorOperands(Loc, lex, rex);
7160 return InvalidOperands(Loc, lex, rex);
7161 }
Steve Naroff90045e82007-07-13 23:32:42 +00007162
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007163 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00007164 if (lex.isInvalid() || rex.isInvalid())
7165 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007166
John Wiegley429bb272011-04-08 18:41:53 +00007167 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00007168 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007169
Chris Lattner7ef655a2010-01-12 21:23:57 +00007170 // Check for remainder by zero.
John Wiegley429bb272011-04-08 18:41:53 +00007171 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
7172 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
7173 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007174
Chris Lattner7ef655a2010-01-12 21:23:57 +00007175 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00007176}
7177
Chris Lattner7ef655a2010-01-12 21:23:57 +00007178QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00007179 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
7180 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00007181 QualType compType = CheckVectorOperands(Loc, lex, rex);
7182 if (CompLHSTy) *CompLHSTy = compType;
7183 return compType;
7184 }
Steve Naroff49b45262007-07-13 16:58:59 +00007185
Eli Friedmanab3a8522009-03-28 01:22:36 +00007186 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00007187 if (lex.isInvalid() || rex.isInvalid())
7188 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00007189
Reid Spencer5f016e22007-07-11 17:01:13 +00007190 // handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00007191 if (lex.get()->getType()->isArithmeticType() &&
7192 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00007193 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007194 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00007195 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007196
Eli Friedmand72d16e2008-05-18 18:08:51 +00007197 // Put any potential pointer into PExp
John Wiegley429bb272011-04-08 18:41:53 +00007198 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007199 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00007200 std::swap(PExp, IExp);
7201
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007202 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00007203
Eli Friedmand72d16e2008-05-18 18:08:51 +00007204 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00007205 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00007206
Chris Lattnerb5f15622009-04-24 23:50:08 +00007207 // Check for arithmetic on pointers to incomplete types.
7208 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00007209 if (getLangOptions().CPlusPlus) {
7210 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00007211 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007212 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00007213 }
Douglas Gregore7450f52009-03-24 19:52:54 +00007214
7215 // GNU extension: arithmetic on pointer to void
7216 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00007217 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00007218 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00007219 if (getLangOptions().CPlusPlus) {
7220 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00007221 << lex.get()->getType() << lex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007222 return QualType();
7223 }
7224
7225 // GNU extension: arithmetic on pointer to function
7226 Diag(Loc, diag::ext_gnu_ptr_func_arith)
John Wiegley429bb272011-04-08 18:41:53 +00007227 << lex.get()->getType() << lex.get()->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00007228 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00007229 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00007230 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00007231 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00007232 PExp->getType()->isObjCObjectPointerType()) &&
7233 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00007234 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
7235 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00007236 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00007237 return QualType();
7238 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00007239 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00007240 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00007241 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
7242 << PointeeTy << PExp->getSourceRange();
7243 return QualType();
7244 }
Mike Stump1eb44332009-09-09 15:08:12 +00007245
Eli Friedmanab3a8522009-03-28 01:22:36 +00007246 if (CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00007247 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman04e83572009-08-20 04:21:42 +00007248 if (LHSTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +00007249 LHSTy = lex.get()->getType();
Eli Friedman04e83572009-08-20 04:21:42 +00007250 if (LHSTy->isPromotableIntegerType())
7251 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00007252 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00007253 *CompLHSTy = LHSTy;
7254 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00007255 return PExp->getType();
7256 }
7257 }
7258
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007259 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007260}
7261
Chris Lattnereca7be62008-04-07 05:30:13 +00007262// C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00007263QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00007264 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00007265 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00007266 QualType compType = CheckVectorOperands(Loc, lex, rex);
7267 if (CompLHSTy) *CompLHSTy = compType;
7268 return compType;
7269 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007270
Eli Friedmanab3a8522009-03-28 01:22:36 +00007271 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00007272 if (lex.isInvalid() || rex.isInvalid())
7273 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007274
Chris Lattner6e4ab612007-12-09 21:53:25 +00007275 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007276
Chris Lattner6e4ab612007-12-09 21:53:25 +00007277 // Handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00007278 if (lex.get()->getType()->isArithmeticType() &&
7279 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00007280 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007281 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00007282 }
Mike Stump1eb44332009-09-09 15:08:12 +00007283
Chris Lattner6e4ab612007-12-09 21:53:25 +00007284 // Either ptr - int or ptr - ptr.
John Wiegley429bb272011-04-08 18:41:53 +00007285 if (lex.get()->getType()->isAnyPointerType()) {
7286 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007287
Douglas Gregore7450f52009-03-24 19:52:54 +00007288 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00007289
Douglas Gregore7450f52009-03-24 19:52:54 +00007290 bool ComplainAboutVoid = false;
7291 Expr *ComplainAboutFunc = 0;
7292 if (lpointee->isVoidType()) {
7293 if (getLangOptions().CPlusPlus) {
7294 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00007295 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007296 return QualType();
7297 }
7298
7299 // GNU C extension: arithmetic on pointer to void
7300 ComplainAboutVoid = true;
7301 } else if (lpointee->isFunctionType()) {
7302 if (getLangOptions().CPlusPlus) {
7303 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00007304 << lex.get()->getType() << lex.get()->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007305 return QualType();
7306 }
Douglas Gregore7450f52009-03-24 19:52:54 +00007307
7308 // GNU C extension: arithmetic on pointer to function
John Wiegley429bb272011-04-08 18:41:53 +00007309 ComplainAboutFunc = lex.get();
Douglas Gregore7450f52009-03-24 19:52:54 +00007310 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00007311 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00007312 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley429bb272011-04-08 18:41:53 +00007313 << lex.get()->getSourceRange()
7314 << lex.get()->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00007315 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007316
Chris Lattnerb5f15622009-04-24 23:50:08 +00007317 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00007318 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00007319 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley429bb272011-04-08 18:41:53 +00007320 << lpointee << lex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00007321 return QualType();
7322 }
Mike Stump1eb44332009-09-09 15:08:12 +00007323
Chris Lattner6e4ab612007-12-09 21:53:25 +00007324 // The result type of a pointer-int computation is the pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00007325 if (rex.get()->getType()->isIntegerType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00007326 if (ComplainAboutVoid)
7327 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00007328 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007329 if (ComplainAboutFunc)
7330 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00007331 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00007332 << ComplainAboutFunc->getSourceRange();
7333
John Wiegley429bb272011-04-08 18:41:53 +00007334 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
7335 return lex.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00007336 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007337
Chris Lattner6e4ab612007-12-09 21:53:25 +00007338 // Handle pointer-pointer subtractions.
John Wiegley429bb272011-04-08 18:41:53 +00007339 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00007340 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007341
Douglas Gregore7450f52009-03-24 19:52:54 +00007342 // RHS must be a completely-type object type.
7343 // Handle the GNU void* extension.
7344 if (rpointee->isVoidType()) {
7345 if (getLangOptions().CPlusPlus) {
7346 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00007347 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007348 return QualType();
7349 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007350
Douglas Gregore7450f52009-03-24 19:52:54 +00007351 ComplainAboutVoid = true;
7352 } else if (rpointee->isFunctionType()) {
7353 if (getLangOptions().CPlusPlus) {
7354 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00007355 << rex.get()->getType() << rex.get()->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007356 return QualType();
7357 }
Douglas Gregore7450f52009-03-24 19:52:54 +00007358
7359 // GNU extension: arithmetic on pointer to function
7360 if (!ComplainAboutFunc)
John Wiegley429bb272011-04-08 18:41:53 +00007361 ComplainAboutFunc = rex.get();
Douglas Gregore7450f52009-03-24 19:52:54 +00007362 } else if (!rpointee->isDependentType() &&
7363 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00007364 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley429bb272011-04-08 18:41:53 +00007365 << rex.get()->getSourceRange()
7366 << rex.get()->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00007367 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007368
Eli Friedman88d936b2009-05-16 13:54:38 +00007369 if (getLangOptions().CPlusPlus) {
7370 // Pointee types must be the same: C++ [expr.add]
7371 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7372 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00007373 << lex.get()->getType() << rex.get()->getType()
7374 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00007375 return QualType();
7376 }
7377 } else {
7378 // Pointee types must be compatible C99 6.5.6p3
7379 if (!Context.typesAreCompatible(
7380 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7381 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7382 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00007383 << lex.get()->getType() << rex.get()->getType()
7384 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00007385 return QualType();
7386 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00007387 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007388
Douglas Gregore7450f52009-03-24 19:52:54 +00007389 if (ComplainAboutVoid)
7390 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00007391 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007392 if (ComplainAboutFunc)
7393 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00007394 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00007395 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00007396
John Wiegley429bb272011-04-08 18:41:53 +00007397 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007398 return Context.getPointerDiffType();
7399 }
7400 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007401
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007402 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007403}
7404
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007405static bool isScopedEnumerationType(QualType T) {
7406 if (const EnumType *ET = dyn_cast<EnumType>(T))
7407 return ET->getDecl()->isScoped();
7408 return false;
7409}
7410
John Wiegley429bb272011-04-08 18:41:53 +00007411static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth21206d52011-02-23 23:34:11 +00007412 SourceLocation Loc, unsigned Opc,
7413 QualType LHSTy) {
7414 llvm::APSInt Right;
7415 // Check right/shifter operand
John Wiegley429bb272011-04-08 18:41:53 +00007416 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00007417 return;
7418
7419 if (Right.isNegative()) {
John Wiegley429bb272011-04-08 18:41:53 +00007420 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00007421 S.PDiag(diag::warn_shift_negative)
John Wiegley429bb272011-04-08 18:41:53 +00007422 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00007423 return;
7424 }
7425 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley429bb272011-04-08 18:41:53 +00007426 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00007427 if (Right.uge(LeftBits)) {
John Wiegley429bb272011-04-08 18:41:53 +00007428 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00007429 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley429bb272011-04-08 18:41:53 +00007430 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00007431 return;
7432 }
7433 if (Opc != BO_Shl)
7434 return;
7435
7436 // When left shifting an ICE which is signed, we can check for overflow which
7437 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7438 // integers have defined behavior modulo one more than the maximum value
7439 // representable in the result type, so never warn for those.
7440 llvm::APSInt Left;
John Wiegley429bb272011-04-08 18:41:53 +00007441 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth21206d52011-02-23 23:34:11 +00007442 LHSTy->hasUnsignedIntegerRepresentation())
7443 return;
7444 llvm::APInt ResultBits =
7445 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7446 if (LeftBits.uge(ResultBits))
7447 return;
7448 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7449 Result = Result.shl(Right);
7450
Ted Kremenekfa821382011-06-15 00:54:52 +00007451 // Print the bit representation of the signed integer as an unsigned
7452 // hexadecimal number.
7453 llvm::SmallString<40> HexResult;
7454 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7455
Chandler Carruth21206d52011-02-23 23:34:11 +00007456 // If we are only missing a sign bit, this is less likely to result in actual
7457 // bugs -- if the result is cast back to an unsigned type, it will have the
7458 // expected value. Thus we place this behind a different warning that can be
7459 // turned off separately if needed.
7460 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00007461 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7462 << HexResult.str() << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00007463 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00007464 return;
7465 }
7466
7467 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenekfa821382011-06-15 00:54:52 +00007468 << HexResult.str() << Result.getMinSignedBits() << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00007469 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00007470}
7471
Chris Lattnereca7be62008-04-07 05:30:13 +00007472// C99 6.5.7
John Wiegley429bb272011-04-08 18:41:53 +00007473QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth21206d52011-02-23 23:34:11 +00007474 unsigned Opc, bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00007475 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley429bb272011-04-08 18:41:53 +00007476 if (!lex.get()->getType()->hasIntegerRepresentation() ||
7477 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007478 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007479
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007480 // C++0x: Don't allow scoped enums. FIXME: Use something better than
7481 // hasIntegerRepresentation() above instead of this.
John Wiegley429bb272011-04-08 18:41:53 +00007482 if (isScopedEnumerationType(lex.get()->getType()) ||
7483 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007484 return InvalidOperands(Loc, lex, rex);
7485 }
7486
Nate Begeman2207d792009-10-25 02:26:48 +00007487 // Vector shifts promote their scalar inputs to vector type.
John Wiegley429bb272011-04-08 18:41:53 +00007488 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Nate Begeman2207d792009-10-25 02:26:48 +00007489 return CheckVectorOperands(Loc, lex, rex);
7490
Chris Lattnerca5eede2007-12-12 05:47:28 +00007491 // Shifts don't perform usual arithmetic conversions, they just do integer
7492 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00007493
John McCall1bc80af2010-12-16 19:28:59 +00007494 // For the LHS, do usual unary conversions, but then reset them away
7495 // if this is a compound assignment.
John Wiegley429bb272011-04-08 18:41:53 +00007496 ExprResult old_lex = lex;
7497 lex = UsualUnaryConversions(lex.take());
7498 if (lex.isInvalid())
7499 return QualType();
7500 QualType LHSTy = lex.get()->getType();
John McCall1bc80af2010-12-16 19:28:59 +00007501 if (isCompAssign) lex = old_lex;
7502
7503 // The RHS is simpler.
John Wiegley429bb272011-04-08 18:41:53 +00007504 rex = UsualUnaryConversions(rex.take());
7505 if (rex.isInvalid())
7506 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007507
Ryan Flynnd0439682009-08-07 16:20:20 +00007508 // Sanity-check shift operands
Chandler Carruth21206d52011-02-23 23:34:11 +00007509 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnd0439682009-08-07 16:20:20 +00007510
Chris Lattnerca5eede2007-12-12 05:47:28 +00007511 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00007512 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007513}
7514
Chandler Carruth99919472010-07-10 12:30:03 +00007515static bool IsWithinTemplateSpecialization(Decl *D) {
7516 if (DeclContext *DC = D->getDeclContext()) {
7517 if (isa<ClassTemplateSpecializationDecl>(DC))
7518 return true;
7519 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7520 return FD->isFunctionTemplateSpecialization();
7521 }
7522 return false;
7523}
7524
Douglas Gregor0c6db942009-05-04 06:07:12 +00007525// C99 6.5.8, C++ [expr.rel]
John Wiegley429bb272011-04-08 18:41:53 +00007526QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00007527 unsigned OpaqueOpc, bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00007528 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00007529
Chris Lattner02dd4b12009-12-05 05:40:13 +00007530 // Handle vector comparisons separately.
John Wiegley429bb272011-04-08 18:41:53 +00007531 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007532 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007533
John Wiegley429bb272011-04-08 18:41:53 +00007534 QualType lType = lex.get()->getType();
7535 QualType rType = rex.get()->getType();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007536
John Wiegley429bb272011-04-08 18:41:53 +00007537 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
7538 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00007539 QualType LHSStrippedType = LHSStripped->getType();
7540 QualType RHSStrippedType = RHSStripped->getType();
7541
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007542
7543
Chandler Carruth543cb652011-02-17 08:37:06 +00007544 // Two different enums will raise a warning when compared.
7545 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
7546 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
7547 if (LHSEnumType->getDecl()->getIdentifier() &&
7548 RHSEnumType->getDecl()->getIdentifier() &&
7549 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
7550 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7551 << LHSStrippedType << RHSStrippedType
John Wiegley429bb272011-04-08 18:41:53 +00007552 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth543cb652011-02-17 08:37:06 +00007553 }
7554 }
7555 }
7556
Douglas Gregor8eee1192010-06-22 22:12:46 +00007557 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00007558 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley429bb272011-04-08 18:41:53 +00007559 !lex.get()->getLocStart().isMacroID() &&
7560 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00007561 // For non-floating point types, check for self-comparisons of the form
7562 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7563 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00007564 //
7565 // NOTE: Don't warn about comparison expressions resulting from macro
7566 // expansion. Also don't warn about comparisons which are only self
7567 // comparisons within a template specialization. The warnings should catch
7568 // obvious cases in the definition of the template anyways. The idea is to
7569 // warn when the typed comparison operator will always evaluate to the same
7570 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00007571 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00007572 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00007573 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00007574 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00007575 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007576 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00007577 << (Opc == BO_EQ
7578 || Opc == BO_LE
7579 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00007580 } else if (lType->isArrayType() && rType->isArrayType() &&
7581 !DRL->getDecl()->getType()->isReferenceType() &&
7582 !DRR->getDecl()->getType()->isReferenceType()) {
7583 // what is it always going to eval to?
7584 char always_evals_to;
7585 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007586 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007587 always_evals_to = 0; // false
7588 break;
John McCall2de56d12010-08-25 11:45:40 +00007589 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007590 always_evals_to = 1; // true
7591 break;
7592 default:
7593 // best we can say is 'a constant'
7594 always_evals_to = 2; // e.g. array1 <= array2
7595 break;
7596 }
Ted Kremenek351ba912011-02-23 01:52:04 +00007597 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007598 << 1 // array
7599 << always_evals_to);
7600 }
7601 }
Chandler Carruth99919472010-07-10 12:30:03 +00007602 }
Mike Stump1eb44332009-09-09 15:08:12 +00007603
Chris Lattner55660a72009-03-08 19:39:53 +00007604 if (isa<CastExpr>(LHSStripped))
7605 LHSStripped = LHSStripped->IgnoreParenCasts();
7606 if (isa<CastExpr>(RHSStripped))
7607 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00007608
Chris Lattner55660a72009-03-08 19:39:53 +00007609 // Warn about comparisons against a string constant (unless the other
7610 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00007611 Expr *literalString = 0;
7612 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00007613 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007614 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007615 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00007616 literalString = lex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007617 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007618 } else if ((isa<StringLiteral>(RHSStripped) ||
7619 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007620 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007621 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00007622 literalString = rex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007623 literalStringStripped = RHSStripped;
7624 }
7625
7626 if (literalString) {
7627 std::string resultComparison;
7628 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007629 case BO_LT: resultComparison = ") < 0"; break;
7630 case BO_GT: resultComparison = ") > 0"; break;
7631 case BO_LE: resultComparison = ") <= 0"; break;
7632 case BO_GE: resultComparison = ") >= 0"; break;
7633 case BO_EQ: resultComparison = ") == 0"; break;
7634 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00007635 default: assert(false && "Invalid comparison operator");
7636 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007637
Ted Kremenek351ba912011-02-23 01:52:04 +00007638 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00007639 PDiag(diag::warn_stringcompare)
7640 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00007641 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00007642 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00007643 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007644
Douglas Gregord64fdd02010-06-08 19:50:34 +00007645 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley429bb272011-04-08 18:41:53 +00007646 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00007647 UsualArithmeticConversions(lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00007648 if (lex.isInvalid() || rex.isInvalid())
7649 return QualType();
7650 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00007651 else {
John Wiegley429bb272011-04-08 18:41:53 +00007652 lex = UsualUnaryConversions(lex.take());
7653 if (lex.isInvalid())
7654 return QualType();
7655
7656 rex = UsualUnaryConversions(rex.take());
7657 if (rex.isInvalid())
7658 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007659 }
7660
John Wiegley429bb272011-04-08 18:41:53 +00007661 lType = lex.get()->getType();
7662 rType = rex.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007663
Douglas Gregor447b69e2008-11-19 03:25:36 +00007664 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007665 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00007666
Chris Lattnera5937dd2007-08-26 01:18:55 +00007667 if (isRelational) {
7668 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007669 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007670 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007671 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007672 if (lType->hasFloatingRepresentation())
John Wiegley429bb272011-04-08 18:41:53 +00007673 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007674
Chris Lattnera5937dd2007-08-26 01:18:55 +00007675 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007676 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007677 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007678
John Wiegley429bb272011-04-08 18:41:53 +00007679 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007680 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00007681 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007682 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007683
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007684 // All of the following pointer-related warnings are GCC extensions, except
7685 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00007686 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007687 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00007688 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00007689 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00007690 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007691
Douglas Gregor0c6db942009-05-04 06:07:12 +00007692 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007693 if (LCanPointeeTy == RCanPointeeTy)
7694 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007695 if (!isRelational &&
7696 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7697 // Valid unless comparison between non-null pointer and function pointer
7698 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007699 // In a SFINAE context, we treat this as a hard error to maintain
7700 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007701 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7702 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007703 Diag(Loc,
7704 isSFINAEContext()?
7705 diag::err_typecheck_comparison_of_fptr_to_void
7706 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley429bb272011-04-08 18:41:53 +00007707 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007708
7709 if (isSFINAEContext())
7710 return QualType();
7711
John Wiegley429bb272011-04-08 18:41:53 +00007712 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007713 return ResultTy;
7714 }
7715 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007716
Douglas Gregor0c6db942009-05-04 06:07:12 +00007717 // C++ [expr.rel]p2:
7718 // [...] Pointer conversions (4.10) and qualification
7719 // conversions (4.4) are performed on pointer operands (or on
7720 // a pointer operand and a null pointer constant) to bring
7721 // them to their composite pointer type. [...]
7722 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00007723 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00007724 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007725 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00007726 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007727 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00007728 if (T.isNull()) {
7729 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007730 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00007731 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007732 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007733 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007734 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007735 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00007736 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00007737 }
7738
John Wiegley429bb272011-04-08 18:41:53 +00007739 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7740 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00007741 return ResultTy;
7742 }
Eli Friedman3075e762009-08-23 00:27:47 +00007743 // C99 6.5.9p2 and C99 6.5.8p2
7744 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7745 RCanPointeeTy.getUnqualifiedType())) {
7746 // Valid unless a relational comparison of function pointers
7747 if (isRelational && LCanPointeeTy->isFunctionType()) {
7748 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007749 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007750 }
7751 } else if (!isRelational &&
7752 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7753 // Valid unless comparison between non-null pointer and function pointer
7754 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7755 && !LHSIsNull && !RHSIsNull) {
7756 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley429bb272011-04-08 18:41:53 +00007757 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007758 }
7759 } else {
7760 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007761 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007762 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007763 }
John McCall34d6f932011-03-11 04:25:25 +00007764 if (LCanPointeeTy != RCanPointeeTy) {
7765 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007766 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007767 else
John Wiegley429bb272011-04-08 18:41:53 +00007768 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007769 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007770 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007771 }
Mike Stump1eb44332009-09-09 15:08:12 +00007772
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007773 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007774 // Comparison of nullptr_t with itself.
7775 if (lType->isNullPtrType() && rType->isNullPtrType())
7776 return ResultTy;
7777
Mike Stump1eb44332009-09-09 15:08:12 +00007778 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007779 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007780 if (RHSIsNull &&
Douglas Gregor17e37c72011-06-01 15:12:24 +00007781 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor16cd4b72011-06-16 18:52:05 +00007782 (!isRelational &&
7783 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley429bb272011-04-08 18:41:53 +00007784 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregor443c2122010-08-07 13:36:37 +00007785 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007786 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007787 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007788 return ResultTy;
7789 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007790 if (LHSIsNull &&
Douglas Gregor17e37c72011-06-01 15:12:24 +00007791 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor16cd4b72011-06-16 18:52:05 +00007792 (!isRelational &&
7793 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley429bb272011-04-08 18:41:53 +00007794 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregor443c2122010-08-07 13:36:37 +00007795 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007796 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007797 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007798 return ResultTy;
7799 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007800
7801 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00007802 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00007803 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7804 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00007805 // In addition, pointers to members can be compared, or a pointer to
7806 // member and a null pointer constant. Pointer to member conversions
7807 // (4.11) and qualification conversions (4.4) are performed to bring
7808 // them to a common type. If one operand is a null pointer constant,
7809 // the common type is the type of the other operand. Otherwise, the
7810 // common type is a pointer to member type similar (4.4) to the type
7811 // of one of the operands, with a cv-qualification signature (4.4)
7812 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00007813 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007814 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00007815 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007816 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00007817 if (T.isNull()) {
7818 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007819 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00007820 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007821 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007822 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007823 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007824 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00007825 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00007826 }
Mike Stump1eb44332009-09-09 15:08:12 +00007827
John Wiegley429bb272011-04-08 18:41:53 +00007828 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7829 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00007830 return ResultTy;
7831 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007832
7833 // Handle scoped enumeration types specifically, since they don't promote
7834 // to integers.
John Wiegley429bb272011-04-08 18:41:53 +00007835 if (lex.get()->getType()->isEnumeralType() &&
7836 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007837 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007838 }
Mike Stump1eb44332009-09-09 15:08:12 +00007839
Steve Naroff1c7d0672008-09-04 15:10:53 +00007840 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007841 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00007842 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7843 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007844
Steve Naroff1c7d0672008-09-04 15:10:53 +00007845 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007846 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007847 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley429bb272011-04-08 18:41:53 +00007848 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007849 }
John Wiegley429bb272011-04-08 18:41:53 +00007850 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007851 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007852 }
John Wiegley429bb272011-04-08 18:41:53 +00007853
Steve Naroff59f53942008-09-28 01:11:11 +00007854 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007855 if (!isRelational
7856 && ((lType->isBlockPointerType() && rType->isPointerType())
7857 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007858 if (!LHSIsNull && !RHSIsNull) {
John McCall34d6f932011-03-11 04:25:25 +00007859 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007860 ->getPointeeType()->isVoidType())
John McCall34d6f932011-03-11 04:25:25 +00007861 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007862 ->getPointeeType()->isVoidType())))
7863 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley429bb272011-04-08 18:41:53 +00007864 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007865 }
John McCall34d6f932011-03-11 04:25:25 +00007866 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007867 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007868 else
John Wiegley429bb272011-04-08 18:41:53 +00007869 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007870 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007871 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007872
John McCall34d6f932011-03-11 04:25:25 +00007873 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7874 const PointerType *LPT = lType->getAs<PointerType>();
7875 const PointerType *RPT = rType->getAs<PointerType>();
7876 if (LPT || RPT) {
7877 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7878 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007879
Steve Naroffa8069f12008-11-17 19:49:16 +00007880 if (!LPtrToVoid && !RPtrToVoid &&
7881 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007882 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007883 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00007884 }
John McCall34d6f932011-03-11 04:25:25 +00007885 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007886 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007887 else
John Wiegley429bb272011-04-08 18:41:53 +00007888 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007889 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007890 }
Steve Naroff14108da2009-07-10 23:34:53 +00007891 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007892 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00007893 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007894 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall34d6f932011-03-11 04:25:25 +00007895 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007896 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007897 else
John Wiegley429bb272011-04-08 18:41:53 +00007898 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007899 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007900 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007901 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007902 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7903 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007904 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007905 bool isError = false;
7906 if ((LHSIsNull && lType->isIntegerType()) ||
7907 (RHSIsNull && rType->isIntegerType())) {
7908 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007909 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007910 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007911 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007912 else if (getLangOptions().CPlusPlus) {
7913 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7914 isError = true;
7915 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007916 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007917
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007918 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007919 Diag(Loc, DiagID)
John Wiegley429bb272011-04-08 18:41:53 +00007920 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007921 if (isError)
7922 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007923 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007924
7925 if (lType->isIntegerType())
John Wiegley429bb272011-04-08 18:41:53 +00007926 lex = ImpCastExprToType(lex.take(), rType,
John McCall404cd162010-11-13 01:35:44 +00007927 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007928 else
John Wiegley429bb272011-04-08 18:41:53 +00007929 rex = ImpCastExprToType(rex.take(), lType,
John McCall404cd162010-11-13 01:35:44 +00007930 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007931 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007932 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007933
Steve Naroff39218df2008-09-04 16:56:14 +00007934 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00007935 if (!isRelational && RHSIsNull
7936 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00007937 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007938 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007939 }
Mike Stumpaf199f32009-05-07 18:43:07 +00007940 if (!isRelational && LHSIsNull
7941 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00007942 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007943 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007944 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007945
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007946 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007947}
7948
Nate Begemanbe2341d2008-07-14 18:02:46 +00007949/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007950/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007951/// like a scalar comparison, a vector comparison produces a vector of integer
7952/// types.
John Wiegley429bb272011-04-08 18:41:53 +00007953QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007954 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007955 bool isRelational) {
7956 // Check to make sure we're operating on vectors of the same type and width,
7957 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007958 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007959 if (vType.isNull())
7960 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007961
John Wiegley429bb272011-04-08 18:41:53 +00007962 QualType lType = lex.get()->getType();
7963 QualType rType = rex.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007964
Anton Yartsev7870b132011-03-27 15:36:07 +00007965 // If AltiVec, the comparison results in a numeric type, i.e.
7966 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007967 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007968 return Context.getLogicalOperationType();
7969
Nate Begemanbe2341d2008-07-14 18:02:46 +00007970 // For non-floating point types, check for self-comparisons of the form
7971 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7972 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007973 if (!lType->hasFloatingRepresentation()) {
John Wiegley429bb272011-04-08 18:41:53 +00007974 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
7975 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007976 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007977 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007978 PDiag(diag::warn_comparison_always)
7979 << 0 // self-
7980 << 2 // "a constant"
7981 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007982 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007983
Nate Begemanbe2341d2008-07-14 18:02:46 +00007984 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007985 if (!isRelational && lType->hasFloatingRepresentation()) {
7986 assert (rType->hasFloatingRepresentation());
John Wiegley429bb272011-04-08 18:41:53 +00007987 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007988 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007989
Nate Begemanbe2341d2008-07-14 18:02:46 +00007990 // Return the type for the comparison, which is the same as vector type for
7991 // integer vectors, or an integer type of identical size and number of
7992 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00007993 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00007994 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007995
John McCall183700f2009-09-21 23:43:11 +00007996 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00007997 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00007998 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007999 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00008000 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00008001 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8002
Mike Stumpeed9cac2009-02-19 03:04:26 +00008003 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00008004 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00008005 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8006}
8007
Reid Spencer5f016e22007-07-11 17:01:13 +00008008inline QualType Sema::CheckBitwiseOperands(
John Wiegley429bb272011-04-08 18:41:53 +00008009 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
8010 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
8011 if (lex.get()->getType()->hasIntegerRepresentation() &&
8012 rex.get()->getType()->hasIntegerRepresentation())
Douglas Gregorf6094622010-07-23 15:58:24 +00008013 return CheckVectorOperands(Loc, lex, rex);
8014
8015 return InvalidOperands(Loc, lex, rex);
8016 }
Steve Naroff90045e82007-07-13 23:32:42 +00008017
John Wiegley429bb272011-04-08 18:41:53 +00008018 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
8019 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
8020 if (lexResult.isInvalid() || rexResult.isInvalid())
8021 return QualType();
8022 lex = lexResult.take();
8023 rex = rexResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00008024
John Wiegley429bb272011-04-08 18:41:53 +00008025 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
8026 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00008027 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008028 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00008029}
8030
8031inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley429bb272011-04-08 18:41:53 +00008032 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00008033
8034 // Diagnose cases where the user write a logical and/or but probably meant a
8035 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
8036 // is a constant.
John Wiegley429bb272011-04-08 18:41:53 +00008037 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
8038 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Chris Lattner23ef3e42010-07-15 00:26:43 +00008039 // Don't warn in macros.
Chris Lattnerb7690b42010-07-24 01:10:11 +00008040 !Loc.isMacroID()) {
8041 // If the RHS can be constant folded, and if it constant folds to something
8042 // that isn't 0 or 1 (which indicate a potential logical operation that
8043 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00008044 // Parens on the RHS are ignored.
Chris Lattnerb7690b42010-07-24 01:10:11 +00008045 Expr::EvalResult Result;
Chandler Carruth0683a142011-05-31 05:41:42 +00008046 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
8047 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
8048 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
8049 Diag(Loc, diag::warn_logical_instead_of_bitwise)
8050 << rex.get()->getSourceRange()
8051 << (Opc == BO_LAnd ? "&&" : "||")
8052 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattnerb7690b42010-07-24 01:10:11 +00008053 }
8054 }
Chris Lattner90a8f272010-07-13 19:41:32 +00008055
Anders Carlssona4c98cd2009-11-23 21:47:44 +00008056 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00008057 lex = UsualUnaryConversions(lex.take());
8058 if (lex.isInvalid())
8059 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00008060
John Wiegley429bb272011-04-08 18:41:53 +00008061 rex = UsualUnaryConversions(rex.take());
8062 if (rex.isInvalid())
8063 return QualType();
8064
8065 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00008066 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008067
Anders Carlssona4c98cd2009-11-23 21:47:44 +00008068 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00008069 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008070
John McCall75f7c0f2010-06-04 00:29:51 +00008071 // The following is safe because we only use this method for
8072 // non-overloadable operands.
8073
Anders Carlssona4c98cd2009-11-23 21:47:44 +00008074 // C++ [expr.log.and]p1
8075 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00008076 // The operands are both contextually converted to type bool.
John Wiegley429bb272011-04-08 18:41:53 +00008077 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
8078 if (lexRes.isInvalid())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00008079 return InvalidOperands(Loc, lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00008080 lex = move(lexRes);
8081
8082 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
8083 if (rexRes.isInvalid())
8084 return InvalidOperands(Loc, lex, rex);
8085 rex = move(rexRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008086
Anders Carlssona4c98cd2009-11-23 21:47:44 +00008087 // C++ [expr.log.and]p2
8088 // C++ [expr.log.or]p2
8089 // The result is a bool.
8090 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00008091}
8092
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00008093/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
8094/// is a read-only property; return true if so. A readonly property expression
8095/// depends on various declarations and thus must be treated specially.
8096///
Mike Stump1eb44332009-09-09 15:08:12 +00008097static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00008098 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
8099 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00008100 if (PropExpr->isImplicitProperty()) return false;
8101
8102 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
8103 QualType BaseType = PropExpr->isSuperReceiver() ?
8104 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00008105 PropExpr->getBase()->getType();
8106
John McCall12f78a62010-12-02 01:19:52 +00008107 if (const ObjCObjectPointerType *OPT =
8108 BaseType->getAsObjCInterfacePointerType())
8109 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
8110 if (S.isPropertyReadonly(PDecl, IFace))
8111 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00008112 }
8113 return false;
8114}
8115
Fariborz Jahanian14086762011-03-28 23:47:18 +00008116static bool IsConstProperty(Expr *E, Sema &S) {
8117 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
8118 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
8119 if (PropExpr->isImplicitProperty()) return false;
8120
8121 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
8122 QualType T = PDecl->getType();
8123 if (T->isReferenceType())
Fariborz Jahanian61750f22011-03-30 16:59:30 +00008124 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanian14086762011-03-28 23:47:18 +00008125 CanQualType CT = S.Context.getCanonicalType(T);
8126 return CT.isConstQualified();
8127 }
8128 return false;
8129}
8130
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008131static bool IsReadonlyMessage(Expr *E, Sema &S) {
8132 if (E->getStmtClass() != Expr::MemberExprClass)
8133 return false;
8134 const MemberExpr *ME = cast<MemberExpr>(E);
8135 NamedDecl *Member = ME->getMemberDecl();
8136 if (isa<FieldDecl>(Member)) {
8137 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
8138 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
8139 return false;
8140 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
8141 }
8142 return false;
8143}
8144
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008145/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
8146/// emit an error and return true. If so, return false.
8147static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00008148 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00008149 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00008150 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00008151 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
8152 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00008153 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
8154 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008155 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8156 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008157 if (IsLV == Expr::MLV_Valid)
8158 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008159
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008160 unsigned Diag = 0;
8161 bool NeedType = false;
8162 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00008163 case Expr::MLV_ConstQualified:
8164 Diag = diag::err_typecheck_assign_const;
8165
John McCall7acddac2011-06-17 06:42:21 +00008166 // In ARC, use some specialized diagnostics for occasions where we
8167 // infer 'const'. These are always pseudo-strong variables.
John McCallf85e1932011-06-15 23:02:42 +00008168 if (S.getLangOptions().ObjCAutoRefCount) {
8169 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8170 if (declRef && isa<VarDecl>(declRef->getDecl())) {
8171 VarDecl *var = cast<VarDecl>(declRef->getDecl());
8172
John McCall7acddac2011-06-17 06:42:21 +00008173 // Use the normal diagnostic if it's pseudo-__strong but the
8174 // user actually wrote 'const'.
8175 if (var->isARCPseudoStrong() &&
8176 (!var->getTypeSourceInfo() ||
8177 !var->getTypeSourceInfo()->getType().isConstQualified())) {
8178 // There are two pseudo-strong cases:
8179 // - self
John McCallf85e1932011-06-15 23:02:42 +00008180 ObjCMethodDecl *method = S.getCurMethodDecl();
8181 if (method && var == method->getSelfDecl())
8182 Diag = diag::err_typecheck_arr_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00008183
8184 // - fast enumeration variables
8185 else
John McCallf85e1932011-06-15 23:02:42 +00008186 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00008187
John McCallf85e1932011-06-15 23:02:42 +00008188 SourceRange Assign;
8189 if (Loc != OrigLoc)
8190 Assign = SourceRange(OrigLoc, OrigLoc);
8191 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8192 // We need to preserve the AST regardless, so migration tool
8193 // can do its job.
8194 return false;
8195 }
8196 }
8197 }
8198
8199 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008200 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008201 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8202 NeedType = true;
8203 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008204 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008205 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8206 NeedType = true;
8207 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00008208 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008209 Diag = diag::err_typecheck_lvalue_casts_not_supported;
8210 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00008211 case Expr::MLV_Valid:
8212 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00008213 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00008214 case Expr::MLV_MemberFunction:
8215 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008216 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8217 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008218 case Expr::MLV_IncompleteType:
8219 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00008220 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008221 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00008222 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00008223 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008224 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8225 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00008226 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008227 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8228 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00008229 case Expr::MLV_ReadonlyProperty:
8230 Diag = diag::error_readonly_property_assignment;
8231 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00008232 case Expr::MLV_NoSetterProperty:
8233 Diag = diag::error_nosetter_property_assignment;
8234 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008235 case Expr::MLV_InvalidMessageExpression:
8236 Diag = diag::error_readonly_message_assignment;
8237 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00008238 case Expr::MLV_SubObjCPropertySetting:
8239 Diag = diag::error_no_subobject_property_setting;
8240 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008241 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00008242
Daniel Dunbar44e35f72009-04-15 00:08:05 +00008243 SourceRange Assign;
8244 if (Loc != OrigLoc)
8245 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008246 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00008247 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008248 else
Mike Stump1eb44332009-09-09 15:08:12 +00008249 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008250 return true;
8251}
8252
8253
8254
8255// C99 6.5.16.1
John Wiegley429bb272011-04-08 18:41:53 +00008256QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008257 SourceLocation Loc,
8258 QualType CompoundType) {
8259 // Verify that LHS is a modifiable lvalue, and emit error if not.
8260 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008261 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008262
8263 QualType LHSType = LHS->getType();
John Wiegley429bb272011-04-08 18:41:53 +00008264 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008265 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008266 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00008267 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00008268 // Simple assignment "x = y".
John Wiegley429bb272011-04-08 18:41:53 +00008269 if (LHS->getObjectKind() == OK_ObjCProperty) {
8270 ExprResult LHSResult = Owned(LHS);
8271 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
8272 if (LHSResult.isInvalid())
8273 return QualType();
8274 LHS = LHSResult.take();
8275 }
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00008276 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00008277 if (RHS.isInvalid())
8278 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00008279 // Special case of NSObject attributes on c-style pointer types.
8280 if (ConvTy == IncompatiblePointer &&
8281 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00008282 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00008283 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00008284 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00008285 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008286
John McCallf89e55a2010-11-18 06:31:45 +00008287 if (ConvTy == Compatible &&
8288 getLangOptions().ObjCNonFragileABI &&
8289 LHSType->isObjCObjectType())
8290 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
8291 << LHSType;
8292
Chris Lattner2c156472008-08-21 18:04:13 +00008293 // If the RHS is a unary plus or minus, check to see if they = and + are
8294 // right next to each other. If so, the user may have typo'd "x =+ 4"
8295 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00008296 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00008297 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8298 RHSCheck = ICE->getSubExpr();
8299 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00008300 if ((UO->getOpcode() == UO_Plus ||
8301 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008302 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00008303 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00008304 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
8305 // And there is a space or other character before the subexpr of the
8306 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00008307 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8308 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008309 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00008310 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008311 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00008312 }
Chris Lattner2c156472008-08-21 18:04:13 +00008313 }
John McCallf85e1932011-06-15 23:02:42 +00008314
8315 if (ConvTy == Compatible) {
8316 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
8317 checkRetainCycles(LHS, RHS.get());
8318 else
8319 checkUnsafeAssigns(Loc, LHSType, RHS.get());
8320 }
Chris Lattner2c156472008-08-21 18:04:13 +00008321 } else {
8322 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00008323 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00008324 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00008325
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008326 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00008327 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00008328 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00008329
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +00008330 CheckForNullPointerDereference(*this, LHS);
Ted Kremeneka0125d82011-02-16 01:57:07 +00008331 // Check for trivial buffer overflows.
Ted Kremenek3aea4da2011-03-01 18:41:00 +00008332 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremeneka0125d82011-02-16 01:57:07 +00008333
Reid Spencer5f016e22007-07-11 17:01:13 +00008334 // C99 6.5.16p3: The type of an assignment expression is the type of the
8335 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00008336 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00008337 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8338 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008339 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00008340 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00008341 return (getLangOptions().CPlusPlus
8342 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008343}
8344
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008345// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00008346static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00008347 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00008348 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00008349
John McCallfb8721c2011-04-10 19:13:55 +00008350 LHS = S.CheckPlaceholderExpr(LHS.take());
8351 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00008352 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00008353 return QualType();
8354
John McCallcf2e5062010-10-12 07:14:40 +00008355 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8356 // operands, but not unary promotions.
8357 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008358
John McCallf6a16482010-12-04 03:47:34 +00008359 // So we treat the LHS as a ignored value, and in C++ we allow the
8360 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00008361 LHS = S.IgnoredValueConversions(LHS.take());
8362 if (LHS.isInvalid())
8363 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00008364
8365 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00008366 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8367 if (RHS.isInvalid())
8368 return QualType();
8369 if (!RHS.get()->getType()->isVoidType())
8370 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00008371 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008372
John Wiegley429bb272011-04-08 18:41:53 +00008373 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008374}
8375
Steve Naroff49b45262007-07-13 16:58:59 +00008376/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8377/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00008378static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8379 ExprValueKind &VK,
8380 SourceLocation OpLoc,
8381 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00008382 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008383 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008384
Chris Lattner3528d352008-11-21 07:05:48 +00008385 QualType ResType = Op->getType();
8386 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008387
John McCall09431682010-11-18 19:01:18 +00008388 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008389 // Decrement of bool is not allowed.
8390 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00008391 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008392 return QualType();
8393 }
8394 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00008395 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008396 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00008397 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00008398 } else if (ResType->isAnyPointerType()) {
8399 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00008400
Chris Lattner3528d352008-11-21 07:05:48 +00008401 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00008402 if (PointeeTy->isVoidType()) {
John McCall09431682010-11-18 19:01:18 +00008403 if (S.getLangOptions().CPlusPlus) {
8404 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00008405 << Op->getSourceRange();
8406 return QualType();
8407 }
8408
8409 // Pointer to void is a GNU extension in C.
John McCall09431682010-11-18 19:01:18 +00008410 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00008411 } else if (PointeeTy->isFunctionType()) {
John McCall09431682010-11-18 19:01:18 +00008412 if (S.getLangOptions().CPlusPlus) {
8413 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00008414 << Op->getType() << Op->getSourceRange();
8415 return QualType();
8416 }
8417
John McCall09431682010-11-18 19:01:18 +00008418 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00008419 << ResType << Op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008420 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
8421 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00008422 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00008423 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00008424 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00008425 // Diagnose bad cases where we step over interface counts.
John McCall09431682010-11-18 19:01:18 +00008426 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
8427 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00008428 << PointeeTy << Op->getSourceRange();
8429 return QualType();
8430 }
Eli Friedman5b088a12010-01-03 00:20:48 +00008431 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00008432 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00008433 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00008434 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008435 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008436 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008437 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008438 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8439 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00008440 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
8441 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00008442 } else {
John McCall09431682010-11-18 19:01:18 +00008443 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00008444 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00008445 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008446 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008447 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00008448 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00008449 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00008450 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008451 // In C++, a prefix increment is the same type as the operand. Otherwise
8452 // (in C or with postfix), the increment is the unqualified type of the
8453 // operand.
John McCall09431682010-11-18 19:01:18 +00008454 if (isPrefix && S.getLangOptions().CPlusPlus) {
8455 VK = VK_LValue;
8456 return ResType;
8457 } else {
8458 VK = VK_RValue;
8459 return ResType.getUnqualifiedType();
8460 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008461}
8462
John Wiegley429bb272011-04-08 18:41:53 +00008463ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCallf6a16482010-12-04 03:47:34 +00008464 assert(E->getValueKind() == VK_LValue &&
8465 E->getObjectKind() == OK_ObjCProperty);
8466 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
8467
Douglas Gregor926df6c2011-06-11 01:09:30 +00008468 QualType T = E->getType();
8469 QualType ReceiverType;
8470 if (PRE->isObjectReceiver())
8471 ReceiverType = PRE->getBase()->getType();
8472 else if (PRE->isSuperReceiver())
8473 ReceiverType = PRE->getSuperReceiverType();
8474 else
8475 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
8476
John McCallf6a16482010-12-04 03:47:34 +00008477 ExprValueKind VK = VK_RValue;
8478 if (PRE->isImplicitProperty()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00008479 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian99130e52010-12-22 19:46:35 +00008480 PRE->getImplicitPropertyGetter()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00008481 T = getMessageSendResultType(ReceiverType, GetterMethod,
8482 PRE->isClassReceiver(),
8483 PRE->isSuperReceiver());
8484 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian99130e52010-12-22 19:46:35 +00008485 }
8486 else {
8487 Diag(PRE->getLocation(), diag::err_getter_not_found)
8488 << PRE->getBase()->getType();
8489 }
John McCallf6a16482010-12-04 03:47:34 +00008490 }
Douglas Gregor926df6c2011-06-11 01:09:30 +00008491
8492 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCallf6a16482010-12-04 03:47:34 +00008493 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00008494
8495 ExprResult Result = MaybeBindToTemporary(E);
8496 if (!Result.isInvalid())
8497 E = Result.take();
John Wiegley429bb272011-04-08 18:41:53 +00008498
8499 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00008500}
8501
John Wiegley429bb272011-04-08 18:41:53 +00008502void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
8503 assert(LHS.get()->getValueKind() == VK_LValue &&
8504 LHS.get()->getObjectKind() == OK_ObjCProperty);
8505 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCallf6a16482010-12-04 03:47:34 +00008506
John McCallf85e1932011-06-15 23:02:42 +00008507 bool Consumed = false;
8508
John Wiegley429bb272011-04-08 18:41:53 +00008509 if (PropRef->isImplicitProperty()) {
John McCallf6a16482010-12-04 03:47:34 +00008510 // If using property-dot syntax notation for assignment, and there is a
8511 // setter, RHS expression is being passed to the setter argument. So,
8512 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley429bb272011-04-08 18:41:53 +00008513 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCallf6a16482010-12-04 03:47:34 +00008514 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
8515 LHSTy = (*P)->getType();
John McCallf85e1932011-06-15 23:02:42 +00008516 Consumed = (getLangOptions().ObjCAutoRefCount &&
8517 (*P)->hasAttr<NSConsumedAttr>());
John McCallf6a16482010-12-04 03:47:34 +00008518
8519 // Otherwise, if the getter returns an l-value, just call that.
8520 } else {
John Wiegley429bb272011-04-08 18:41:53 +00008521 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCallf6a16482010-12-04 03:47:34 +00008522 ExprValueKind VK = Expr::getValueKindForType(Result);
8523 if (VK == VK_LValue) {
John Wiegley429bb272011-04-08 18:41:53 +00008524 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
8525 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCallf6a16482010-12-04 03:47:34 +00008526 return;
John McCall12f78a62010-12-02 01:19:52 +00008527 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008528 }
John McCallf85e1932011-06-15 23:02:42 +00008529 } else if (getLangOptions().ObjCAutoRefCount) {
8530 const ObjCMethodDecl *setter
8531 = PropRef->getExplicitProperty()->getSetterMethodDecl();
8532 if (setter) {
8533 ObjCMethodDecl::param_iterator P = setter->param_begin();
8534 LHSTy = (*P)->getType();
8535 Consumed = (*P)->hasAttr<NSConsumedAttr>();
8536 }
John McCallf6a16482010-12-04 03:47:34 +00008537 }
8538
John McCallf85e1932011-06-15 23:02:42 +00008539 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
8540 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008541 InitializedEntity Entity =
John McCallf85e1932011-06-15 23:02:42 +00008542 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley429bb272011-04-08 18:41:53 +00008543 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCallf85e1932011-06-15 23:02:42 +00008544 if (!ArgE.isInvalid()) {
John Wiegley429bb272011-04-08 18:41:53 +00008545 RHS = ArgE;
John McCallf85e1932011-06-15 23:02:42 +00008546 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
8547 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
8548 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008549 }
8550}
8551
8552
Anders Carlsson369dee42008-02-01 07:15:58 +00008553/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00008554/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008555/// where the declaration is needed for type checking. We only need to
8556/// handle cases when the expression references a function designator
8557/// or is an lvalue. Here are some examples:
8558/// - &(x) => x
8559/// - &*****f => f for f a function designator.
8560/// - &s.xx => s
8561/// - &s.zz[1].yy -> s, if zz is an array
8562/// - *(x + 1) -> x, if x is an array
8563/// - &"123"[2] -> 0
8564/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00008565static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00008566 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00008567 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00008568 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00008569 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00008570 // If this is an arrow operator, the address is an offset from
8571 // the base's value, so the object the base refers to is
8572 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00008573 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00008574 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00008575 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00008576 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00008577 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00008578 // FIXME: This code shouldn't be necessary! We should catch the implicit
8579 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00008580 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8581 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8582 if (ICE->getSubExpr()->getType()->isArrayType())
8583 return getPrimaryDecl(ICE->getSubExpr());
8584 }
8585 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00008586 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008587 case Stmt::UnaryOperatorClass: {
8588 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008589
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008590 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00008591 case UO_Real:
8592 case UO_Imag:
8593 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008594 return getPrimaryDecl(UO->getSubExpr());
8595 default:
8596 return 0;
8597 }
8598 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008599 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00008600 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00008601 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00008602 // If the result of an implicit cast is an l-value, we care about
8603 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00008604 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00008605 default:
8606 return 0;
8607 }
8608}
8609
8610/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00008611/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00008612/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008613/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00008614/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008615/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00008616/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00008617static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
8618 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00008619 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008620 return S.Context.DependentTy;
8621 if (OrigOp->getType() == S.Context.OverloadTy)
8622 return S.Context.OverloadTy;
John McCall755d8492011-04-12 00:42:48 +00008623 if (OrigOp->getType() == S.Context.UnknownAnyTy)
8624 return S.Context.UnknownAnyTy;
John McCall864c0412011-04-26 20:42:42 +00008625 if (OrigOp->getType() == S.Context.BoundMemberTy) {
8626 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8627 << OrigOp->getSourceRange();
8628 return QualType();
8629 }
John McCall9c72c602010-08-27 09:08:28 +00008630
John McCall755d8492011-04-12 00:42:48 +00008631 assert(!OrigOp->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00008632
John McCall9c72c602010-08-27 09:08:28 +00008633 // Make sure to ignore parentheses in subsequent checks
8634 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00008635
John McCall09431682010-11-18 19:01:18 +00008636 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00008637 // Implement C99-only parts of addressof rules.
8638 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00008639 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00008640 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8641 // (assuming the deref expression is valid).
8642 return uOp->getSubExpr()->getType();
8643 }
8644 // Technically, there should be a check for array subscript
8645 // expressions here, but the result of one is always an lvalue anyway.
8646 }
John McCall5808ce42011-02-03 08:15:49 +00008647 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00008648 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00008649
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008650 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00008651 bool sfinae = S.isSFINAEContext();
8652 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8653 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00008654 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008655 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00008656 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00008657 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008658 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00008659 } else if (lval == Expr::LV_MemberFunction) {
8660 // If it's an instance method, make a member pointer.
8661 // The expression must have exactly the form &A::foo.
8662
8663 // If the underlying expression isn't a decl ref, give up.
8664 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008665 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008666 << OrigOp->getSourceRange();
8667 return QualType();
8668 }
8669 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8670 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8671
8672 // The id-expression was parenthesized.
8673 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00008674 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008675 << OrigOp->getSourceRange();
8676
8677 // The method was named without a qualifier.
8678 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00008679 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008680 << op->getSourceRange();
8681 }
8682
John McCall09431682010-11-18 19:01:18 +00008683 return S.Context.getMemberPointerType(op->getType(),
8684 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00008685 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00008686 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008687 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00008688 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00008689 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00008690 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008691 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00008692 return QualType();
8693 }
John McCall7eb0a9e2010-11-24 05:12:34 +00008694 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008695 // The operand cannot be a bit-field
John McCall09431682010-11-18 19:01:18 +00008696 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman23d58ce2009-04-20 08:23:18 +00008697 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00008698 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00008699 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00008700 // The operand cannot be an element of a vector
John McCall09431682010-11-18 19:01:18 +00008701 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00008702 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00008703 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00008704 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00008705 // cannot take address of a property expression.
John McCall09431682010-11-18 19:01:18 +00008706 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian0337f212009-07-07 18:50:52 +00008707 << "property expression" << op->getSourceRange();
8708 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00008709 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008710 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008711 // with the register storage-class specifier.
8712 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008713 // in C++ it is not error to take address of a register
8714 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008715 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00008716 !S.getLangOptions().CPlusPlus) {
8717 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008718 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00008719 return QualType();
8720 }
John McCallba135432009-11-21 08:51:07 +00008721 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008722 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008723 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008724 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008725 // Could be a pointer to member, though, if there is an explicit
8726 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008727 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008728 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008729 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008730 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008731 S.Diag(OpLoc,
8732 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008733 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008734 return QualType();
8735 }
Mike Stump1eb44332009-09-09 15:08:12 +00008736
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008737 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8738 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008739 return S.Context.getMemberPointerType(op->getType(),
8740 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008741 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008742 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00008743 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00008744 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008745 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008746
Eli Friedman441cf102009-05-16 23:27:50 +00008747 if (lval == Expr::LV_IncompleteVoidType) {
8748 // Taking the address of a void variable is technically illegal, but we
8749 // allow it in cases which are otherwise valid.
8750 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008751 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008752 }
8753
Reid Spencer5f016e22007-07-11 17:01:13 +00008754 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008755 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008756 return S.Context.getObjCObjectPointerType(op->getType());
8757 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008758}
8759
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008760/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008761static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8762 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008763 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008764 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008765
John Wiegley429bb272011-04-08 18:41:53 +00008766 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8767 if (ConvResult.isInvalid())
8768 return QualType();
8769 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008770 QualType OpTy = Op->getType();
8771 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00008772
8773 if (isa<CXXReinterpretCastExpr>(Op)) {
8774 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8775 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8776 Op->getSourceRange());
8777 }
8778
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008779 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8780 // is an incomplete type or void. It would be possible to warn about
8781 // dereferencing a void pointer, but it's completely well-defined, and such a
8782 // warning is unlikely to catch any mistakes.
8783 if (const PointerType *PT = OpTy->getAs<PointerType>())
8784 Result = PT->getPointeeType();
8785 else if (const ObjCObjectPointerType *OPT =
8786 OpTy->getAs<ObjCObjectPointerType>())
8787 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008788 else {
John McCallfb8721c2011-04-10 19:13:55 +00008789 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008790 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008791 if (PR.take() != Op)
8792 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008793 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008794
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008795 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008796 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008797 << OpTy << Op->getSourceRange();
8798 return QualType();
8799 }
John McCall09431682010-11-18 19:01:18 +00008800
8801 // Dereferences are usually l-values...
8802 VK = VK_LValue;
8803
8804 // ...except that certain expressions are never l-values in C.
8805 if (!S.getLangOptions().CPlusPlus &&
8806 IsCForbiddenLValueType(S.Context, Result))
8807 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008808
8809 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008810}
8811
John McCall2de56d12010-08-25 11:45:40 +00008812static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008813 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008814 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008815 switch (Kind) {
8816 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008817 case tok::periodstar: Opc = BO_PtrMemD; break;
8818 case tok::arrowstar: Opc = BO_PtrMemI; break;
8819 case tok::star: Opc = BO_Mul; break;
8820 case tok::slash: Opc = BO_Div; break;
8821 case tok::percent: Opc = BO_Rem; break;
8822 case tok::plus: Opc = BO_Add; break;
8823 case tok::minus: Opc = BO_Sub; break;
8824 case tok::lessless: Opc = BO_Shl; break;
8825 case tok::greatergreater: Opc = BO_Shr; break;
8826 case tok::lessequal: Opc = BO_LE; break;
8827 case tok::less: Opc = BO_LT; break;
8828 case tok::greaterequal: Opc = BO_GE; break;
8829 case tok::greater: Opc = BO_GT; break;
8830 case tok::exclaimequal: Opc = BO_NE; break;
8831 case tok::equalequal: Opc = BO_EQ; break;
8832 case tok::amp: Opc = BO_And; break;
8833 case tok::caret: Opc = BO_Xor; break;
8834 case tok::pipe: Opc = BO_Or; break;
8835 case tok::ampamp: Opc = BO_LAnd; break;
8836 case tok::pipepipe: Opc = BO_LOr; break;
8837 case tok::equal: Opc = BO_Assign; break;
8838 case tok::starequal: Opc = BO_MulAssign; break;
8839 case tok::slashequal: Opc = BO_DivAssign; break;
8840 case tok::percentequal: Opc = BO_RemAssign; break;
8841 case tok::plusequal: Opc = BO_AddAssign; break;
8842 case tok::minusequal: Opc = BO_SubAssign; break;
8843 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8844 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8845 case tok::ampequal: Opc = BO_AndAssign; break;
8846 case tok::caretequal: Opc = BO_XorAssign; break;
8847 case tok::pipeequal: Opc = BO_OrAssign; break;
8848 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008849 }
8850 return Opc;
8851}
8852
John McCall2de56d12010-08-25 11:45:40 +00008853static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008854 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008855 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008856 switch (Kind) {
8857 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008858 case tok::plusplus: Opc = UO_PreInc; break;
8859 case tok::minusminus: Opc = UO_PreDec; break;
8860 case tok::amp: Opc = UO_AddrOf; break;
8861 case tok::star: Opc = UO_Deref; break;
8862 case tok::plus: Opc = UO_Plus; break;
8863 case tok::minus: Opc = UO_Minus; break;
8864 case tok::tilde: Opc = UO_Not; break;
8865 case tok::exclaim: Opc = UO_LNot; break;
8866 case tok::kw___real: Opc = UO_Real; break;
8867 case tok::kw___imag: Opc = UO_Imag; break;
8868 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008869 }
8870 return Opc;
8871}
8872
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008873/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8874/// This warning is only emitted for builtin assignment operations. It is also
8875/// suppressed in the event of macro expansions.
8876static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8877 SourceLocation OpLoc) {
8878 if (!S.ActiveTemplateInstantiations.empty())
8879 return;
8880 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8881 return;
8882 lhs = lhs->IgnoreParenImpCasts();
8883 rhs = rhs->IgnoreParenImpCasts();
8884 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8885 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8886 if (!LeftDeclRef || !RightDeclRef ||
8887 LeftDeclRef->getLocation().isMacroID() ||
8888 RightDeclRef->getLocation().isMacroID())
8889 return;
8890 const ValueDecl *LeftDecl =
8891 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8892 const ValueDecl *RightDecl =
8893 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8894 if (LeftDecl != RightDecl)
8895 return;
8896 if (LeftDecl->getType().isVolatileQualified())
8897 return;
8898 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8899 if (RefTy->getPointeeType().isVolatileQualified())
8900 return;
8901
8902 S.Diag(OpLoc, diag::warn_self_assignment)
8903 << LeftDeclRef->getType()
8904 << lhs->getSourceRange() << rhs->getSourceRange();
8905}
8906
Douglas Gregoreaebc752008-11-06 23:29:22 +00008907/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8908/// operator @p Opc at location @c TokLoc. This routine only supports
8909/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008910ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008911 BinaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008912 Expr *lhsExpr, Expr *rhsExpr) {
8913 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008914 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008915 // The following two variables are used for compound assignment operators
8916 QualType CompLHSTy; // Type of LHS after promotions for computation
8917 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008918 ExprValueKind VK = VK_RValue;
8919 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008920
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008921 // Check if a 'foo<int>' involved in a binary op, identifies a single
8922 // function unambiguously (i.e. an lvalue ala 13.4)
8923 // But since an assignment can trigger target based overload, exclude it in
8924 // our blind search. i.e:
8925 // template<class T> void f(); template<class T, class U> void f(U);
8926 // f<int> == 0; // resolve f<int> blindly
8927 // void (*p)(int); p = f<int>; // resolve f<int> using target
8928 if (Opc != BO_Assign) {
John McCallfb8721c2011-04-10 19:13:55 +00008929 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008930 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008931 lhs = move(resolvedLHS);
John McCall1de4d4e2011-04-07 08:22:57 +00008932
John McCallfb8721c2011-04-10 19:13:55 +00008933 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008934 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008935 rhs = move(resolvedRHS);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008936 }
8937
Eli Friedmaned3b2562011-06-17 20:52:22 +00008938 // The canonical way to check for a GNU null is with isNullPointerConstant,
8939 // but we use a bit of a hack here for speed; this is a relatively
8940 // hot path, and isNullPointerConstant is slow.
8941 bool LeftNull = isa<GNUNullExpr>(lhs.get()->IgnoreParenImpCasts());
8942 bool RightNull = isa<GNUNullExpr>(rhs.get()->IgnoreParenImpCasts());
Richard Trieu3e95ba92011-06-16 21:36:56 +00008943
8944 // Detect when a NULL constant is used improperly in an expression. These
8945 // are mainly cases where the null pointer is used as an integer instead
8946 // of a pointer.
8947 if (LeftNull || RightNull) {
8948 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
8949 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
8950 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
8951 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
8952 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
8953 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
8954 // These are the operations that would not make sense with a null pointer
8955 // no matter what the other expression is.
Chandler Carruth2af68e42011-06-19 09:05:14 +00008956 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
8957 << (LeftNull ? lhs.get()->getSourceRange() : SourceRange())
8958 << (RightNull ? rhs.get()->getSourceRange() : SourceRange());
Richard Trieu3e95ba92011-06-16 21:36:56 +00008959 } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
8960 Opc == BO_EQ || Opc == BO_NE) {
8961 // These are the operations that would not make sense with a null pointer
8962 // if the other expression the other expression is not a pointer.
8963 QualType LeftType = lhs.get()->getType();
8964 QualType RightType = rhs.get()->getType();
Chandler Carruth2af68e42011-06-19 09:05:14 +00008965 if (LeftNull != RightNull &&
8966 !LeftType->isPointerLikeType() && !RightType->isPointerLikeType()) {
8967 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
8968 << (LeftNull ? lhs.get()->getSourceRange()
8969 : rhs.get()->getSourceRange());
Richard Trieu3e95ba92011-06-16 21:36:56 +00008970 }
8971 }
8972 }
8973
Douglas Gregoreaebc752008-11-06 23:29:22 +00008974 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008975 case BO_Assign:
John Wiegley429bb272011-04-08 18:41:53 +00008976 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00008977 if (getLangOptions().CPlusPlus &&
John Wiegley429bb272011-04-08 18:41:53 +00008978 lhs.get()->getObjectKind() != OK_ObjCProperty) {
8979 VK = lhs.get()->getValueKind();
8980 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008981 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008982 if (!ResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00008983 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008984 break;
John McCall2de56d12010-08-25 11:45:40 +00008985 case BO_PtrMemD:
8986 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00008987 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008988 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008989 break;
John McCall2de56d12010-08-25 11:45:40 +00008990 case BO_Mul:
8991 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00008992 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008993 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008994 break;
John McCall2de56d12010-08-25 11:45:40 +00008995 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008996 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8997 break;
John McCall2de56d12010-08-25 11:45:40 +00008998 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008999 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
9000 break;
John McCall2de56d12010-08-25 11:45:40 +00009001 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00009002 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
9003 break;
John McCall2de56d12010-08-25 11:45:40 +00009004 case BO_Shl:
9005 case BO_Shr:
Chandler Carruth21206d52011-02-23 23:34:11 +00009006 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009007 break;
John McCall2de56d12010-08-25 11:45:40 +00009008 case BO_LE:
9009 case BO_LT:
9010 case BO_GE:
9011 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00009012 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009013 break;
John McCall2de56d12010-08-25 11:45:40 +00009014 case BO_EQ:
9015 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00009016 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009017 break;
John McCall2de56d12010-08-25 11:45:40 +00009018 case BO_And:
9019 case BO_Xor:
9020 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00009021 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
9022 break;
John McCall2de56d12010-08-25 11:45:40 +00009023 case BO_LAnd:
9024 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00009025 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009026 break;
John McCall2de56d12010-08-25 11:45:40 +00009027 case BO_MulAssign:
9028 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00009029 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00009030 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00009031 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00009032 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9033 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009034 break;
John McCall2de56d12010-08-25 11:45:40 +00009035 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00009036 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
9037 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00009038 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9039 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009040 break;
John McCall2de56d12010-08-25 11:45:40 +00009041 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00009042 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00009043 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9044 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009045 break;
John McCall2de56d12010-08-25 11:45:40 +00009046 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00009047 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00009048 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9049 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009050 break;
John McCall2de56d12010-08-25 11:45:40 +00009051 case BO_ShlAssign:
9052 case BO_ShrAssign:
Chandler Carruth21206d52011-02-23 23:34:11 +00009053 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00009054 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00009055 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9056 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009057 break;
John McCall2de56d12010-08-25 11:45:40 +00009058 case BO_AndAssign:
9059 case BO_XorAssign:
9060 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00009061 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
9062 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00009063 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9064 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009065 break;
John McCall2de56d12010-08-25 11:45:40 +00009066 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00009067 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009068 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
9069 VK = rhs.get()->getValueKind();
9070 OK = rhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00009071 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00009072 break;
9073 }
John Wiegley429bb272011-04-08 18:41:53 +00009074 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00009075 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00009076 if (CompResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00009077 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
9078 ResultTy, VK, OK, OpLoc));
9079 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00009080 VK = VK_LValue;
John Wiegley429bb272011-04-08 18:41:53 +00009081 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00009082 }
John Wiegley429bb272011-04-08 18:41:53 +00009083 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
9084 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00009085 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00009086}
9087
Sebastian Redlaee3c932009-10-27 12:10:02 +00009088/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9089/// operators are mixed in a way that suggests that the programmer forgot that
9090/// comparison operators have higher precedence. The most typical example of
9091/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00009092static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009093 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00009094 typedef BinaryOperator BinOp;
9095 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
9096 rhsopc = static_cast<BinOp::Opcode>(-1);
9097 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009098 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00009099 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009100 rhsopc = BO->getOpcode();
9101
9102 // Subs are not binary operators.
9103 if (lhsopc == -1 && rhsopc == -1)
9104 return;
9105
9106 // Bitwise operations are sometimes used as eager logical ops.
9107 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00009108 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
9109 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009110 return;
9111
Chandler Carruthf0b60d62011-06-16 01:05:14 +00009112 if (BinOp::isComparisonOp(lhsopc)) {
9113 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9114 << SourceRange(lhs->getLocStart(), OpLoc)
9115 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc);
Sebastian Redl6b169ac2009-10-26 17:01:32 +00009116 SuggestParentheses(Self, OpLoc,
Douglas Gregor55b38842010-04-14 16:09:52 +00009117 Self.PDiag(diag::note_precedence_bitwise_silence)
9118 << BinOp::getOpcodeStr(lhsopc),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00009119 lhs->getSourceRange());
9120 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009121 Self.PDiag(diag::note_precedence_bitwise_first)
9122 << BinOp::getOpcodeStr(Opc),
9123 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Chandler Carruthf0b60d62011-06-16 01:05:14 +00009124 } else if (BinOp::isComparisonOp(rhsopc)) {
9125 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9126 << SourceRange(OpLoc, rhs->getLocEnd())
9127 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc);
Sebastian Redl6b169ac2009-10-26 17:01:32 +00009128 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009129 Self.PDiag(diag::note_precedence_bitwise_silence)
9130 << BinOp::getOpcodeStr(rhsopc),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00009131 rhs->getSourceRange());
9132 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00009133 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00009134 << BinOp::getOpcodeStr(Opc),
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009135 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Chandler Carruthf0b60d62011-06-16 01:05:14 +00009136 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009137}
9138
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00009139/// \brief It accepts a '&&' expr that is inside a '||' one.
9140/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9141/// in parentheses.
9142static void
9143EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00009144 BinaryOperator *Bop) {
9145 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00009146 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9147 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00009148 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00009149 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00009150 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00009151}
9152
9153/// \brief Returns true if the given expression can be evaluated as a constant
9154/// 'true'.
9155static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9156 bool Res;
9157 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9158}
9159
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00009160/// \brief Returns true if the given expression can be evaluated as a constant
9161/// 'false'.
9162static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9163 bool Res;
9164 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9165}
9166
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00009167/// \brief Look for '&&' in the left hand of a '||' expr.
9168static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00009169 Expr *OrLHS, Expr *OrRHS) {
9170 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00009171 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00009172 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9173 if (EvaluatesAsFalse(S, OrRHS))
9174 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00009175 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9176 if (!EvaluatesAsTrue(S, Bop->getLHS()))
9177 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9178 } else if (Bop->getOpcode() == BO_LOr) {
9179 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9180 // If it's "a || b && 1 || c" we didn't warn earlier for
9181 // "a || b && 1", but warn now.
9182 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9183 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9184 }
9185 }
9186 }
9187}
9188
9189/// \brief Look for '&&' in the right hand of a '||' expr.
9190static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00009191 Expr *OrLHS, Expr *OrRHS) {
9192 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00009193 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00009194 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9195 if (EvaluatesAsFalse(S, OrLHS))
9196 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00009197 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9198 if (!EvaluatesAsTrue(S, Bop->getRHS()))
9199 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00009200 }
9201 }
9202}
9203
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009204/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00009205/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00009206static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009207 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00009208 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00009209 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00009210 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
9211
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00009212 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9213 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00009214 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00009215 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
9216 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00009217 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009218}
9219
Reid Spencer5f016e22007-07-11 17:01:13 +00009220// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00009221ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00009222 tok::TokenKind Kind,
9223 Expr *lhs, Expr *rhs) {
9224 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00009225 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
9226 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00009227
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009228 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9229 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
9230
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009231 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
9232}
9233
John McCall60d7b3a2010-08-24 06:29:42 +00009234ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00009235 BinaryOperatorKind Opc,
9236 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00009237 if (getLangOptions().CPlusPlus) {
9238 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009239
John McCall01b2e4e2010-12-06 05:26:58 +00009240 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
9241 UseBuiltinOperator = false;
9242 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
9243 UseBuiltinOperator = true;
9244 } else {
9245 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
9246 !rhs->getType()->isOverloadableType();
9247 }
9248
9249 if (!UseBuiltinOperator) {
9250 // Find all of the overloaded operators visible from this
9251 // point. We perform both an operator-name lookup from the local
9252 // scope and an argument-dependent lookup based on the types of
9253 // the arguments.
9254 UnresolvedSet<16> Functions;
9255 OverloadedOperatorKind OverOp
9256 = BinaryOperator::getOverloadedOperator(Opc);
9257 if (S && OverOp != OO_None)
9258 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
9259 Functions);
9260
9261 // Build the (potentially-overloaded, potentially-dependent)
9262 // binary operation.
9263 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
9264 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00009265 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009266
Douglas Gregoreaebc752008-11-06 23:29:22 +00009267 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009268 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00009269}
9270
John McCall60d7b3a2010-08-24 06:29:42 +00009271ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00009272 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00009273 Expr *InputExpr) {
9274 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00009275 ExprValueKind VK = VK_RValue;
9276 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00009277 QualType resultType;
9278 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00009279 case UO_PreInc:
9280 case UO_PreDec:
9281 case UO_PostInc:
9282 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00009283 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00009284 Opc == UO_PreInc ||
9285 Opc == UO_PostInc,
9286 Opc == UO_PreInc ||
9287 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00009288 break;
John McCall2de56d12010-08-25 11:45:40 +00009289 case UO_AddrOf:
John Wiegley429bb272011-04-08 18:41:53 +00009290 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00009291 break;
John McCall1de4d4e2011-04-07 08:22:57 +00009292 case UO_Deref: {
John McCallfb8721c2011-04-10 19:13:55 +00009293 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall1de4d4e2011-04-07 08:22:57 +00009294 if (!resolved.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009295 Input = move(resolved);
9296 Input = DefaultFunctionArrayLvalueConversion(Input.take());
9297 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00009298 break;
John McCall1de4d4e2011-04-07 08:22:57 +00009299 }
John McCall2de56d12010-08-25 11:45:40 +00009300 case UO_Plus:
9301 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00009302 Input = UsualUnaryConversions(Input.take());
9303 if (Input.isInvalid()) return ExprError();
9304 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009305 if (resultType->isDependentType())
9306 break;
Douglas Gregor00619622010-06-22 23:41:02 +00009307 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9308 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00009309 break;
9310 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
9311 resultType->isEnumeralType())
9312 break;
9313 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00009314 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00009315 resultType->isPointerType())
9316 break;
John McCall2cd11fe2010-10-12 02:09:17 +00009317 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00009318 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00009319 if (Input.isInvalid()) return ExprError();
9320 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00009321 }
Douglas Gregor74253732008-11-19 15:42:04 +00009322
Sebastian Redl0eb23302009-01-19 00:08:26 +00009323 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00009324 << resultType << Input.get()->getSourceRange());
9325
John McCall2de56d12010-08-25 11:45:40 +00009326 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00009327 Input = UsualUnaryConversions(Input.take());
9328 if (Input.isInvalid()) return ExprError();
9329 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009330 if (resultType->isDependentType())
9331 break;
Chris Lattner02a65142008-07-25 23:52:49 +00009332 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9333 if (resultType->isComplexType() || resultType->isComplexIntegerType())
9334 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00009335 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00009336 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00009337 else if (resultType->hasIntegerRepresentation())
9338 break;
9339 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00009340 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00009341 if (Input.isInvalid()) return ExprError();
9342 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00009343 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00009344 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00009345 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00009346 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009347 break;
John Wiegley429bb272011-04-08 18:41:53 +00009348
John McCall2de56d12010-08-25 11:45:40 +00009349 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00009350 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00009351 Input = DefaultFunctionArrayLvalueConversion(Input.take());
9352 if (Input.isInvalid()) return ExprError();
9353 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009354 if (resultType->isDependentType())
9355 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00009356 if (resultType->isScalarType()) {
9357 // C99 6.5.3.3p1: ok, fallthrough;
9358 if (Context.getLangOptions().CPlusPlus) {
9359 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9360 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00009361 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9362 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00009363 }
John McCall2cd11fe2010-10-12 02:09:17 +00009364 } else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00009365 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00009366 if (Input.isInvalid()) return ExprError();
9367 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00009368 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00009369 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00009370 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00009371 }
Douglas Gregorea844f32010-09-20 17:13:33 +00009372
Reid Spencer5f016e22007-07-11 17:01:13 +00009373 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00009374 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00009375 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00009376 break;
John McCall2de56d12010-08-25 11:45:40 +00009377 case UO_Real:
9378 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00009379 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00009380 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00009381 if (Input.isInvalid()) return ExprError();
9382 if (Input.get()->getValueKind() != VK_RValue &&
9383 Input.get()->getObjectKind() == OK_Ordinary)
9384 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00009385 break;
John McCall2de56d12010-08-25 11:45:40 +00009386 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00009387 resultType = Input.get()->getType();
9388 VK = Input.get()->getValueKind();
9389 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00009390 break;
9391 }
John Wiegley429bb272011-04-08 18:41:53 +00009392 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00009393 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009394
John Wiegley429bb272011-04-08 18:41:53 +00009395 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00009396 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00009397}
9398
John McCall60d7b3a2010-08-24 06:29:42 +00009399ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00009400 UnaryOperatorKind Opc,
9401 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00009402 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00009403 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009404 // Find all of the overloaded operators visible from this
9405 // point. We perform both an operator-name lookup from the local
9406 // scope and an argument-dependent lookup based on the types of
9407 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00009408 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009409 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00009410 if (S && OverOp != OO_None)
9411 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9412 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009413
John McCall9ae2f072010-08-23 23:25:46 +00009414 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009415 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009416
John McCall9ae2f072010-08-23 23:25:46 +00009417 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009418}
9419
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009420// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00009421ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00009422 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00009423 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009424}
9425
Steve Naroff1b273c42007-09-16 14:56:35 +00009426/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009427ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00009428 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009429 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00009430 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009431 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009432 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00009433}
9434
John McCallf85e1932011-06-15 23:02:42 +00009435/// Given the last statement in a statement-expression, check whether
9436/// the result is a producing expression (like a call to an
9437/// ns_returns_retained function) and, if so, rebuild it to hoist the
9438/// release out of the full-expression. Otherwise, return null.
9439/// Cannot fail.
9440static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
9441 // Should always be wrapped with one of these.
9442 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
9443 if (!cleanups) return 0;
9444
9445 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9446 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
9447 return 0;
9448
9449 // Splice out the cast. This shouldn't modify any interesting
9450 // features of the statement.
9451 Expr *producer = cast->getSubExpr();
9452 assert(producer->getType() == cast->getType());
9453 assert(producer->getValueKind() == cast->getValueKind());
9454 cleanups->setSubExpr(producer);
9455 return cleanups;
9456}
9457
John McCall60d7b3a2010-08-24 06:29:42 +00009458ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00009459Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009460 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009461 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9462 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9463
Douglas Gregordd8f5692010-03-10 04:54:39 +00009464 bool isFileScope
9465 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00009466 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00009467 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00009468
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009469 // FIXME: there are a variety of strange constraints to enforce here, for
9470 // example, it is not possible to goto into a stmt expression apparently.
9471 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009472
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009473 // If there are sub stmts in the compound stmt, take the type of the last one
9474 // as the type of the stmtexpr.
9475 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009476 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009477 if (!Compound->body_empty()) {
9478 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009479 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009480 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009481 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9482 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009483 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009484 }
John McCallf85e1932011-06-15 23:02:42 +00009485
John Wiegley429bb272011-04-08 18:41:53 +00009486 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00009487 // Do function/array conversion on the last expression, but not
9488 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00009489 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9490 if (LastExpr.isInvalid())
9491 return ExprError();
9492 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00009493
John Wiegley429bb272011-04-08 18:41:53 +00009494 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00009495 // In ARC, if the final expression ends in a consume, splice
9496 // the consume out and bind it later. In the alternate case
9497 // (when dealing with a retainable type), the result
9498 // initialization will create a produce. In both cases the
9499 // result will be +1, and we'll need to balance that out with
9500 // a bind.
9501 if (Expr *rebuiltLastStmt
9502 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9503 LastExpr = rebuiltLastStmt;
9504 } else {
9505 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009506 InitializedEntity::InitializeResult(LPLoc,
9507 Ty,
9508 false),
9509 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00009510 LastExpr);
9511 }
9512
John Wiegley429bb272011-04-08 18:41:53 +00009513 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009514 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009515 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009516 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00009517 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009518 else
John Wiegley429bb272011-04-08 18:41:53 +00009519 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009520 StmtExprMayBindToTemp = true;
9521 }
9522 }
9523 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00009524 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009525
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009526 // FIXME: Check that expression type is complete/non-abstract; statement
9527 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009528 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9529 if (StmtExprMayBindToTemp)
9530 return MaybeBindToTemporary(ResStmtExpr);
9531 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009532}
Steve Naroffd34e9152007-08-01 22:05:33 +00009533
John McCall60d7b3a2010-08-24 06:29:42 +00009534ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009535 TypeSourceInfo *TInfo,
9536 OffsetOfComponent *CompPtr,
9537 unsigned NumComponents,
9538 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009539 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009540 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009541 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009542
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009543 // We must have at least one component that refers to the type, and the first
9544 // one is known to be a field designator. Verify that the ArgTy represents
9545 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00009546 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009547 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9548 << ArgTy << TypeRange);
9549
9550 // Type must be complete per C99 7.17p3 because a declaring a variable
9551 // with an incomplete type would be ill-formed.
9552 if (!Dependent
9553 && RequireCompleteType(BuiltinLoc, ArgTy,
9554 PDiag(diag::err_offsetof_incomplete_type)
9555 << TypeRange))
9556 return ExprError();
9557
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009558 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9559 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009560 // FIXME: This diagnostic isn't actually visible because the location is in
9561 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009562 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009563 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9564 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009565
9566 bool DidWarnAboutNonPOD = false;
9567 QualType CurrentType = ArgTy;
9568 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9569 llvm::SmallVector<OffsetOfNode, 4> Comps;
9570 llvm::SmallVector<Expr*, 4> Exprs;
9571 for (unsigned i = 0; i != NumComponents; ++i) {
9572 const OffsetOfComponent &OC = CompPtr[i];
9573 if (OC.isBrackets) {
9574 // Offset of an array sub-field. TODO: Should we allow vector elements?
9575 if (!CurrentType->isDependentType()) {
9576 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9577 if(!AT)
9578 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9579 << CurrentType);
9580 CurrentType = AT->getElementType();
9581 } else
9582 CurrentType = Context.DependentTy;
9583
9584 // The expression must be an integral expression.
9585 // FIXME: An integral constant expression?
9586 Expr *Idx = static_cast<Expr*>(OC.U.E);
9587 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9588 !Idx->getType()->isIntegerType())
9589 return ExprError(Diag(Idx->getLocStart(),
9590 diag::err_typecheck_subscript_not_integer)
9591 << Idx->getSourceRange());
9592
9593 // Record this array index.
9594 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9595 Exprs.push_back(Idx);
9596 continue;
9597 }
9598
9599 // Offset of a field.
9600 if (CurrentType->isDependentType()) {
9601 // We have the offset of a field, but we can't look into the dependent
9602 // type. Just record the identifier of the field.
9603 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9604 CurrentType = Context.DependentTy;
9605 continue;
9606 }
9607
9608 // We need to have a complete type to look into.
9609 if (RequireCompleteType(OC.LocStart, CurrentType,
9610 diag::err_offsetof_incomplete_type))
9611 return ExprError();
9612
9613 // Look for the designated field.
9614 const RecordType *RC = CurrentType->getAs<RecordType>();
9615 if (!RC)
9616 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9617 << CurrentType);
9618 RecordDecl *RD = RC->getDecl();
9619
9620 // C++ [lib.support.types]p5:
9621 // The macro offsetof accepts a restricted set of type arguments in this
9622 // International Standard. type shall be a POD structure or a POD union
9623 // (clause 9).
9624 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9625 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009626 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009627 PDiag(diag::warn_offsetof_non_pod_type)
9628 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9629 << CurrentType))
9630 DidWarnAboutNonPOD = true;
9631 }
9632
9633 // Look for the field.
9634 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9635 LookupQualifiedName(R, RD);
9636 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009637 IndirectFieldDecl *IndirectMemberDecl = 0;
9638 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009639 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009640 MemberDecl = IndirectMemberDecl->getAnonField();
9641 }
9642
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009643 if (!MemberDecl)
9644 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9645 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9646 OC.LocEnd));
9647
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009648 // C99 7.17p3:
9649 // (If the specified member is a bit-field, the behavior is undefined.)
9650 //
9651 // We diagnose this as an error.
9652 if (MemberDecl->getBitWidth()) {
9653 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9654 << MemberDecl->getDeclName()
9655 << SourceRange(BuiltinLoc, RParenLoc);
9656 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9657 return ExprError();
9658 }
Eli Friedman19410a72010-08-05 10:11:36 +00009659
9660 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009661 if (IndirectMemberDecl)
9662 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009663
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009664 // If the member was found in a base class, introduce OffsetOfNodes for
9665 // the base class indirections.
9666 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9667 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009668 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009669 CXXBasePath &Path = Paths.front();
9670 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9671 B != BEnd; ++B)
9672 Comps.push_back(OffsetOfNode(B->Base));
9673 }
Eli Friedman19410a72010-08-05 10:11:36 +00009674
Francois Pichet87c2e122010-11-21 06:08:52 +00009675 if (IndirectMemberDecl) {
9676 for (IndirectFieldDecl::chain_iterator FI =
9677 IndirectMemberDecl->chain_begin(),
9678 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9679 assert(isa<FieldDecl>(*FI));
9680 Comps.push_back(OffsetOfNode(OC.LocStart,
9681 cast<FieldDecl>(*FI), OC.LocEnd));
9682 }
9683 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009684 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009685
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009686 CurrentType = MemberDecl->getType().getNonReferenceType();
9687 }
9688
9689 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9690 TInfo, Comps.data(), Comps.size(),
9691 Exprs.data(), Exprs.size(), RParenLoc));
9692}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009693
John McCall60d7b3a2010-08-24 06:29:42 +00009694ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009695 SourceLocation BuiltinLoc,
9696 SourceLocation TypeLoc,
9697 ParsedType argty,
9698 OffsetOfComponent *CompPtr,
9699 unsigned NumComponents,
9700 SourceLocation RPLoc) {
9701
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009702 TypeSourceInfo *ArgTInfo;
9703 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
9704 if (ArgTy.isNull())
9705 return ExprError();
9706
Eli Friedman5a15dc12010-08-05 10:15:45 +00009707 if (!ArgTInfo)
9708 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9709
9710 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9711 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009712}
9713
9714
John McCall60d7b3a2010-08-24 06:29:42 +00009715ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009716 Expr *CondExpr,
9717 Expr *LHSExpr, Expr *RHSExpr,
9718 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009719 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9720
John McCallf89e55a2010-11-18 06:31:45 +00009721 ExprValueKind VK = VK_RValue;
9722 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009723 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009724 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009725 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009726 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009727 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009728 } else {
9729 // The conditional expression is required to be a constant expression.
9730 llvm::APSInt condEval(32);
9731 SourceLocation ExpLoc;
9732 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00009733 return ExprError(Diag(ExpLoc,
9734 diag::err_typecheck_choose_expr_requires_constant)
9735 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00009736
Sebastian Redl28507842009-02-26 14:39:58 +00009737 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009738 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9739
9740 resType = ActiveExpr->getType();
9741 ValueDependent = ActiveExpr->isValueDependent();
9742 VK = ActiveExpr->getValueKind();
9743 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009744 }
9745
Sebastian Redlf53597f2009-03-15 17:47:39 +00009746 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009747 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009748 resType->isDependentType(),
9749 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009750}
9751
Steve Naroff4eb206b2008-09-03 18:15:37 +00009752//===----------------------------------------------------------------------===//
9753// Clang Extensions.
9754//===----------------------------------------------------------------------===//
9755
9756/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00009757void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009758 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9759 PushBlockScope(BlockScope, Block);
9760 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009761 if (BlockScope)
9762 PushDeclContext(BlockScope, Block);
9763 else
9764 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00009765}
9766
Mike Stump98eb8a72009-02-04 22:31:32 +00009767void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009768 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009769 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009770 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009771
John McCallbf1a0282010-06-04 23:28:52 +00009772 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009773 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009774
John McCall711c52b2011-01-05 12:14:39 +00009775 // GetTypeForDeclarator always produces a function type for a block
9776 // literal signature. Furthermore, it is always a FunctionProtoType
9777 // unless the function was written with a typedef.
9778 assert(T->isFunctionType() &&
9779 "GetTypeForDeclarator made a non-function block signature");
9780
9781 // Look for an explicit signature in that function type.
9782 FunctionProtoTypeLoc ExplicitSignature;
9783
9784 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9785 if (isa<FunctionProtoTypeLoc>(tmp)) {
9786 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9787
9788 // Check whether that explicit signature was synthesized by
9789 // GetTypeForDeclarator. If so, don't save that as part of the
9790 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009791 if (ExplicitSignature.getLocalRangeBegin() ==
9792 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009793 // This would be much cheaper if we stored TypeLocs instead of
9794 // TypeSourceInfos.
9795 TypeLoc Result = ExplicitSignature.getResultLoc();
9796 unsigned Size = Result.getFullDataSize();
9797 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9798 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9799
9800 ExplicitSignature = FunctionProtoTypeLoc();
9801 }
John McCall82dc0092010-06-04 11:21:44 +00009802 }
Mike Stump1eb44332009-09-09 15:08:12 +00009803
John McCall711c52b2011-01-05 12:14:39 +00009804 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9805 CurBlock->FunctionType = T;
9806
9807 const FunctionType *Fn = T->getAs<FunctionType>();
9808 QualType RetTy = Fn->getResultType();
9809 bool isVariadic =
9810 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9811
John McCallc71a4912010-06-04 19:02:56 +00009812 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009813
John McCall82dc0092010-06-04 11:21:44 +00009814 // Don't allow returning a objc interface by value.
9815 if (RetTy->isObjCObjectType()) {
9816 Diag(ParamInfo.getSourceRange().getBegin(),
9817 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9818 return;
9819 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009820
John McCall82dc0092010-06-04 11:21:44 +00009821 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009822 // return type. TODO: what should we do with declarators like:
9823 // ^ * { ... }
9824 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00009825 if (RetTy != Context.DependentTy)
9826 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009827
John McCall82dc0092010-06-04 11:21:44 +00009828 // Push block parameters from the declarator if we had them.
John McCallc71a4912010-06-04 19:02:56 +00009829 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009830 if (ExplicitSignature) {
9831 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9832 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009833 if (Param->getIdentifier() == 0 &&
9834 !Param->isImplicit() &&
9835 !Param->isInvalidDecl() &&
9836 !getLangOptions().CPlusPlus)
9837 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009838 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009839 }
John McCall82dc0092010-06-04 11:21:44 +00009840
9841 // Fake up parameter variables if we have a typedef, like
9842 // ^ fntype { ... }
9843 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9844 for (FunctionProtoType::arg_type_iterator
9845 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9846 ParmVarDecl *Param =
9847 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9848 ParamInfo.getSourceRange().getBegin(),
9849 *I);
John McCallc71a4912010-06-04 19:02:56 +00009850 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009851 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009852 }
John McCall82dc0092010-06-04 11:21:44 +00009853
John McCallc71a4912010-06-04 19:02:56 +00009854 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009855 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00009856 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00009857 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9858 CurBlock->TheDecl->param_end(),
9859 /*CheckParameterNames=*/false);
9860 }
9861
John McCall82dc0092010-06-04 11:21:44 +00009862 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009863 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009864
John McCallc71a4912010-06-04 19:02:56 +00009865 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00009866 Diag(ParamInfo.getAttributes()->getLoc(),
9867 diag::warn_attribute_sentinel_not_variadic) << 1;
9868 // FIXME: remove the attribute.
9869 }
9870
9871 // Put the parameter variables in scope. We can bail out immediately
9872 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009873 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009874 return;
9875
Steve Naroff090276f2008-10-10 01:28:17 +00009876 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009877 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9878 (*AI)->setOwningFunction(CurBlock->TheDecl);
9879
Steve Naroff090276f2008-10-10 01:28:17 +00009880 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009881 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009882 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009883
Steve Naroff090276f2008-10-10 01:28:17 +00009884 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009885 }
John McCall7a9813c2010-01-22 00:28:27 +00009886 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009887}
9888
9889/// ActOnBlockError - If there is an error parsing a block, this callback
9890/// is invoked to pop the information about the block from the action impl.
9891void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00009892 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009893 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009894 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009895}
9896
9897/// ActOnBlockStmtExpr - This is called when the body of a block statement
9898/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009899ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009900 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009901 // If blocks are disabled, emit an error.
9902 if (!LangOpts.Blocks)
9903 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009904
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009905 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009906
Steve Naroff090276f2008-10-10 01:28:17 +00009907 PopDeclContext();
9908
Steve Naroff4eb206b2008-09-03 18:15:37 +00009909 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009910 if (!BSI->ReturnType.isNull())
9911 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009912
Mike Stump56925862009-07-28 22:04:01 +00009913 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009914 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009915
John McCall469a1eb2011-02-02 13:00:07 +00009916 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00009917 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9918 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00009919
John McCallc71a4912010-06-04 19:02:56 +00009920 // If the user wrote a function type in some form, try to use that.
9921 if (!BSI->FunctionType.isNull()) {
9922 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9923
9924 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9925 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9926
9927 // Turn protoless block types into nullary block types.
9928 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009929 FunctionProtoType::ExtProtoInfo EPI;
9930 EPI.ExtInfo = Ext;
9931 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009932
9933 // Otherwise, if we don't need to change anything about the function type,
9934 // preserve its sugar structure.
9935 } else if (FTy->getResultType() == RetTy &&
9936 (!NoReturn || FTy->getNoReturnAttr())) {
9937 BlockTy = BSI->FunctionType;
9938
9939 // Otherwise, make the minimal modifications to the function type.
9940 } else {
9941 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009942 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9943 EPI.TypeQuals = 0; // FIXME: silently?
9944 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009945 BlockTy = Context.getFunctionType(RetTy,
9946 FPT->arg_type_begin(),
9947 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009948 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009949 }
9950
9951 // If we don't have a function type, just build one from nothing.
9952 } else {
John McCalle23cf432010-12-14 08:05:40 +00009953 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00009954 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00009955 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009956 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009957
John McCallc71a4912010-06-04 19:02:56 +00009958 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9959 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009960 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009961
Chris Lattner17a78302009-04-19 05:28:12 +00009962 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00009963 if (getCurFunction()->NeedsScopeChecking() &&
9964 !hasAnyUnrecoverableErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00009965 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009966
Chris Lattnere476bdc2011-02-17 23:58:47 +00009967 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009968
John McCall469a1eb2011-02-02 13:00:07 +00009969 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCalle0054f62010-08-25 05:56:39 +00009970
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009971 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9972 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009973 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009974}
9975
John McCall60d7b3a2010-08-24 06:29:42 +00009976ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00009977 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009978 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009979 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009980 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00009981 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009982}
9983
John McCall60d7b3a2010-08-24 06:29:42 +00009984ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009985 Expr *E, TypeSourceInfo *TInfo,
9986 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009987 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009988
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009989 // Get the va_list type
9990 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009991 if (VaListType->isArrayType()) {
9992 // Deal with implicit array decay; for example, on x86-64,
9993 // va_list is an array, but it's supposed to decay to
9994 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009995 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009996 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009997 ExprResult Result = UsualUnaryConversions(E);
9998 if (Result.isInvalid())
9999 return ExprError();
10000 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +000010001 } else {
10002 // Otherwise, the va_list argument must be an l-value because
10003 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +000010004 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +000010005 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +000010006 return ExprError();
10007 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +000010008
Douglas Gregordd027302009-05-19 23:10:31 +000010009 if (!E->isTypeDependent() &&
10010 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +000010011 return ExprError(Diag(E->getLocStart(),
10012 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +000010013 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +000010014 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010015
David Majnemer0adde122011-06-14 05:17:32 +000010016 if (!TInfo->getType()->isDependentType()) {
10017 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10018 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
10019 << TInfo->getTypeLoc().getSourceRange()))
10020 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +000010021
David Majnemer0adde122011-06-14 05:17:32 +000010022 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10023 TInfo->getType(),
10024 PDiag(diag::err_second_parameter_to_va_arg_abstract)
10025 << TInfo->getTypeLoc().getSourceRange()))
10026 return ExprError();
10027
John McCallf85e1932011-06-15 23:02:42 +000010028 if (!TInfo->getType().isPODType(Context))
David Majnemer0adde122011-06-14 05:17:32 +000010029 Diag(TInfo->getTypeLoc().getBeginLoc(),
10030 diag::warn_second_parameter_to_va_arg_not_pod)
10031 << TInfo->getType()
10032 << TInfo->getTypeLoc().getSourceRange();
10033 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010034
Abramo Bagnara2cad9002010-08-10 10:06:15 +000010035 QualType T = TInfo->getType().getNonLValueExprType(Context);
10036 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +000010037}
10038
John McCall60d7b3a2010-08-24 06:29:42 +000010039ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +000010040 // The type of __null will be int or long, depending on the size of
10041 // pointers on the target.
10042 QualType Ty;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +000010043 unsigned pw = Context.Target.getPointerWidth(0);
10044 if (pw == Context.Target.getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +000010045 Ty = Context.IntTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +000010046 else if (pw == Context.Target.getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +000010047 Ty = Context.LongTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +000010048 else if (pw == Context.Target.getLongLongWidth())
10049 Ty = Context.LongLongTy;
10050 else {
10051 assert(!"I don't know size of pointer!");
10052 Ty = Context.IntTy;
10053 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +000010054
Sebastian Redlf53597f2009-03-15 17:47:39 +000010055 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +000010056}
10057
Sean Hunt1e3f5ba2010-04-28 23:02:27 +000010058static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +000010059 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000010060 if (!SemaRef.getLangOptions().ObjC1)
10061 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010062
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000010063 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10064 if (!PT)
10065 return;
10066
10067 // Check if the destination is of type 'id'.
10068 if (!PT->isObjCIdType()) {
10069 // Check if the destination is the 'NSString' interface.
10070 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10071 if (!ID || !ID->getIdentifier()->isStr("NSString"))
10072 return;
10073 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010074
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000010075 // Strip off any parens and casts.
10076 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
10077 if (!SL || SL->isWide())
10078 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010079
Douglas Gregor849b2432010-03-31 17:46:05 +000010080 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000010081}
10082
Chris Lattner5cf216b2008-01-04 18:04:52 +000010083bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10084 SourceLocation Loc,
10085 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +000010086 Expr *SrcExpr, AssignmentAction Action,
10087 bool *Complained) {
10088 if (Complained)
10089 *Complained = false;
10090
Chris Lattner5cf216b2008-01-04 18:04:52 +000010091 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +000010092 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010093 bool isInvalid = false;
10094 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +000010095 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010096
Chris Lattner5cf216b2008-01-04 18:04:52 +000010097 switch (ConvTy) {
10098 default: assert(0 && "Unknown conversion type");
10099 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +000010100 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +000010101 DiagKind = diag::ext_typecheck_convert_pointer_int;
10102 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +000010103 case IntToPointer:
10104 DiagKind = diag::ext_typecheck_convert_int_pointer;
10105 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010106 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +000010107 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +000010108 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +000010109 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10110 SrcType->isObjCObjectPointerType();
Chris Lattner5cf216b2008-01-04 18:04:52 +000010111 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +000010112 case IncompatiblePointerSign:
10113 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10114 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010115 case FunctionVoidPointer:
10116 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10117 break;
John McCall86c05f32011-02-01 00:10:29 +000010118 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +000010119 // Perform array-to-pointer decay if necessary.
10120 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10121
John McCall86c05f32011-02-01 00:10:29 +000010122 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10123 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10124 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10125 DiagKind = diag::err_typecheck_incompatible_address_space;
10126 break;
John McCallf85e1932011-06-15 23:02:42 +000010127
10128
10129 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10130 DiagKind = diag::err_typecheck_incompatible_lifetime;
10131 break;
John McCall86c05f32011-02-01 00:10:29 +000010132 }
10133
10134 llvm_unreachable("unknown error case for discarding qualifiers!");
10135 // fallthrough
10136 }
Chris Lattner5cf216b2008-01-04 18:04:52 +000010137 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +000010138 // If the qualifiers lost were because we were applying the
10139 // (deprecated) C++ conversion from a string literal to a char*
10140 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
10141 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +000010142 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +000010143 // bit of refactoring (so that the second argument is an
10144 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +000010145 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +000010146 // C++ semantics.
10147 if (getLangOptions().CPlusPlus &&
10148 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10149 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010150 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10151 break;
Sean Huntc9132b62009-11-08 07:46:34 +000010152 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +000010153 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +000010154 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +000010155 case IntToBlockPointer:
10156 DiagKind = diag::err_int_to_block_pointer;
10157 break;
10158 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +000010159 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +000010160 break;
Steve Naroff39579072008-10-14 22:18:38 +000010161 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +000010162 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +000010163 // it can give a more specific diagnostic.
10164 DiagKind = diag::warn_incompatible_qualified_id;
10165 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +000010166 case IncompatibleVectors:
10167 DiagKind = diag::warn_incompatible_vectors;
10168 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010169 case Incompatible:
10170 DiagKind = diag::err_typecheck_convert_incompatible;
10171 isInvalid = true;
10172 break;
10173 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010174
Douglas Gregord4eea832010-04-09 00:35:39 +000010175 QualType FirstType, SecondType;
10176 switch (Action) {
10177 case AA_Assigning:
10178 case AA_Initializing:
10179 // The destination type comes first.
10180 FirstType = DstType;
10181 SecondType = SrcType;
10182 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +000010183
Douglas Gregord4eea832010-04-09 00:35:39 +000010184 case AA_Returning:
10185 case AA_Passing:
10186 case AA_Converting:
10187 case AA_Sending:
10188 case AA_Casting:
10189 // The source type comes first.
10190 FirstType = SrcType;
10191 SecondType = DstType;
10192 break;
10193 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +000010194
Douglas Gregord4eea832010-04-09 00:35:39 +000010195 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000010196 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor926df6c2011-06-11 01:09:30 +000010197 if (CheckInferredResultType)
10198 EmitRelatedResultTypeNote(SrcExpr);
10199
Douglas Gregora41a8c52010-04-22 00:20:18 +000010200 if (Complained)
10201 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010202 return isInvalid;
10203}
Anders Carlssone21555e2008-11-30 19:50:32 +000010204
Chris Lattner3bf68932009-04-25 21:59:05 +000010205bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +000010206 llvm::APSInt ICEResult;
10207 if (E->isIntegerConstantExpr(ICEResult, Context)) {
10208 if (Result)
10209 *Result = ICEResult;
10210 return false;
10211 }
10212
Anders Carlssone21555e2008-11-30 19:50:32 +000010213 Expr::EvalResult EvalResult;
10214
Mike Stumpeed9cac2009-02-19 03:04:26 +000010215 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +000010216 EvalResult.HasSideEffects) {
10217 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
10218
10219 if (EvalResult.Diag) {
10220 // We only show the note if it's not the usual "invalid subexpression"
10221 // or if it's actually in a subexpression.
10222 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
10223 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
10224 Diag(EvalResult.DiagLoc, EvalResult.Diag);
10225 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010226
Anders Carlssone21555e2008-11-30 19:50:32 +000010227 return true;
10228 }
10229
Eli Friedman3b5ccca2009-04-25 22:26:58 +000010230 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
10231 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +000010232
Eli Friedman3b5ccca2009-04-25 22:26:58 +000010233 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +000010234 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
10235 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +000010236 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +000010237
Anders Carlssone21555e2008-11-30 19:50:32 +000010238 if (Result)
10239 *Result = EvalResult.Val.getInt();
10240 return false;
10241}
Douglas Gregore0762c92009-06-19 23:52:42 +000010242
Douglas Gregor2afce722009-11-26 00:44:06 +000010243void
Mike Stump1eb44332009-09-09 15:08:12 +000010244Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010245 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +000010246 ExpressionEvaluationContextRecord(NewContext,
10247 ExprTemporaries.size(),
10248 ExprNeedsCleanups));
10249 ExprNeedsCleanups = false;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010250}
10251
Mike Stump1eb44332009-09-09 15:08:12 +000010252void
Douglas Gregor2afce722009-11-26 00:44:06 +000010253Sema::PopExpressionEvaluationContext() {
10254 // Pop the current expression evaluation context off the stack.
10255 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
10256 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010257
Douglas Gregor06d33692009-12-12 07:57:52 +000010258 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
10259 if (Rec.PotentiallyReferenced) {
10260 // Mark any remaining declarations in the current position of the stack
10261 // as "referenced". If they were not meant to be referenced, semantic
10262 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010263 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +000010264 I = Rec.PotentiallyReferenced->begin(),
10265 IEnd = Rec.PotentiallyReferenced->end();
10266 I != IEnd; ++I)
10267 MarkDeclarationReferenced(I->first, I->second);
10268 }
10269
10270 if (Rec.PotentiallyDiagnosed) {
10271 // Emit any pending diagnostics.
10272 for (PotentiallyEmittedDiagnostics::iterator
10273 I = Rec.PotentiallyDiagnosed->begin(),
10274 IEnd = Rec.PotentiallyDiagnosed->end();
10275 I != IEnd; ++I)
10276 Diag(I->first, I->second);
10277 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010278 }
Douglas Gregor2afce722009-11-26 00:44:06 +000010279
10280 // When are coming out of an unevaluated context, clear out any
10281 // temporaries that we may have created as part of the evaluation of
10282 // the expression in that context: they aren't relevant because they
10283 // will never be constructed.
John McCallf85e1932011-06-15 23:02:42 +000010284 if (Rec.Context == Unevaluated) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010285 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
10286 ExprTemporaries.end());
John McCallf85e1932011-06-15 23:02:42 +000010287 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10288
10289 // Otherwise, merge the contexts together.
10290 } else {
10291 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10292 }
Douglas Gregor2afce722009-11-26 00:44:06 +000010293
10294 // Destroy the popped expression evaluation record.
10295 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010296}
Douglas Gregore0762c92009-06-19 23:52:42 +000010297
John McCallf85e1932011-06-15 23:02:42 +000010298void Sema::DiscardCleanupsInEvaluationContext() {
10299 ExprTemporaries.erase(
10300 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
10301 ExprTemporaries.end());
10302 ExprNeedsCleanups = false;
10303}
10304
Douglas Gregore0762c92009-06-19 23:52:42 +000010305/// \brief Note that the given declaration was referenced in the source code.
10306///
10307/// This routine should be invoke whenever a given declaration is referenced
10308/// in the source code, and where that reference occurred. If this declaration
10309/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
10310/// C99 6.9p3), then the declaration will be marked as used.
10311///
10312/// \param Loc the location where the declaration was referenced.
10313///
10314/// \param D the declaration that has been referenced by the source code.
10315void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
10316 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +000010317
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +000010318 D->setReferenced();
10319
Douglas Gregorc070cc62010-06-17 23:14:26 +000010320 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +000010321 return;
Mike Stump1eb44332009-09-09 15:08:12 +000010322
Douglas Gregorb5352cf2009-10-08 21:35:42 +000010323 // Mark a parameter or variable declaration "used", regardless of whether we're in a
10324 // template or not. The reason for this is that unevaluated expressions
10325 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
10326 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010327 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +000010328 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +000010329 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +000010330 return;
10331 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +000010332
Douglas Gregorfc2ca562010-04-07 20:29:57 +000010333 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
10334 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +000010335
Douglas Gregore0762c92009-06-19 23:52:42 +000010336 // Do not mark anything as "used" within a dependent context; wait for
10337 // an instantiation.
10338 if (CurContext->isDependentContext())
10339 return;
Mike Stump1eb44332009-09-09 15:08:12 +000010340
Douglas Gregor2afce722009-11-26 00:44:06 +000010341 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000010342 case Unevaluated:
10343 // We are in an expression that is not potentially evaluated; do nothing.
10344 return;
Mike Stump1eb44332009-09-09 15:08:12 +000010345
Douglas Gregorac7610d2009-06-22 20:57:11 +000010346 case PotentiallyEvaluated:
10347 // We are in a potentially-evaluated expression, so this declaration is
10348 // "used"; handle this below.
10349 break;
Mike Stump1eb44332009-09-09 15:08:12 +000010350
Douglas Gregorac7610d2009-06-22 20:57:11 +000010351 case PotentiallyPotentiallyEvaluated:
10352 // We are in an expression that may be potentially evaluated; queue this
10353 // declaration reference until we know whether the expression is
10354 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +000010355 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +000010356 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010357
10358 case PotentiallyEvaluatedIfUsed:
10359 // Referenced declarations will only be used if the construct in the
10360 // containing expression is used.
10361 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010362 }
Mike Stump1eb44332009-09-09 15:08:12 +000010363
Douglas Gregore0762c92009-06-19 23:52:42 +000010364 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +000010365 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sean Hunt1e238652011-05-12 03:51:51 +000010366 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
10367 if (Constructor->isTrivial())
Chandler Carruth4e6fbce2010-08-23 07:55:51 +000010368 return;
10369 if (!Constructor->isUsed(false))
10370 DefineImplicitDefaultConstructor(Loc, Constructor);
Sean Hunt509f0482011-05-14 18:20:50 +000010371 } else if (Constructor->isDefaulted() &&
Sean Hunt49634cf2011-05-13 06:10:58 +000010372 Constructor->isCopyConstructor()) {
Douglas Gregorc070cc62010-06-17 23:14:26 +000010373 if (!Constructor->isUsed(false))
Sean Hunt49634cf2011-05-13 06:10:58 +000010374 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010375 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010376
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010377 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010378 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Sean Huntcb45a0f2011-05-12 22:46:25 +000010379 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010380 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010381 if (Destructor->isVirtual())
10382 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010383 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Sean Hunt2b188082011-05-14 05:23:28 +000010384 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010385 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +000010386 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +000010387 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010388 } else if (MethodDecl->isVirtual())
10389 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010390 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +000010391 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +000010392 // Recursive functions should be marked when used from another function.
10393 if (CurContext == Function) return;
10394
Mike Stump1eb44332009-09-09 15:08:12 +000010395 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +000010396 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +000010397 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010398 bool AlreadyInstantiated = false;
10399 if (FunctionTemplateSpecializationInfo *SpecInfo
10400 = Function->getTemplateSpecializationInfo()) {
10401 if (SpecInfo->getPointOfInstantiation().isInvalid())
10402 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010403 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +000010404 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010405 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010406 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010407 = Function->getMemberSpecializationInfo()) {
10408 if (MSInfo->getPointOfInstantiation().isInvalid())
10409 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010410 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +000010411 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010412 AlreadyInstantiated = true;
10413 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010414
Douglas Gregor60406be2010-01-16 22:29:39 +000010415 if (!AlreadyInstantiated) {
10416 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
10417 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
10418 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
10419 Loc));
10420 else
Chandler Carruth62c78d52010-08-25 08:44:16 +000010421 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +000010422 }
John McCall15e310a2011-02-19 02:53:41 +000010423 } else {
10424 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +000010425 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
10426 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +000010427 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +000010428 MarkDeclarationReferenced(Loc, *i);
10429 }
John McCall15e310a2011-02-19 02:53:41 +000010430 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010431
John McCall15e310a2011-02-19 02:53:41 +000010432 // Keep track of used but undefined functions.
10433 if (!Function->isPure() && !Function->hasBody() &&
10434 Function->getLinkage() != ExternalLinkage) {
10435 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
10436 if (old.isInvalid()) old = Loc;
10437 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +000010438
John McCall15e310a2011-02-19 02:53:41 +000010439 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +000010440 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +000010441 }
Mike Stump1eb44332009-09-09 15:08:12 +000010442
Douglas Gregore0762c92009-06-19 23:52:42 +000010443 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +000010444 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +000010445 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010446 Var->getInstantiatedFromStaticDataMember()) {
10447 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10448 assert(MSInfo && "Missing member specialization information?");
10449 if (MSInfo->getPointOfInstantiation().isInvalid() &&
10450 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
10451 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redlf79a7192011-04-29 08:19:30 +000010452 // This is a modification of an existing AST node. Notify listeners.
10453 if (ASTMutationListener *L = getASTMutationListener())
10454 L->StaticDataMemberInstantiated(Var);
Chandler Carruth62c78d52010-08-25 08:44:16 +000010455 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010456 }
10457 }
Mike Stump1eb44332009-09-09 15:08:12 +000010458
John McCall77efc682011-02-21 19:25:48 +000010459 // Keep track of used but undefined variables. We make a hole in
10460 // the warning for static const data members with in-line
10461 // initializers.
John McCall15e310a2011-02-19 02:53:41 +000010462 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +000010463 && Var->getLinkage() != ExternalLinkage
10464 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +000010465 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
10466 if (old.isInvalid()) old = Loc;
10467 }
Douglas Gregor7caa6822009-07-24 20:34:43 +000010468
Douglas Gregore0762c92009-06-19 23:52:42 +000010469 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +000010470 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010471 }
Douglas Gregore0762c92009-06-19 23:52:42 +000010472}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010473
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010474namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010475 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010476 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010477 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010478 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10479 Sema &S;
10480 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010481
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010482 public:
10483 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010484
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010485 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010486
10487 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10488 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010489 };
10490}
10491
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010492bool MarkReferencedDecls::TraverseTemplateArgument(
10493 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010494 if (Arg.getKind() == TemplateArgument::Declaration) {
10495 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
10496 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010497
10498 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010499}
10500
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010501bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010502 if (ClassTemplateSpecializationDecl *Spec
10503 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10504 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000010505 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010506 }
10507
Chandler Carruthe3e210c2010-06-10 10:31:57 +000010508 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010509}
10510
10511void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10512 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010513 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010514}
10515
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010516namespace {
10517 /// \brief Helper class that marks all of the declarations referenced by
10518 /// potentially-evaluated subexpressions as "referenced".
10519 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10520 Sema &S;
10521
10522 public:
10523 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10524
10525 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
10526
10527 void VisitDeclRefExpr(DeclRefExpr *E) {
10528 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10529 }
10530
10531 void VisitMemberExpr(MemberExpr *E) {
10532 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010533 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010534 }
10535
10536 void VisitCXXNewExpr(CXXNewExpr *E) {
10537 if (E->getConstructor())
10538 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
10539 if (E->getOperatorNew())
10540 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
10541 if (E->getOperatorDelete())
10542 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010543 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010544 }
10545
10546 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10547 if (E->getOperatorDelete())
10548 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000010549 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10550 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10551 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10552 S.MarkDeclarationReferenced(E->getLocStart(),
10553 S.LookupDestructor(Record));
10554 }
10555
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010556 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010557 }
10558
10559 void VisitCXXConstructExpr(CXXConstructExpr *E) {
10560 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010561 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010562 }
10563
10564 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
10565 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10566 }
Douglas Gregor102ff972010-10-19 17:17:35 +000010567
10568 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10569 Visit(E->getExpr());
10570 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010571 };
10572}
10573
10574/// \brief Mark any declarations that appear within this expression or any
10575/// potentially-evaluated subexpressions as "referenced".
10576void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
10577 EvaluatedExprMarker(*this).Visit(E);
10578}
10579
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010580/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10581/// of the program being compiled.
10582///
10583/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010584/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010585/// possibility that the code will actually be executable. Code in sizeof()
10586/// expressions, code used only during overload resolution, etc., are not
10587/// potentially evaluated. This routine will suppress such diagnostics or,
10588/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010589/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010590/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010591///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010592/// This routine should be used for all diagnostics that describe the run-time
10593/// behavior of a program, such as passing a non-POD value through an ellipsis.
10594/// Failure to do so will likely result in spurious diagnostics or failures
10595/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek762696f2011-02-23 01:51:43 +000010596bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010597 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +000010598 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010599 case Unevaluated:
10600 // The argument will never be evaluated, so don't complain.
10601 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010602
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010603 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010604 case PotentiallyEvaluatedIfUsed:
Ted Kremenek351ba912011-02-23 01:52:04 +000010605 if (stmt && getCurFunctionOrMethodDecl()) {
10606 FunctionScopes.back()->PossiblyUnreachableDiags.
10607 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
10608 }
10609 else
10610 Diag(Loc, PD);
10611
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010612 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010613
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010614 case PotentiallyPotentiallyEvaluated:
10615 ExprEvalContexts.back().addDiagnostic(Loc, PD);
10616 break;
10617 }
10618
10619 return false;
10620}
10621
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010622bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10623 CallExpr *CE, FunctionDecl *FD) {
10624 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10625 return false;
10626
10627 PartialDiagnostic Note =
10628 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10629 << FD->getDeclName() : PDiag();
10630 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010631
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010632 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010633 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010634 PDiag(diag::err_call_function_incomplete_return)
10635 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010636 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010637 << CE->getSourceRange(),
10638 std::make_pair(NoteLoc, Note)))
10639 return true;
10640
10641 return false;
10642}
10643
Douglas Gregor92c3a042011-01-19 16:50:08 +000010644// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000010645// will prevent this condition from triggering, which is what we want.
10646void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10647 SourceLocation Loc;
10648
John McCalla52ef082009-11-11 02:41:58 +000010649 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000010650 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000010651
John McCall5a881bb2009-10-12 21:59:07 +000010652 if (isa<BinaryOperator>(E)) {
10653 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +000010654 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000010655 return;
10656
Douglas Gregor92c3a042011-01-19 16:50:08 +000010657 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10658
John McCallc8d8ac52009-11-12 00:06:05 +000010659 // Greylist some idioms by putting them into a warning subcategory.
10660 if (ObjCMessageExpr *ME
10661 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10662 Selector Sel = ME->getSelector();
10663
John McCallc8d8ac52009-11-12 00:06:05 +000010664 // self = [<foo> init...]
Douglas Gregor813d8342011-02-18 22:29:55 +000010665 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000010666 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10667
10668 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000010669 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000010670 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10671 }
John McCalla52ef082009-11-11 02:41:58 +000010672
John McCall5a881bb2009-10-12 21:59:07 +000010673 Loc = Op->getOperatorLoc();
10674 } else if (isa<CXXOperatorCallExpr>(E)) {
10675 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +000010676 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000010677 return;
10678
Douglas Gregor92c3a042011-01-19 16:50:08 +000010679 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000010680 Loc = Op->getOperatorLoc();
10681 } else {
10682 // Not an assignment.
10683 return;
10684 }
10685
Douglas Gregor55b38842010-04-14 16:09:52 +000010686 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000010687
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000010688 SourceLocation Open = E->getSourceRange().getBegin();
10689 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10690 Diag(Loc, diag::note_condition_assign_silence)
10691 << FixItHint::CreateInsertion(Open, "(")
10692 << FixItHint::CreateInsertion(Close, ")");
10693
Douglas Gregor92c3a042011-01-19 16:50:08 +000010694 if (IsOrAssign)
10695 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10696 << FixItHint::CreateReplacement(Loc, "!=");
10697 else
10698 Diag(Loc, diag::note_condition_assign_to_comparison)
10699 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000010700}
10701
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010702/// \brief Redundant parentheses over an equality comparison can indicate
10703/// that the user intended an assignment used as condition.
10704void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000010705 // Don't warn if the parens came from a macro.
10706 SourceLocation parenLoc = parenE->getLocStart();
10707 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10708 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000010709 // Don't warn for dependent expressions.
10710 if (parenE->isTypeDependent())
10711 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000010712
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010713 Expr *E = parenE->IgnoreParens();
10714
10715 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000010716 if (opE->getOpcode() == BO_EQ &&
10717 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10718 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010719 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000010720
Ted Kremenekf7275cd2011-02-02 02:20:30 +000010721 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000010722 Diag(Loc, diag::note_equality_comparison_silence)
10723 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
10724 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000010725 Diag(Loc, diag::note_equality_comparison_to_assign)
10726 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010727 }
10728}
10729
John Wiegley429bb272011-04-08 18:41:53 +000010730ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000010731 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010732 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10733 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000010734
John McCall864c0412011-04-26 20:42:42 +000010735 ExprResult result = CheckPlaceholderExpr(E);
10736 if (result.isInvalid()) return ExprError();
10737 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000010738
John McCall864c0412011-04-26 20:42:42 +000010739 if (!E->isTypeDependent()) {
John McCallf6a16482010-12-04 03:47:34 +000010740 if (getLangOptions().CPlusPlus)
10741 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10742
John Wiegley429bb272011-04-08 18:41:53 +000010743 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10744 if (ERes.isInvalid())
10745 return ExprError();
10746 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000010747
10748 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000010749 if (!T->isScalarType()) { // C99 6.8.4.1p1
10750 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10751 << T << E->getSourceRange();
10752 return ExprError();
10753 }
John McCall5a881bb2009-10-12 21:59:07 +000010754 }
10755
John Wiegley429bb272011-04-08 18:41:53 +000010756 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000010757}
Douglas Gregor586596f2010-05-06 17:25:47 +000010758
John McCall60d7b3a2010-08-24 06:29:42 +000010759ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10760 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +000010761 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +000010762 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010763
10764 return CheckBooleanCondition(Sub, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000010765}
John McCall2a984ca2010-10-12 00:20:44 +000010766
John McCall1de4d4e2011-04-07 08:22:57 +000010767namespace {
John McCall755d8492011-04-12 00:42:48 +000010768 /// A visitor for rebuilding a call to an __unknown_any expression
10769 /// to have an appropriate type.
10770 struct RebuildUnknownAnyFunction
10771 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10772
10773 Sema &S;
10774
10775 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10776
10777 ExprResult VisitStmt(Stmt *S) {
10778 llvm_unreachable("unexpected statement!");
10779 return ExprError();
10780 }
10781
10782 ExprResult VisitExpr(Expr *expr) {
10783 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
10784 << expr->getSourceRange();
10785 return ExprError();
10786 }
10787
10788 /// Rebuild an expression which simply semantically wraps another
10789 /// expression which it shares the type and value kind of.
10790 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10791 ExprResult subResult = Visit(expr->getSubExpr());
10792 if (subResult.isInvalid()) return ExprError();
10793
10794 Expr *subExpr = subResult.take();
10795 expr->setSubExpr(subExpr);
10796 expr->setType(subExpr->getType());
10797 expr->setValueKind(subExpr->getValueKind());
10798 assert(expr->getObjectKind() == OK_Ordinary);
10799 return expr;
10800 }
10801
10802 ExprResult VisitParenExpr(ParenExpr *paren) {
10803 return rebuildSugarExpr(paren);
10804 }
10805
10806 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10807 return rebuildSugarExpr(op);
10808 }
10809
10810 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10811 ExprResult subResult = Visit(op->getSubExpr());
10812 if (subResult.isInvalid()) return ExprError();
10813
10814 Expr *subExpr = subResult.take();
10815 op->setSubExpr(subExpr);
10816 op->setType(S.Context.getPointerType(subExpr->getType()));
10817 assert(op->getValueKind() == VK_RValue);
10818 assert(op->getObjectKind() == OK_Ordinary);
10819 return op;
10820 }
10821
10822 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
10823 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
10824
10825 expr->setType(decl->getType());
10826
10827 assert(expr->getValueKind() == VK_RValue);
10828 if (S.getLangOptions().CPlusPlus &&
10829 !(isa<CXXMethodDecl>(decl) &&
10830 cast<CXXMethodDecl>(decl)->isInstance()))
10831 expr->setValueKind(VK_LValue);
10832
10833 return expr;
10834 }
10835
10836 ExprResult VisitMemberExpr(MemberExpr *mem) {
10837 return resolveDecl(mem, mem->getMemberDecl());
10838 }
10839
10840 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10841 return resolveDecl(ref, ref->getDecl());
10842 }
10843 };
10844}
10845
10846/// Given a function expression of unknown-any type, try to rebuild it
10847/// to have a function type.
10848static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
10849 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
10850 if (result.isInvalid()) return ExprError();
10851 return S.DefaultFunctionArrayConversion(result.take());
10852}
10853
10854namespace {
John McCall379b5152011-04-11 07:02:50 +000010855 /// A visitor for rebuilding an expression of type __unknown_anytype
10856 /// into one which resolves the type directly on the referring
10857 /// expression. Strict preservation of the original source
10858 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000010859 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000010860 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000010861
10862 Sema &S;
10863
10864 /// The current destination type.
10865 QualType DestType;
10866
10867 RebuildUnknownAnyExpr(Sema &S, QualType castType)
10868 : S(S), DestType(castType) {}
10869
John McCalla5fc4722011-04-09 22:50:59 +000010870 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000010871 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +000010872 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010873 }
10874
John McCall379b5152011-04-11 07:02:50 +000010875 ExprResult VisitExpr(Expr *expr) {
10876 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10877 << expr->getSourceRange();
10878 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010879 }
10880
John McCall379b5152011-04-11 07:02:50 +000010881 ExprResult VisitCallExpr(CallExpr *call);
10882 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
10883
John McCalla5fc4722011-04-09 22:50:59 +000010884 /// Rebuild an expression which simply semantically wraps another
10885 /// expression which it shares the type and value kind of.
10886 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10887 ExprResult subResult = Visit(expr->getSubExpr());
John McCall755d8492011-04-12 00:42:48 +000010888 if (subResult.isInvalid()) return ExprError();
John McCalla5fc4722011-04-09 22:50:59 +000010889 Expr *subExpr = subResult.take();
10890 expr->setSubExpr(subExpr);
10891 expr->setType(subExpr->getType());
10892 expr->setValueKind(subExpr->getValueKind());
10893 assert(expr->getObjectKind() == OK_Ordinary);
10894 return expr;
10895 }
John McCall1de4d4e2011-04-07 08:22:57 +000010896
John McCalla5fc4722011-04-09 22:50:59 +000010897 ExprResult VisitParenExpr(ParenExpr *paren) {
10898 return rebuildSugarExpr(paren);
10899 }
10900
10901 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10902 return rebuildSugarExpr(op);
10903 }
10904
John McCall755d8492011-04-12 00:42:48 +000010905 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10906 const PointerType *ptr = DestType->getAs<PointerType>();
10907 if (!ptr) {
10908 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
10909 << op->getSourceRange();
10910 return ExprError();
10911 }
10912 assert(op->getValueKind() == VK_RValue);
10913 assert(op->getObjectKind() == OK_Ordinary);
10914 op->setType(DestType);
10915
10916 // Build the sub-expression as if it were an object of the pointee type.
10917 DestType = ptr->getPointeeType();
10918 ExprResult subResult = Visit(op->getSubExpr());
10919 if (subResult.isInvalid()) return ExprError();
10920 op->setSubExpr(subResult.take());
10921 return op;
10922 }
10923
John McCall379b5152011-04-11 07:02:50 +000010924 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCalla5fc4722011-04-09 22:50:59 +000010925
John McCall755d8492011-04-12 00:42:48 +000010926 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCalla5fc4722011-04-09 22:50:59 +000010927
John McCall755d8492011-04-12 00:42:48 +000010928 ExprResult VisitMemberExpr(MemberExpr *mem) {
10929 return resolveDecl(mem, mem->getMemberDecl());
10930 }
John McCalla5fc4722011-04-09 22:50:59 +000010931
10932 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall379b5152011-04-11 07:02:50 +000010933 return resolveDecl(ref, ref->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000010934 }
10935 };
10936}
10937
John McCall379b5152011-04-11 07:02:50 +000010938/// Rebuilds a call expression which yielded __unknown_anytype.
10939ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
10940 Expr *callee = call->getCallee();
10941
10942 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000010943 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000010944 FK_FunctionPointer,
10945 FK_BlockPointer
10946 };
10947
10948 FnKind kind;
10949 QualType type = callee->getType();
John McCallf5307512011-04-27 00:36:17 +000010950 if (type == S.Context.BoundMemberTy) {
10951 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
10952 kind = FK_MemberFunction;
10953 type = Expr::findBoundMemberType(callee);
John McCall379b5152011-04-11 07:02:50 +000010954 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
10955 type = ptr->getPointeeType();
10956 kind = FK_FunctionPointer;
10957 } else {
10958 type = type->castAs<BlockPointerType>()->getPointeeType();
10959 kind = FK_BlockPointer;
10960 }
10961 const FunctionType *fnType = type->castAs<FunctionType>();
10962
10963 // Verify that this is a legal result type of a function.
10964 if (DestType->isArrayType() || DestType->isFunctionType()) {
10965 unsigned diagID = diag::err_func_returning_array_function;
10966 if (kind == FK_BlockPointer)
10967 diagID = diag::err_block_returning_array_function;
10968
10969 S.Diag(call->getExprLoc(), diagID)
10970 << DestType->isFunctionType() << DestType;
10971 return ExprError();
10972 }
10973
10974 // Otherwise, go ahead and set DestType as the call's result.
10975 call->setType(DestType.getNonLValueExprType(S.Context));
10976 call->setValueKind(Expr::getValueKindForType(DestType));
10977 assert(call->getObjectKind() == OK_Ordinary);
10978
10979 // Rebuild the function type, replacing the result type with DestType.
10980 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
10981 DestType = S.Context.getFunctionType(DestType,
10982 proto->arg_type_begin(),
10983 proto->getNumArgs(),
10984 proto->getExtProtoInfo());
10985 else
10986 DestType = S.Context.getFunctionNoProtoType(DestType,
10987 fnType->getExtInfo());
10988
10989 // Rebuild the appropriate pointer-to-function type.
10990 switch (kind) {
John McCallf5307512011-04-27 00:36:17 +000010991 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000010992 // Nothing to do.
10993 break;
10994
10995 case FK_FunctionPointer:
10996 DestType = S.Context.getPointerType(DestType);
10997 break;
10998
10999 case FK_BlockPointer:
11000 DestType = S.Context.getBlockPointerType(DestType);
11001 break;
11002 }
11003
11004 // Finally, we can recurse.
11005 ExprResult calleeResult = Visit(callee);
11006 if (!calleeResult.isUsable()) return ExprError();
11007 call->setCallee(calleeResult.take());
11008
11009 // Bind a temporary if necessary.
11010 return S.MaybeBindToTemporary(call);
11011}
11012
11013ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall755d8492011-04-12 00:42:48 +000011014 ObjCMethodDecl *method = msg->getMethodDecl();
11015 assert(method && "__unknown_anytype message without result type?");
John McCall379b5152011-04-11 07:02:50 +000011016
John McCall755d8492011-04-12 00:42:48 +000011017 // Verify that this is a legal result type of a call.
11018 if (DestType->isArrayType() || DestType->isFunctionType()) {
11019 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
11020 << DestType->isFunctionType() << DestType;
11021 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011022 }
11023
John McCall755d8492011-04-12 00:42:48 +000011024 assert(method->getResultType() == S.Context.UnknownAnyTy);
11025 method->setResultType(DestType);
11026
John McCall379b5152011-04-11 07:02:50 +000011027 // Change the type of the message.
John McCall755d8492011-04-12 00:42:48 +000011028 msg->setType(DestType.getNonReferenceType());
11029 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000011030
John McCall755d8492011-04-12 00:42:48 +000011031 return S.MaybeBindToTemporary(msg);
John McCall379b5152011-04-11 07:02:50 +000011032}
11033
11034ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall755d8492011-04-12 00:42:48 +000011035 // The only case we should ever see here is a function-to-pointer decay.
John McCall379b5152011-04-11 07:02:50 +000011036 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall379b5152011-04-11 07:02:50 +000011037 assert(ice->getValueKind() == VK_RValue);
11038 assert(ice->getObjectKind() == OK_Ordinary);
11039
John McCall755d8492011-04-12 00:42:48 +000011040 ice->setType(DestType);
11041
John McCall379b5152011-04-11 07:02:50 +000011042 // Rebuild the sub-expression as the pointee (function) type.
11043 DestType = DestType->castAs<PointerType>()->getPointeeType();
11044
11045 ExprResult result = Visit(ice->getSubExpr());
11046 if (!result.isUsable()) return ExprError();
11047
11048 ice->setSubExpr(result.take());
11049 return S.Owned(ice);
11050}
11051
John McCall755d8492011-04-12 00:42:48 +000011052ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall379b5152011-04-11 07:02:50 +000011053 ExprValueKind valueKind = VK_LValue;
John McCall379b5152011-04-11 07:02:50 +000011054 QualType type = DestType;
11055
11056 // We know how to make this work for certain kinds of decls:
11057
11058 // - functions
John McCall755d8492011-04-12 00:42:48 +000011059 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall379b5152011-04-11 07:02:50 +000011060 // This is true because FunctionDecls must always have function
11061 // type, so we can't be resolving the entire thing at once.
11062 assert(type->isFunctionType());
11063
John McCallf5307512011-04-27 00:36:17 +000011064 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
11065 if (method->isInstance()) {
11066 valueKind = VK_RValue;
11067 type = S.Context.BoundMemberTy;
11068 }
11069
John McCall379b5152011-04-11 07:02:50 +000011070 // Function references aren't l-values in C.
11071 if (!S.getLangOptions().CPlusPlus)
11072 valueKind = VK_RValue;
11073
11074 // - variables
11075 } else if (isa<VarDecl>(decl)) {
John McCall755d8492011-04-12 00:42:48 +000011076 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
11077 type = refTy->getPointeeType();
John McCall379b5152011-04-11 07:02:50 +000011078 } else if (type->isFunctionType()) {
John McCall755d8492011-04-12 00:42:48 +000011079 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
11080 << decl << expr->getSourceRange();
11081 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011082 }
11083
11084 // - nothing else
11085 } else {
11086 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11087 << decl << expr->getSourceRange();
11088 return ExprError();
11089 }
11090
John McCall755d8492011-04-12 00:42:48 +000011091 decl->setType(DestType);
11092 expr->setType(type);
11093 expr->setValueKind(valueKind);
11094 return S.Owned(expr);
John McCall379b5152011-04-11 07:02:50 +000011095}
11096
John McCall1de4d4e2011-04-07 08:22:57 +000011097/// Check a cast of an unknown-any type. We intentionally only
11098/// trigger this for C-style casts.
John Wiegley429bb272011-04-08 18:41:53 +000011099ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
11100 Expr *castExpr, CastKind &castKind,
11101 ExprValueKind &VK, CXXCastPath &path) {
John McCall1de4d4e2011-04-07 08:22:57 +000011102 // Rewrite the casted expression from scratch.
John McCalla5fc4722011-04-09 22:50:59 +000011103 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
11104 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011105
John McCalla5fc4722011-04-09 22:50:59 +000011106 castExpr = result.take();
11107 VK = castExpr->getValueKind();
11108 castKind = CK_NoOp;
11109
11110 return castExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000011111}
11112
11113static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
11114 Expr *orig = e;
John McCall379b5152011-04-11 07:02:50 +000011115 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000011116 while (true) {
11117 e = e->IgnoreParenImpCasts();
John McCall379b5152011-04-11 07:02:50 +000011118 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall1de4d4e2011-04-07 08:22:57 +000011119 e = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011120 diagID = diag::err_uncasted_call_of_unknown_any;
11121 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000011122 break;
John McCall379b5152011-04-11 07:02:50 +000011123 }
John McCall1de4d4e2011-04-07 08:22:57 +000011124 }
11125
John McCall379b5152011-04-11 07:02:50 +000011126 SourceLocation loc;
11127 NamedDecl *d;
11128 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11129 loc = ref->getLocation();
11130 d = ref->getDecl();
11131 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
11132 loc = mem->getMemberLoc();
11133 d = mem->getMemberDecl();
11134 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
11135 diagID = diag::err_uncasted_call_of_unknown_any;
11136 loc = msg->getSelectorLoc();
11137 d = msg->getMethodDecl();
11138 assert(d && "unknown method returning __unknown_any?");
11139 } else {
11140 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11141 << e->getSourceRange();
11142 return ExprError();
11143 }
11144
11145 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000011146
11147 // Never recoverable.
11148 return ExprError();
11149}
11150
John McCall2a984ca2010-10-12 00:20:44 +000011151/// Check for operands with placeholder types and complain if found.
11152/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000011153ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall1de4d4e2011-04-07 08:22:57 +000011154 // Placeholder types are always *exactly* the appropriate builtin type.
11155 QualType type = E->getType();
John McCall2a984ca2010-10-12 00:20:44 +000011156
John McCall1de4d4e2011-04-07 08:22:57 +000011157 // Overloaded expressions.
11158 if (type == Context.OverloadTy)
11159 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregordb2eae62011-03-16 19:16:25 +000011160 E->getSourceRange(),
John McCall1de4d4e2011-04-07 08:22:57 +000011161 QualType(),
11162 diag::err_ovl_unresolvable);
11163
John McCall864c0412011-04-26 20:42:42 +000011164 // Bound member functions.
11165 if (type == Context.BoundMemberTy) {
11166 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
11167 << E->getSourceRange();
11168 return ExprError();
11169 }
11170
John McCall1de4d4e2011-04-07 08:22:57 +000011171 // Expressions of unknown type.
11172 if (type == Context.UnknownAnyTy)
11173 return diagnoseUnknownAnyExpr(*this, E);
11174
11175 assert(!type->isPlaceholderType());
11176 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +000011177}
Richard Trieubb9b80c2011-04-21 21:44:26 +000011178
11179bool Sema::CheckCaseExpression(Expr *expr) {
11180 if (expr->isTypeDependent())
11181 return true;
11182 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
11183 return expr->getType()->isIntegralOrEnumerationType();
11184 return false;
11185}